tests.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. import pickle
  2. from io import BytesIO
  3. from itertools import chain
  4. from urllib.parse import urlencode
  5. from django.core.exceptions import DisallowedHost
  6. from django.core.handlers.wsgi import LimitedStream, WSGIRequest
  7. from django.http import (
  8. HttpHeaders,
  9. HttpRequest,
  10. RawPostDataException,
  11. UnreadablePostError,
  12. )
  13. from django.http.multipartparser import MultiPartParserError
  14. from django.http.request import split_domain_port
  15. from django.test import RequestFactory, SimpleTestCase, override_settings
  16. from django.test.client import FakePayload
  17. class RequestsTests(SimpleTestCase):
  18. def test_httprequest(self):
  19. request = HttpRequest()
  20. self.assertEqual(list(request.GET), [])
  21. self.assertEqual(list(request.POST), [])
  22. self.assertEqual(list(request.COOKIES), [])
  23. self.assertEqual(list(request.META), [])
  24. # .GET and .POST should be QueryDicts
  25. self.assertEqual(request.GET.urlencode(), "")
  26. self.assertEqual(request.POST.urlencode(), "")
  27. # and FILES should be MultiValueDict
  28. self.assertEqual(request.FILES.getlist("foo"), [])
  29. self.assertIsNone(request.content_type)
  30. self.assertIsNone(request.content_params)
  31. def test_httprequest_full_path(self):
  32. request = HttpRequest()
  33. request.path = "/;some/?awful/=path/foo:bar/"
  34. request.path_info = "/prefix" + request.path
  35. request.META["QUERY_STRING"] = ";some=query&+query=string"
  36. expected = "/%3Bsome/%3Fawful/%3Dpath/foo:bar/?;some=query&+query=string"
  37. self.assertEqual(request.get_full_path(), expected)
  38. self.assertEqual(request.get_full_path_info(), "/prefix" + expected)
  39. def test_httprequest_full_path_with_query_string_and_fragment(self):
  40. request = HttpRequest()
  41. request.path = "/foo#bar"
  42. request.path_info = "/prefix" + request.path
  43. request.META["QUERY_STRING"] = "baz#quux"
  44. self.assertEqual(request.get_full_path(), "/foo%23bar?baz#quux")
  45. self.assertEqual(request.get_full_path_info(), "/prefix/foo%23bar?baz#quux")
  46. def test_httprequest_repr(self):
  47. request = HttpRequest()
  48. request.path = "/somepath/"
  49. request.method = "GET"
  50. request.GET = {"get-key": "get-value"}
  51. request.POST = {"post-key": "post-value"}
  52. request.COOKIES = {"post-key": "post-value"}
  53. request.META = {"post-key": "post-value"}
  54. self.assertEqual(repr(request), "<HttpRequest: GET '/somepath/'>")
  55. def test_httprequest_repr_invalid_method_and_path(self):
  56. request = HttpRequest()
  57. self.assertEqual(repr(request), "<HttpRequest>")
  58. request = HttpRequest()
  59. request.method = "GET"
  60. self.assertEqual(repr(request), "<HttpRequest>")
  61. request = HttpRequest()
  62. request.path = ""
  63. self.assertEqual(repr(request), "<HttpRequest>")
  64. def test_wsgirequest(self):
  65. request = WSGIRequest(
  66. {
  67. "PATH_INFO": "bogus",
  68. "REQUEST_METHOD": "bogus",
  69. "CONTENT_TYPE": "text/html; charset=utf8",
  70. "wsgi.input": BytesIO(b""),
  71. }
  72. )
  73. self.assertEqual(list(request.GET), [])
  74. self.assertEqual(list(request.POST), [])
  75. self.assertEqual(list(request.COOKIES), [])
  76. self.assertEqual(
  77. set(request.META),
  78. {
  79. "PATH_INFO",
  80. "REQUEST_METHOD",
  81. "SCRIPT_NAME",
  82. "CONTENT_TYPE",
  83. "wsgi.input",
  84. },
  85. )
  86. self.assertEqual(request.META["PATH_INFO"], "bogus")
  87. self.assertEqual(request.META["REQUEST_METHOD"], "bogus")
  88. self.assertEqual(request.META["SCRIPT_NAME"], "")
  89. self.assertEqual(request.content_type, "text/html")
  90. self.assertEqual(request.content_params, {"charset": "utf8"})
  91. def test_wsgirequest_with_script_name(self):
  92. """
  93. The request's path is correctly assembled, regardless of whether or
  94. not the SCRIPT_NAME has a trailing slash (#20169).
  95. """
  96. # With trailing slash
  97. request = WSGIRequest(
  98. {
  99. "PATH_INFO": "/somepath/",
  100. "SCRIPT_NAME": "/PREFIX/",
  101. "REQUEST_METHOD": "get",
  102. "wsgi.input": BytesIO(b""),
  103. }
  104. )
  105. self.assertEqual(request.path, "/PREFIX/somepath/")
  106. # Without trailing slash
  107. request = WSGIRequest(
  108. {
  109. "PATH_INFO": "/somepath/",
  110. "SCRIPT_NAME": "/PREFIX",
  111. "REQUEST_METHOD": "get",
  112. "wsgi.input": BytesIO(b""),
  113. }
  114. )
  115. self.assertEqual(request.path, "/PREFIX/somepath/")
  116. def test_wsgirequest_script_url_double_slashes(self):
  117. """
  118. WSGI squashes multiple successive slashes in PATH_INFO, WSGIRequest
  119. should take that into account when populating request.path and
  120. request.META['SCRIPT_NAME'] (#17133).
  121. """
  122. request = WSGIRequest(
  123. {
  124. "SCRIPT_URL": "/mst/milestones//accounts/login//help",
  125. "PATH_INFO": "/milestones/accounts/login/help",
  126. "REQUEST_METHOD": "get",
  127. "wsgi.input": BytesIO(b""),
  128. }
  129. )
  130. self.assertEqual(request.path, "/mst/milestones/accounts/login/help")
  131. self.assertEqual(request.META["SCRIPT_NAME"], "/mst")
  132. def test_wsgirequest_with_force_script_name(self):
  133. """
  134. The FORCE_SCRIPT_NAME setting takes precedence over the request's
  135. SCRIPT_NAME environment parameter (#20169).
  136. """
  137. with override_settings(FORCE_SCRIPT_NAME="/FORCED_PREFIX/"):
  138. request = WSGIRequest(
  139. {
  140. "PATH_INFO": "/somepath/",
  141. "SCRIPT_NAME": "/PREFIX/",
  142. "REQUEST_METHOD": "get",
  143. "wsgi.input": BytesIO(b""),
  144. }
  145. )
  146. self.assertEqual(request.path, "/FORCED_PREFIX/somepath/")
  147. def test_wsgirequest_path_with_force_script_name_trailing_slash(self):
  148. """
  149. The request's path is correctly assembled, regardless of whether or not
  150. the FORCE_SCRIPT_NAME setting has a trailing slash (#20169).
  151. """
  152. # With trailing slash
  153. with override_settings(FORCE_SCRIPT_NAME="/FORCED_PREFIX/"):
  154. request = WSGIRequest(
  155. {
  156. "PATH_INFO": "/somepath/",
  157. "REQUEST_METHOD": "get",
  158. "wsgi.input": BytesIO(b""),
  159. }
  160. )
  161. self.assertEqual(request.path, "/FORCED_PREFIX/somepath/")
  162. # Without trailing slash
  163. with override_settings(FORCE_SCRIPT_NAME="/FORCED_PREFIX"):
  164. request = WSGIRequest(
  165. {
  166. "PATH_INFO": "/somepath/",
  167. "REQUEST_METHOD": "get",
  168. "wsgi.input": BytesIO(b""),
  169. }
  170. )
  171. self.assertEqual(request.path, "/FORCED_PREFIX/somepath/")
  172. def test_wsgirequest_repr(self):
  173. request = WSGIRequest({"REQUEST_METHOD": "get", "wsgi.input": BytesIO(b"")})
  174. self.assertEqual(repr(request), "<WSGIRequest: GET '/'>")
  175. request = WSGIRequest(
  176. {
  177. "PATH_INFO": "/somepath/",
  178. "REQUEST_METHOD": "get",
  179. "wsgi.input": BytesIO(b""),
  180. }
  181. )
  182. request.GET = {"get-key": "get-value"}
  183. request.POST = {"post-key": "post-value"}
  184. request.COOKIES = {"post-key": "post-value"}
  185. request.META = {"post-key": "post-value"}
  186. self.assertEqual(repr(request), "<WSGIRequest: GET '/somepath/'>")
  187. def test_wsgirequest_path_info(self):
  188. def wsgi_str(path_info, encoding="utf-8"):
  189. path_info = path_info.encode(
  190. encoding
  191. ) # Actual URL sent by the browser (bytestring)
  192. path_info = path_info.decode(
  193. "iso-8859-1"
  194. ) # Value in the WSGI environ dict (native string)
  195. return path_info
  196. # Regression for #19468
  197. request = WSGIRequest(
  198. {
  199. "PATH_INFO": wsgi_str("/سلام/"),
  200. "REQUEST_METHOD": "get",
  201. "wsgi.input": BytesIO(b""),
  202. }
  203. )
  204. self.assertEqual(request.path, "/سلام/")
  205. # The URL may be incorrectly encoded in a non-UTF-8 encoding (#26971)
  206. request = WSGIRequest(
  207. {
  208. "PATH_INFO": wsgi_str("/café/", encoding="iso-8859-1"),
  209. "REQUEST_METHOD": "get",
  210. "wsgi.input": BytesIO(b""),
  211. }
  212. )
  213. # Since it's impossible to decide the (wrong) encoding of the URL, it's
  214. # left percent-encoded in the path.
  215. self.assertEqual(request.path, "/caf%E9/")
  216. def test_limited_stream(self):
  217. # Read all of a limited stream
  218. stream = LimitedStream(BytesIO(b"test"), 2)
  219. self.assertEqual(stream.read(), b"te")
  220. # Reading again returns nothing.
  221. self.assertEqual(stream.read(), b"")
  222. # Read a number of characters greater than the stream has to offer
  223. stream = LimitedStream(BytesIO(b"test"), 2)
  224. self.assertEqual(stream.read(5), b"te")
  225. # Reading again returns nothing.
  226. self.assertEqual(stream.readline(5), b"")
  227. # Read sequentially from a stream
  228. stream = LimitedStream(BytesIO(b"12345678"), 8)
  229. self.assertEqual(stream.read(5), b"12345")
  230. self.assertEqual(stream.read(5), b"678")
  231. # Reading again returns nothing.
  232. self.assertEqual(stream.readline(5), b"")
  233. # Read lines from a stream
  234. stream = LimitedStream(BytesIO(b"1234\n5678\nabcd\nefgh\nijkl"), 24)
  235. # Read a full line, unconditionally
  236. self.assertEqual(stream.readline(), b"1234\n")
  237. # Read a number of characters less than a line
  238. self.assertEqual(stream.readline(2), b"56")
  239. # Read the rest of the partial line
  240. self.assertEqual(stream.readline(), b"78\n")
  241. # Read a full line, with a character limit greater than the line length
  242. self.assertEqual(stream.readline(6), b"abcd\n")
  243. # Read the next line, deliberately terminated at the line end
  244. self.assertEqual(stream.readline(4), b"efgh")
  245. # Read the next line... just the line end
  246. self.assertEqual(stream.readline(), b"\n")
  247. # Read everything else.
  248. self.assertEqual(stream.readline(), b"ijkl")
  249. # Regression for #15018
  250. # If a stream contains a newline, but the provided length
  251. # is less than the number of provided characters, the newline
  252. # doesn't reset the available character count
  253. stream = LimitedStream(BytesIO(b"1234\nabcdef"), 9)
  254. self.assertEqual(stream.readline(10), b"1234\n")
  255. self.assertEqual(stream.readline(3), b"abc")
  256. # Now expire the available characters
  257. self.assertEqual(stream.readline(3), b"d")
  258. # Reading again returns nothing.
  259. self.assertEqual(stream.readline(2), b"")
  260. # Same test, but with read, not readline.
  261. stream = LimitedStream(BytesIO(b"1234\nabcdef"), 9)
  262. self.assertEqual(stream.read(6), b"1234\na")
  263. self.assertEqual(stream.read(2), b"bc")
  264. self.assertEqual(stream.read(2), b"d")
  265. self.assertEqual(stream.read(2), b"")
  266. self.assertEqual(stream.read(), b"")
  267. def test_stream(self):
  268. payload = FakePayload("name=value")
  269. request = WSGIRequest(
  270. {
  271. "REQUEST_METHOD": "POST",
  272. "CONTENT_TYPE": "application/x-www-form-urlencoded",
  273. "CONTENT_LENGTH": len(payload),
  274. "wsgi.input": payload,
  275. },
  276. )
  277. self.assertEqual(request.read(), b"name=value")
  278. def test_read_after_value(self):
  279. """
  280. Reading from request is allowed after accessing request contents as
  281. POST or body.
  282. """
  283. payload = FakePayload("name=value")
  284. request = WSGIRequest(
  285. {
  286. "REQUEST_METHOD": "POST",
  287. "CONTENT_TYPE": "application/x-www-form-urlencoded",
  288. "CONTENT_LENGTH": len(payload),
  289. "wsgi.input": payload,
  290. }
  291. )
  292. self.assertEqual(request.POST, {"name": ["value"]})
  293. self.assertEqual(request.body, b"name=value")
  294. self.assertEqual(request.read(), b"name=value")
  295. def test_value_after_read(self):
  296. """
  297. Construction of POST or body is not allowed after reading
  298. from request.
  299. """
  300. payload = FakePayload("name=value")
  301. request = WSGIRequest(
  302. {
  303. "REQUEST_METHOD": "POST",
  304. "CONTENT_TYPE": "application/x-www-form-urlencoded",
  305. "CONTENT_LENGTH": len(payload),
  306. "wsgi.input": payload,
  307. }
  308. )
  309. self.assertEqual(request.read(2), b"na")
  310. with self.assertRaises(RawPostDataException):
  311. request.body
  312. self.assertEqual(request.POST, {})
  313. def test_non_ascii_POST(self):
  314. payload = FakePayload(urlencode({"key": "España"}))
  315. request = WSGIRequest(
  316. {
  317. "REQUEST_METHOD": "POST",
  318. "CONTENT_LENGTH": len(payload),
  319. "CONTENT_TYPE": "application/x-www-form-urlencoded",
  320. "wsgi.input": payload,
  321. }
  322. )
  323. self.assertEqual(request.POST, {"key": ["España"]})
  324. def test_alternate_charset_POST(self):
  325. """
  326. Test a POST with non-utf-8 payload encoding.
  327. """
  328. payload = FakePayload(urlencode({"key": "España".encode("latin-1")}))
  329. request = WSGIRequest(
  330. {
  331. "REQUEST_METHOD": "POST",
  332. "CONTENT_LENGTH": len(payload),
  333. "CONTENT_TYPE": "application/x-www-form-urlencoded; charset=iso-8859-1",
  334. "wsgi.input": payload,
  335. }
  336. )
  337. self.assertEqual(request.POST, {"key": ["España"]})
  338. def test_body_after_POST_multipart_form_data(self):
  339. """
  340. Reading body after parsing multipart/form-data is not allowed
  341. """
  342. # Because multipart is used for large amounts of data i.e. file uploads,
  343. # we don't want the data held in memory twice, and we don't want to
  344. # silence the error by setting body = '' either.
  345. payload = FakePayload(
  346. "\r\n".join(
  347. [
  348. "--boundary",
  349. 'Content-Disposition: form-data; name="name"',
  350. "",
  351. "value",
  352. "--boundary--",
  353. ]
  354. )
  355. )
  356. request = WSGIRequest(
  357. {
  358. "REQUEST_METHOD": "POST",
  359. "CONTENT_TYPE": "multipart/form-data; boundary=boundary",
  360. "CONTENT_LENGTH": len(payload),
  361. "wsgi.input": payload,
  362. }
  363. )
  364. self.assertEqual(request.POST, {"name": ["value"]})
  365. with self.assertRaises(RawPostDataException):
  366. request.body
  367. def test_body_after_POST_multipart_related(self):
  368. """
  369. Reading body after parsing multipart that isn't form-data is allowed
  370. """
  371. # Ticket #9054
  372. # There are cases in which the multipart data is related instead of
  373. # being a binary upload, in which case it should still be accessible
  374. # via body.
  375. payload_data = b"\r\n".join(
  376. [
  377. b"--boundary",
  378. b'Content-ID: id; name="name"',
  379. b"",
  380. b"value",
  381. b"--boundary--",
  382. ]
  383. )
  384. payload = FakePayload(payload_data)
  385. request = WSGIRequest(
  386. {
  387. "REQUEST_METHOD": "POST",
  388. "CONTENT_TYPE": "multipart/related; boundary=boundary",
  389. "CONTENT_LENGTH": len(payload),
  390. "wsgi.input": payload,
  391. }
  392. )
  393. self.assertEqual(request.POST, {})
  394. self.assertEqual(request.body, payload_data)
  395. def test_POST_multipart_with_content_length_zero(self):
  396. """
  397. Multipart POST requests with Content-Length >= 0 are valid and need to
  398. be handled.
  399. """
  400. # According to RFC 9110 Section 8.6 every POST with Content-Length >= 0
  401. # is a valid request, so ensure that we handle Content-Length == 0.
  402. payload = FakePayload(
  403. "\r\n".join(
  404. [
  405. "--boundary",
  406. 'Content-Disposition: form-data; name="name"',
  407. "",
  408. "value",
  409. "--boundary--",
  410. ]
  411. )
  412. )
  413. request = WSGIRequest(
  414. {
  415. "REQUEST_METHOD": "POST",
  416. "CONTENT_TYPE": "multipart/form-data; boundary=boundary",
  417. "CONTENT_LENGTH": 0,
  418. "wsgi.input": payload,
  419. }
  420. )
  421. self.assertEqual(request.POST, {})
  422. def test_POST_binary_only(self):
  423. payload = b"\r\n\x01\x00\x00\x00ab\x00\x00\xcd\xcc,@"
  424. environ = {
  425. "REQUEST_METHOD": "POST",
  426. "CONTENT_TYPE": "application/octet-stream",
  427. "CONTENT_LENGTH": len(payload),
  428. "wsgi.input": BytesIO(payload),
  429. }
  430. request = WSGIRequest(environ)
  431. self.assertEqual(request.POST, {})
  432. self.assertEqual(request.FILES, {})
  433. self.assertEqual(request.body, payload)
  434. # Same test without specifying content-type
  435. environ.update({"CONTENT_TYPE": "", "wsgi.input": BytesIO(payload)})
  436. request = WSGIRequest(environ)
  437. self.assertEqual(request.POST, {})
  438. self.assertEqual(request.FILES, {})
  439. self.assertEqual(request.body, payload)
  440. def test_read_by_lines(self):
  441. payload = FakePayload("name=value")
  442. request = WSGIRequest(
  443. {
  444. "REQUEST_METHOD": "POST",
  445. "CONTENT_TYPE": "application/x-www-form-urlencoded",
  446. "CONTENT_LENGTH": len(payload),
  447. "wsgi.input": payload,
  448. }
  449. )
  450. self.assertEqual(list(request), [b"name=value"])
  451. def test_POST_after_body_read(self):
  452. """
  453. POST should be populated even if body is read first
  454. """
  455. payload = FakePayload("name=value")
  456. request = WSGIRequest(
  457. {
  458. "REQUEST_METHOD": "POST",
  459. "CONTENT_TYPE": "application/x-www-form-urlencoded",
  460. "CONTENT_LENGTH": len(payload),
  461. "wsgi.input": payload,
  462. }
  463. )
  464. request.body # evaluate
  465. self.assertEqual(request.POST, {"name": ["value"]})
  466. def test_POST_after_body_read_and_stream_read(self):
  467. """
  468. POST should be populated even if body is read first, and then
  469. the stream is read second.
  470. """
  471. payload = FakePayload("name=value")
  472. request = WSGIRequest(
  473. {
  474. "REQUEST_METHOD": "POST",
  475. "CONTENT_TYPE": "application/x-www-form-urlencoded",
  476. "CONTENT_LENGTH": len(payload),
  477. "wsgi.input": payload,
  478. }
  479. )
  480. request.body # evaluate
  481. self.assertEqual(request.read(1), b"n")
  482. self.assertEqual(request.POST, {"name": ["value"]})
  483. def test_POST_after_body_read_and_stream_read_multipart(self):
  484. """
  485. POST should be populated even if body is read first, and then
  486. the stream is read second. Using multipart/form-data instead of urlencoded.
  487. """
  488. payload = FakePayload(
  489. "\r\n".join(
  490. [
  491. "--boundary",
  492. 'Content-Disposition: form-data; name="name"',
  493. "",
  494. "value",
  495. "--boundary--" "",
  496. ]
  497. )
  498. )
  499. request = WSGIRequest(
  500. {
  501. "REQUEST_METHOD": "POST",
  502. "CONTENT_TYPE": "multipart/form-data; boundary=boundary",
  503. "CONTENT_LENGTH": len(payload),
  504. "wsgi.input": payload,
  505. }
  506. )
  507. request.body # evaluate
  508. # Consume enough data to mess up the parsing:
  509. self.assertEqual(request.read(13), b"--boundary\r\nC")
  510. self.assertEqual(request.POST, {"name": ["value"]})
  511. def test_POST_immutable_for_multipart(self):
  512. """
  513. MultiPartParser.parse() leaves request.POST immutable.
  514. """
  515. payload = FakePayload(
  516. "\r\n".join(
  517. [
  518. "--boundary",
  519. 'Content-Disposition: form-data; name="name"',
  520. "",
  521. "value",
  522. "--boundary--",
  523. ]
  524. )
  525. )
  526. request = WSGIRequest(
  527. {
  528. "REQUEST_METHOD": "POST",
  529. "CONTENT_TYPE": "multipart/form-data; boundary=boundary",
  530. "CONTENT_LENGTH": len(payload),
  531. "wsgi.input": payload,
  532. }
  533. )
  534. self.assertFalse(request.POST._mutable)
  535. def test_multipart_without_boundary(self):
  536. request = WSGIRequest(
  537. {
  538. "REQUEST_METHOD": "POST",
  539. "CONTENT_TYPE": "multipart/form-data;",
  540. "CONTENT_LENGTH": 0,
  541. "wsgi.input": FakePayload(),
  542. }
  543. )
  544. with self.assertRaisesMessage(
  545. MultiPartParserError, "Invalid boundary in multipart: None"
  546. ):
  547. request.POST
  548. def test_multipart_non_ascii_content_type(self):
  549. request = WSGIRequest(
  550. {
  551. "REQUEST_METHOD": "POST",
  552. "CONTENT_TYPE": "multipart/form-data; boundary = \xe0",
  553. "CONTENT_LENGTH": 0,
  554. "wsgi.input": FakePayload(),
  555. }
  556. )
  557. msg = (
  558. "Invalid non-ASCII Content-Type in multipart: multipart/form-data; "
  559. "boundary = à"
  560. )
  561. with self.assertRaisesMessage(MultiPartParserError, msg):
  562. request.POST
  563. def test_POST_connection_error(self):
  564. """
  565. If wsgi.input.read() raises an exception while trying to read() the
  566. POST, the exception is identifiable (not a generic OSError).
  567. """
  568. class ExplodingBytesIO(BytesIO):
  569. def read(self, len=0):
  570. raise OSError("kaboom!")
  571. payload = b"name=value"
  572. request = WSGIRequest(
  573. {
  574. "REQUEST_METHOD": "POST",
  575. "CONTENT_TYPE": "application/x-www-form-urlencoded",
  576. "CONTENT_LENGTH": len(payload),
  577. "wsgi.input": ExplodingBytesIO(payload),
  578. }
  579. )
  580. with self.assertRaises(UnreadablePostError):
  581. request.body
  582. def test_set_encoding_clears_POST(self):
  583. payload = FakePayload("name=Hello Günter")
  584. request = WSGIRequest(
  585. {
  586. "REQUEST_METHOD": "POST",
  587. "CONTENT_TYPE": "application/x-www-form-urlencoded",
  588. "CONTENT_LENGTH": len(payload),
  589. "wsgi.input": payload,
  590. }
  591. )
  592. self.assertEqual(request.POST, {"name": ["Hello Günter"]})
  593. request.encoding = "iso-8859-16"
  594. self.assertEqual(request.POST, {"name": ["Hello GĂŒnter"]})
  595. def test_set_encoding_clears_GET(self):
  596. request = WSGIRequest(
  597. {
  598. "REQUEST_METHOD": "GET",
  599. "wsgi.input": "",
  600. "QUERY_STRING": "name=Hello%20G%C3%BCnter",
  601. }
  602. )
  603. self.assertEqual(request.GET, {"name": ["Hello Günter"]})
  604. request.encoding = "iso-8859-16"
  605. self.assertEqual(request.GET, {"name": ["Hello G\u0102\u0152nter"]})
  606. def test_FILES_connection_error(self):
  607. """
  608. If wsgi.input.read() raises an exception while trying to read() the
  609. FILES, the exception is identifiable (not a generic OSError).
  610. """
  611. class ExplodingBytesIO(BytesIO):
  612. def read(self, len=0):
  613. raise OSError("kaboom!")
  614. payload = b"x"
  615. request = WSGIRequest(
  616. {
  617. "REQUEST_METHOD": "POST",
  618. "CONTENT_TYPE": "multipart/form-data; boundary=foo_",
  619. "CONTENT_LENGTH": len(payload),
  620. "wsgi.input": ExplodingBytesIO(payload),
  621. }
  622. )
  623. with self.assertRaises(UnreadablePostError):
  624. request.FILES
  625. def test_pickling_request(self):
  626. request = HttpRequest()
  627. request.method = "GET"
  628. request.path = "/testpath/"
  629. request.META = {
  630. "QUERY_STRING": ";some=query&+query=string",
  631. "SERVER_NAME": "example.com",
  632. "SERVER_PORT": 80,
  633. }
  634. request.COOKIES = {"post-key": "post-value"}
  635. dump = pickle.dumps(request)
  636. request_from_pickle = pickle.loads(dump)
  637. self.assertEqual(repr(request), repr(request_from_pickle))
  638. class HostValidationTests(SimpleTestCase):
  639. poisoned_hosts = [
  640. "example.com@evil.tld",
  641. "example.com:dr.frankenstein@evil.tld",
  642. "example.com:dr.frankenstein@evil.tld:80",
  643. "example.com:80/badpath",
  644. "example.com: recovermypassword.com",
  645. ]
  646. @override_settings(
  647. USE_X_FORWARDED_HOST=False,
  648. ALLOWED_HOSTS=[
  649. "forward.com",
  650. "example.com",
  651. "internal.com",
  652. "12.34.56.78",
  653. "[2001:19f0:feee::dead:beef:cafe]",
  654. "xn--4ca9at.com",
  655. ".multitenant.com",
  656. "INSENSITIVE.com",
  657. "[::ffff:169.254.169.254]",
  658. ],
  659. )
  660. def test_http_get_host(self):
  661. # Check if X_FORWARDED_HOST is provided.
  662. request = HttpRequest()
  663. request.META = {
  664. "HTTP_X_FORWARDED_HOST": "forward.com",
  665. "HTTP_HOST": "example.com",
  666. "SERVER_NAME": "internal.com",
  667. "SERVER_PORT": 80,
  668. }
  669. # X_FORWARDED_HOST is ignored.
  670. self.assertEqual(request.get_host(), "example.com")
  671. # Check if X_FORWARDED_HOST isn't provided.
  672. request = HttpRequest()
  673. request.META = {
  674. "HTTP_HOST": "example.com",
  675. "SERVER_NAME": "internal.com",
  676. "SERVER_PORT": 80,
  677. }
  678. self.assertEqual(request.get_host(), "example.com")
  679. # Check if HTTP_HOST isn't provided.
  680. request = HttpRequest()
  681. request.META = {
  682. "SERVER_NAME": "internal.com",
  683. "SERVER_PORT": 80,
  684. }
  685. self.assertEqual(request.get_host(), "internal.com")
  686. # Check if HTTP_HOST isn't provided, and we're on a nonstandard port
  687. request = HttpRequest()
  688. request.META = {
  689. "SERVER_NAME": "internal.com",
  690. "SERVER_PORT": 8042,
  691. }
  692. self.assertEqual(request.get_host(), "internal.com:8042")
  693. legit_hosts = [
  694. "example.com",
  695. "example.com:80",
  696. "12.34.56.78",
  697. "12.34.56.78:443",
  698. "[2001:19f0:feee::dead:beef:cafe]",
  699. "[2001:19f0:feee::dead:beef:cafe]:8080",
  700. "xn--4ca9at.com", # Punycode for öäü.com
  701. "anything.multitenant.com",
  702. "multitenant.com",
  703. "insensitive.com",
  704. "example.com.",
  705. "example.com.:80",
  706. "[::ffff:169.254.169.254]",
  707. ]
  708. for host in legit_hosts:
  709. request = HttpRequest()
  710. request.META = {
  711. "HTTP_HOST": host,
  712. }
  713. request.get_host()
  714. # Poisoned host headers are rejected as suspicious
  715. for host in chain(self.poisoned_hosts, ["other.com", "example.com.."]):
  716. with self.assertRaises(DisallowedHost):
  717. request = HttpRequest()
  718. request.META = {
  719. "HTTP_HOST": host,
  720. }
  721. request.get_host()
  722. @override_settings(USE_X_FORWARDED_HOST=True, ALLOWED_HOSTS=["*"])
  723. def test_http_get_host_with_x_forwarded_host(self):
  724. # Check if X_FORWARDED_HOST is provided.
  725. request = HttpRequest()
  726. request.META = {
  727. "HTTP_X_FORWARDED_HOST": "forward.com",
  728. "HTTP_HOST": "example.com",
  729. "SERVER_NAME": "internal.com",
  730. "SERVER_PORT": 80,
  731. }
  732. # X_FORWARDED_HOST is obeyed.
  733. self.assertEqual(request.get_host(), "forward.com")
  734. # Check if X_FORWARDED_HOST isn't provided.
  735. request = HttpRequest()
  736. request.META = {
  737. "HTTP_HOST": "example.com",
  738. "SERVER_NAME": "internal.com",
  739. "SERVER_PORT": 80,
  740. }
  741. self.assertEqual(request.get_host(), "example.com")
  742. # Check if HTTP_HOST isn't provided.
  743. request = HttpRequest()
  744. request.META = {
  745. "SERVER_NAME": "internal.com",
  746. "SERVER_PORT": 80,
  747. }
  748. self.assertEqual(request.get_host(), "internal.com")
  749. # Check if HTTP_HOST isn't provided, and we're on a nonstandard port
  750. request = HttpRequest()
  751. request.META = {
  752. "SERVER_NAME": "internal.com",
  753. "SERVER_PORT": 8042,
  754. }
  755. self.assertEqual(request.get_host(), "internal.com:8042")
  756. # Poisoned host headers are rejected as suspicious
  757. legit_hosts = [
  758. "example.com",
  759. "example.com:80",
  760. "12.34.56.78",
  761. "12.34.56.78:443",
  762. "[2001:19f0:feee::dead:beef:cafe]",
  763. "[2001:19f0:feee::dead:beef:cafe]:8080",
  764. "xn--4ca9at.com", # Punycode for öäü.com
  765. ]
  766. for host in legit_hosts:
  767. request = HttpRequest()
  768. request.META = {
  769. "HTTP_HOST": host,
  770. }
  771. request.get_host()
  772. for host in self.poisoned_hosts:
  773. with self.assertRaises(DisallowedHost):
  774. request = HttpRequest()
  775. request.META = {
  776. "HTTP_HOST": host,
  777. }
  778. request.get_host()
  779. @override_settings(USE_X_FORWARDED_PORT=False)
  780. def test_get_port(self):
  781. request = HttpRequest()
  782. request.META = {
  783. "SERVER_PORT": "8080",
  784. "HTTP_X_FORWARDED_PORT": "80",
  785. }
  786. # Shouldn't use the X-Forwarded-Port header
  787. self.assertEqual(request.get_port(), "8080")
  788. request = HttpRequest()
  789. request.META = {
  790. "SERVER_PORT": "8080",
  791. }
  792. self.assertEqual(request.get_port(), "8080")
  793. @override_settings(USE_X_FORWARDED_PORT=True)
  794. def test_get_port_with_x_forwarded_port(self):
  795. request = HttpRequest()
  796. request.META = {
  797. "SERVER_PORT": "8080",
  798. "HTTP_X_FORWARDED_PORT": "80",
  799. }
  800. # Should use the X-Forwarded-Port header
  801. self.assertEqual(request.get_port(), "80")
  802. request = HttpRequest()
  803. request.META = {
  804. "SERVER_PORT": "8080",
  805. }
  806. self.assertEqual(request.get_port(), "8080")
  807. @override_settings(DEBUG=True, ALLOWED_HOSTS=[])
  808. def test_host_validation_in_debug_mode(self):
  809. """
  810. If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are
  811. allowed.
  812. """
  813. valid_hosts = ["localhost", "subdomain.localhost", "127.0.0.1", "[::1]"]
  814. for host in valid_hosts:
  815. request = HttpRequest()
  816. request.META = {"HTTP_HOST": host}
  817. self.assertEqual(request.get_host(), host)
  818. # Other hostnames raise a DisallowedHost.
  819. with self.assertRaises(DisallowedHost):
  820. request = HttpRequest()
  821. request.META = {"HTTP_HOST": "example.com"}
  822. request.get_host()
  823. @override_settings(ALLOWED_HOSTS=[])
  824. def test_get_host_suggestion_of_allowed_host(self):
  825. """
  826. get_host() makes helpful suggestions if a valid-looking host is not in
  827. ALLOWED_HOSTS.
  828. """
  829. msg_invalid_host = "Invalid HTTP_HOST header: %r."
  830. msg_suggestion = msg_invalid_host + " You may need to add %r to ALLOWED_HOSTS."
  831. msg_suggestion2 = (
  832. msg_invalid_host
  833. + " The domain name provided is not valid according to RFC 1034/1035"
  834. )
  835. for host in [ # Valid-looking hosts
  836. "example.com",
  837. "12.34.56.78",
  838. "[2001:19f0:feee::dead:beef:cafe]",
  839. "xn--4ca9at.com", # Punycode for öäü.com
  840. ]:
  841. request = HttpRequest()
  842. request.META = {"HTTP_HOST": host}
  843. with self.assertRaisesMessage(
  844. DisallowedHost, msg_suggestion % (host, host)
  845. ):
  846. request.get_host()
  847. for domain, port in [ # Valid-looking hosts with a port number
  848. ("example.com", 80),
  849. ("12.34.56.78", 443),
  850. ("[2001:19f0:feee::dead:beef:cafe]", 8080),
  851. ]:
  852. host = "%s:%s" % (domain, port)
  853. request = HttpRequest()
  854. request.META = {"HTTP_HOST": host}
  855. with self.assertRaisesMessage(
  856. DisallowedHost, msg_suggestion % (host, domain)
  857. ):
  858. request.get_host()
  859. for host in self.poisoned_hosts:
  860. request = HttpRequest()
  861. request.META = {"HTTP_HOST": host}
  862. with self.assertRaisesMessage(DisallowedHost, msg_invalid_host % host):
  863. request.get_host()
  864. request = HttpRequest()
  865. request.META = {"HTTP_HOST": "invalid_hostname.com"}
  866. with self.assertRaisesMessage(
  867. DisallowedHost, msg_suggestion2 % "invalid_hostname.com"
  868. ):
  869. request.get_host()
  870. def test_split_domain_port_removes_trailing_dot(self):
  871. domain, port = split_domain_port("example.com.:8080")
  872. self.assertEqual(domain, "example.com")
  873. self.assertEqual(port, "8080")
  874. class BuildAbsoluteURITests(SimpleTestCase):
  875. factory = RequestFactory()
  876. def test_absolute_url(self):
  877. request = HttpRequest()
  878. url = "https://www.example.com/asdf"
  879. self.assertEqual(request.build_absolute_uri(location=url), url)
  880. def test_host_retrieval(self):
  881. request = HttpRequest()
  882. request.get_host = lambda: "www.example.com"
  883. request.path = ""
  884. self.assertEqual(
  885. request.build_absolute_uri(location="/path/with:colons"),
  886. "http://www.example.com/path/with:colons",
  887. )
  888. def test_request_path_begins_with_two_slashes(self):
  889. # //// creates a request with a path beginning with //
  890. request = self.factory.get("////absolute-uri")
  891. tests = (
  892. # location isn't provided
  893. (None, "http://testserver//absolute-uri"),
  894. # An absolute URL
  895. ("http://example.com/?foo=bar", "http://example.com/?foo=bar"),
  896. # A schema-relative URL
  897. ("//example.com/?foo=bar", "http://example.com/?foo=bar"),
  898. # Relative URLs
  899. ("/foo/bar/", "http://testserver/foo/bar/"),
  900. ("/foo/./bar/", "http://testserver/foo/bar/"),
  901. ("/foo/../bar/", "http://testserver/bar/"),
  902. ("///foo/bar/", "http://testserver/foo/bar/"),
  903. )
  904. for location, expected_url in tests:
  905. with self.subTest(location=location):
  906. self.assertEqual(
  907. request.build_absolute_uri(location=location), expected_url
  908. )
  909. class RequestHeadersTests(SimpleTestCase):
  910. ENVIRON = {
  911. # Non-headers are ignored.
  912. "PATH_INFO": "/somepath/",
  913. "REQUEST_METHOD": "get",
  914. "wsgi.input": BytesIO(b""),
  915. "SERVER_NAME": "internal.com",
  916. "SERVER_PORT": 80,
  917. # These non-HTTP prefixed headers are included.
  918. "CONTENT_TYPE": "text/html",
  919. "CONTENT_LENGTH": "100",
  920. # All HTTP-prefixed headers are included.
  921. "HTTP_ACCEPT": "*",
  922. "HTTP_HOST": "example.com",
  923. "HTTP_USER_AGENT": "python-requests/1.2.0",
  924. }
  925. def test_base_request_headers(self):
  926. request = HttpRequest()
  927. request.META = self.ENVIRON
  928. self.assertEqual(
  929. dict(request.headers),
  930. {
  931. "Content-Type": "text/html",
  932. "Content-Length": "100",
  933. "Accept": "*",
  934. "Host": "example.com",
  935. "User-Agent": "python-requests/1.2.0",
  936. },
  937. )
  938. def test_wsgi_request_headers(self):
  939. request = WSGIRequest(self.ENVIRON)
  940. self.assertEqual(
  941. dict(request.headers),
  942. {
  943. "Content-Type": "text/html",
  944. "Content-Length": "100",
  945. "Accept": "*",
  946. "Host": "example.com",
  947. "User-Agent": "python-requests/1.2.0",
  948. },
  949. )
  950. def test_wsgi_request_headers_getitem(self):
  951. request = WSGIRequest(self.ENVIRON)
  952. self.assertEqual(request.headers["User-Agent"], "python-requests/1.2.0")
  953. self.assertEqual(request.headers["user-agent"], "python-requests/1.2.0")
  954. self.assertEqual(request.headers["user_agent"], "python-requests/1.2.0")
  955. self.assertEqual(request.headers["Content-Type"], "text/html")
  956. self.assertEqual(request.headers["Content-Length"], "100")
  957. def test_wsgi_request_headers_get(self):
  958. request = WSGIRequest(self.ENVIRON)
  959. self.assertEqual(request.headers.get("User-Agent"), "python-requests/1.2.0")
  960. self.assertEqual(request.headers.get("user-agent"), "python-requests/1.2.0")
  961. self.assertEqual(request.headers.get("Content-Type"), "text/html")
  962. self.assertEqual(request.headers.get("Content-Length"), "100")
  963. class HttpHeadersTests(SimpleTestCase):
  964. def test_basic(self):
  965. environ = {
  966. "CONTENT_TYPE": "text/html",
  967. "CONTENT_LENGTH": "100",
  968. "HTTP_HOST": "example.com",
  969. }
  970. headers = HttpHeaders(environ)
  971. self.assertEqual(sorted(headers), ["Content-Length", "Content-Type", "Host"])
  972. self.assertEqual(
  973. headers,
  974. {
  975. "Content-Type": "text/html",
  976. "Content-Length": "100",
  977. "Host": "example.com",
  978. },
  979. )
  980. def test_parse_header_name(self):
  981. tests = (
  982. ("PATH_INFO", None),
  983. ("HTTP_ACCEPT", "Accept"),
  984. ("HTTP_USER_AGENT", "User-Agent"),
  985. ("HTTP_X_FORWARDED_PROTO", "X-Forwarded-Proto"),
  986. ("CONTENT_TYPE", "Content-Type"),
  987. ("CONTENT_LENGTH", "Content-Length"),
  988. )
  989. for header, expected in tests:
  990. with self.subTest(header=header):
  991. self.assertEqual(HttpHeaders.parse_header_name(header), expected)