tests.py 38 KB

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