tests.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. import base64
  2. import hashlib
  3. import os
  4. import shutil
  5. import sys
  6. import tempfile as sys_tempfile
  7. import unittest
  8. from io import BytesIO, StringIO
  9. from unittest import mock
  10. from urllib.parse import quote
  11. from django.core.exceptions import SuspiciousFileOperation
  12. from django.core.files import temp as tempfile
  13. from django.core.files.uploadedfile import SimpleUploadedFile, UploadedFile
  14. from django.http.multipartparser import (
  15. FILE,
  16. MultiPartParser,
  17. MultiPartParserError,
  18. Parser,
  19. )
  20. from django.test import SimpleTestCase, TestCase, client, override_settings
  21. from . import uploadhandler
  22. from .models import FileModel
  23. UNICODE_FILENAME = "test-0123456789_中文_Orléans.jpg"
  24. MEDIA_ROOT = sys_tempfile.mkdtemp()
  25. UPLOAD_TO = os.path.join(MEDIA_ROOT, "test_upload")
  26. CANDIDATE_TRAVERSAL_FILE_NAMES = [
  27. "/tmp/hax0rd.txt", # Absolute path, *nix-style.
  28. "C:\\Windows\\hax0rd.txt", # Absolute path, win-style.
  29. "C:/Windows/hax0rd.txt", # Absolute path, broken-style.
  30. "\\tmp\\hax0rd.txt", # Absolute path, broken in a different way.
  31. "/tmp\\hax0rd.txt", # Absolute path, broken by mixing.
  32. "subdir/hax0rd.txt", # Descendant path, *nix-style.
  33. "subdir\\hax0rd.txt", # Descendant path, win-style.
  34. "sub/dir\\hax0rd.txt", # Descendant path, mixed.
  35. "../../hax0rd.txt", # Relative path, *nix-style.
  36. "..\\..\\hax0rd.txt", # Relative path, win-style.
  37. "../..\\hax0rd.txt", # Relative path, mixed.
  38. "../hax0rd.txt", # HTML entities.
  39. "../hax0rd.txt", # HTML entities.
  40. ]
  41. CANDIDATE_INVALID_FILE_NAMES = [
  42. "/tmp/", # Directory, *nix-style.
  43. "c:\\tmp\\", # Directory, win-style.
  44. "/tmp/.", # Directory dot, *nix-style.
  45. "c:\\tmp\\.", # Directory dot, *nix-style.
  46. "/tmp/..", # Parent directory, *nix-style.
  47. "c:\\tmp\\..", # Parent directory, win-style.
  48. "", # Empty filename.
  49. ]
  50. @override_settings(
  51. MEDIA_ROOT=MEDIA_ROOT, ROOT_URLCONF="file_uploads.urls", MIDDLEWARE=[]
  52. )
  53. class FileUploadTests(TestCase):
  54. @classmethod
  55. def setUpClass(cls):
  56. super().setUpClass()
  57. os.makedirs(MEDIA_ROOT, exist_ok=True)
  58. cls.addClassCleanup(shutil.rmtree, MEDIA_ROOT)
  59. def test_upload_name_is_validated(self):
  60. candidates = [
  61. "/tmp/",
  62. "/tmp/..",
  63. "/tmp/.",
  64. ]
  65. if sys.platform == "win32":
  66. candidates.extend(
  67. [
  68. "c:\\tmp\\",
  69. "c:\\tmp\\..",
  70. "c:\\tmp\\.",
  71. ]
  72. )
  73. for file_name in candidates:
  74. with self.subTest(file_name=file_name):
  75. self.assertRaises(SuspiciousFileOperation, UploadedFile, name=file_name)
  76. def test_simple_upload(self):
  77. with open(__file__, "rb") as fp:
  78. post_data = {
  79. "name": "Ringo",
  80. "file_field": fp,
  81. }
  82. response = self.client.post("/upload/", post_data)
  83. self.assertEqual(response.status_code, 200)
  84. def test_large_upload(self):
  85. file = tempfile.NamedTemporaryFile
  86. with file(suffix=".file1") as file1, file(suffix=".file2") as file2:
  87. file1.write(b"a" * (2**21))
  88. file1.seek(0)
  89. file2.write(b"a" * (10 * 2**20))
  90. file2.seek(0)
  91. post_data = {
  92. "name": "Ringo",
  93. "file_field1": file1,
  94. "file_field2": file2,
  95. }
  96. for key in list(post_data):
  97. try:
  98. post_data[key + "_hash"] = hashlib.sha1(
  99. post_data[key].read()
  100. ).hexdigest()
  101. post_data[key].seek(0)
  102. except AttributeError:
  103. post_data[key + "_hash"] = hashlib.sha1(
  104. post_data[key].encode()
  105. ).hexdigest()
  106. response = self.client.post("/verify/", post_data)
  107. self.assertEqual(response.status_code, 200)
  108. def _test_base64_upload(self, content, encode=base64.b64encode):
  109. payload = client.FakePayload(
  110. "\r\n".join(
  111. [
  112. "--" + client.BOUNDARY,
  113. 'Content-Disposition: form-data; name="file"; filename="test.txt"',
  114. "Content-Type: application/octet-stream",
  115. "Content-Transfer-Encoding: base64",
  116. "",
  117. ]
  118. )
  119. )
  120. payload.write(b"\r\n" + encode(content.encode()) + b"\r\n")
  121. payload.write("--" + client.BOUNDARY + "--\r\n")
  122. r = {
  123. "CONTENT_LENGTH": len(payload),
  124. "CONTENT_TYPE": client.MULTIPART_CONTENT,
  125. "PATH_INFO": "/echo_content/",
  126. "REQUEST_METHOD": "POST",
  127. "wsgi.input": payload,
  128. }
  129. response = self.client.request(**r)
  130. self.assertEqual(response.json()["file"], content)
  131. def test_base64_upload(self):
  132. self._test_base64_upload("This data will be transmitted base64-encoded.")
  133. def test_big_base64_upload(self):
  134. self._test_base64_upload("Big data" * 68000) # > 512Kb
  135. def test_big_base64_newlines_upload(self):
  136. self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes)
  137. def test_base64_invalid_upload(self):
  138. payload = client.FakePayload(
  139. "\r\n".join(
  140. [
  141. "--" + client.BOUNDARY,
  142. 'Content-Disposition: form-data; name="file"; filename="test.txt"',
  143. "Content-Type: application/octet-stream",
  144. "Content-Transfer-Encoding: base64",
  145. "",
  146. ]
  147. )
  148. )
  149. payload.write(b"\r\n!\r\n")
  150. payload.write("--" + client.BOUNDARY + "--\r\n")
  151. r = {
  152. "CONTENT_LENGTH": len(payload),
  153. "CONTENT_TYPE": client.MULTIPART_CONTENT,
  154. "PATH_INFO": "/echo_content/",
  155. "REQUEST_METHOD": "POST",
  156. "wsgi.input": payload,
  157. }
  158. response = self.client.request(**r)
  159. self.assertEqual(response.json()["file"], "")
  160. def test_unicode_file_name(self):
  161. with sys_tempfile.TemporaryDirectory() as temp_dir:
  162. # This file contains Chinese symbols and an accented char in the name.
  163. with open(os.path.join(temp_dir, UNICODE_FILENAME), "w+b") as file1:
  164. file1.write(b"b" * (2**10))
  165. file1.seek(0)
  166. response = self.client.post("/unicode_name/", {"file_unicode": file1})
  167. self.assertEqual(response.status_code, 200)
  168. def test_unicode_file_name_rfc2231(self):
  169. """
  170. Receiving file upload when filename is encoded with RFC 2231.
  171. """
  172. payload = client.FakePayload()
  173. payload.write(
  174. "\r\n".join(
  175. [
  176. "--" + client.BOUNDARY,
  177. 'Content-Disposition: form-data; name="file_unicode"; '
  178. "filename*=UTF-8''%s" % quote(UNICODE_FILENAME),
  179. "Content-Type: application/octet-stream",
  180. "",
  181. "You got pwnd.\r\n",
  182. "\r\n--" + client.BOUNDARY + "--\r\n",
  183. ]
  184. )
  185. )
  186. r = {
  187. "CONTENT_LENGTH": len(payload),
  188. "CONTENT_TYPE": client.MULTIPART_CONTENT,
  189. "PATH_INFO": "/unicode_name/",
  190. "REQUEST_METHOD": "POST",
  191. "wsgi.input": payload,
  192. }
  193. response = self.client.request(**r)
  194. self.assertEqual(response.status_code, 200)
  195. def test_unicode_name_rfc2231(self):
  196. """
  197. Receiving file upload when filename is encoded with RFC 2231.
  198. """
  199. payload = client.FakePayload()
  200. payload.write(
  201. "\r\n".join(
  202. [
  203. "--" + client.BOUNDARY,
  204. "Content-Disposition: form-data; name*=UTF-8''file_unicode; "
  205. "filename*=UTF-8''%s" % quote(UNICODE_FILENAME),
  206. "Content-Type: application/octet-stream",
  207. "",
  208. "You got pwnd.\r\n",
  209. "\r\n--" + client.BOUNDARY + "--\r\n",
  210. ]
  211. )
  212. )
  213. r = {
  214. "CONTENT_LENGTH": len(payload),
  215. "CONTENT_TYPE": client.MULTIPART_CONTENT,
  216. "PATH_INFO": "/unicode_name/",
  217. "REQUEST_METHOD": "POST",
  218. "wsgi.input": payload,
  219. }
  220. response = self.client.request(**r)
  221. self.assertEqual(response.status_code, 200)
  222. def test_unicode_file_name_rfc2231_with_double_quotes(self):
  223. payload = client.FakePayload()
  224. payload.write(
  225. "\r\n".join(
  226. [
  227. "--" + client.BOUNDARY,
  228. 'Content-Disposition: form-data; name="file_unicode"; '
  229. "filename*=\"UTF-8''%s\"" % quote(UNICODE_FILENAME),
  230. "Content-Type: application/octet-stream",
  231. "",
  232. "You got pwnd.\r\n",
  233. "\r\n--" + client.BOUNDARY + "--\r\n",
  234. ]
  235. )
  236. )
  237. r = {
  238. "CONTENT_LENGTH": len(payload),
  239. "CONTENT_TYPE": client.MULTIPART_CONTENT,
  240. "PATH_INFO": "/unicode_name/",
  241. "REQUEST_METHOD": "POST",
  242. "wsgi.input": payload,
  243. }
  244. response = self.client.request(**r)
  245. self.assertEqual(response.status_code, 200)
  246. def test_unicode_name_rfc2231_with_double_quotes(self):
  247. payload = client.FakePayload()
  248. payload.write(
  249. "\r\n".join(
  250. [
  251. "--" + client.BOUNDARY,
  252. "Content-Disposition: form-data; name*=\"UTF-8''file_unicode\"; "
  253. "filename*=\"UTF-8''%s\"" % quote(UNICODE_FILENAME),
  254. "Content-Type: application/octet-stream",
  255. "",
  256. "You got pwnd.\r\n",
  257. "\r\n--" + client.BOUNDARY + "--\r\n",
  258. ]
  259. )
  260. )
  261. r = {
  262. "CONTENT_LENGTH": len(payload),
  263. "CONTENT_TYPE": client.MULTIPART_CONTENT,
  264. "PATH_INFO": "/unicode_name/",
  265. "REQUEST_METHOD": "POST",
  266. "wsgi.input": payload,
  267. }
  268. response = self.client.request(**r)
  269. self.assertEqual(response.status_code, 200)
  270. def test_blank_filenames(self):
  271. """
  272. Receiving file upload when filename is blank (before and after
  273. sanitization) should be okay.
  274. """
  275. filenames = [
  276. "",
  277. # Normalized by MultiPartParser.IE_sanitize().
  278. "C:\\Windows\\",
  279. # Normalized by os.path.basename().
  280. "/",
  281. "ends-with-slash/",
  282. ]
  283. payload = client.FakePayload()
  284. for i, name in enumerate(filenames):
  285. payload.write(
  286. "\r\n".join(
  287. [
  288. "--" + client.BOUNDARY,
  289. 'Content-Disposition: form-data; name="file%s"; filename="%s"'
  290. % (i, name),
  291. "Content-Type: application/octet-stream",
  292. "",
  293. "You got pwnd.\r\n",
  294. ]
  295. )
  296. )
  297. payload.write("\r\n--" + client.BOUNDARY + "--\r\n")
  298. r = {
  299. "CONTENT_LENGTH": len(payload),
  300. "CONTENT_TYPE": client.MULTIPART_CONTENT,
  301. "PATH_INFO": "/echo/",
  302. "REQUEST_METHOD": "POST",
  303. "wsgi.input": payload,
  304. }
  305. response = self.client.request(**r)
  306. self.assertEqual(response.status_code, 200)
  307. # Empty filenames should be ignored
  308. received = response.json()
  309. for i, name in enumerate(filenames):
  310. self.assertIsNone(received.get("file%s" % i))
  311. def test_non_printable_chars_in_file_names(self):
  312. file_name = "non-\x00printable\x00\n_chars.txt\x00"
  313. payload = client.FakePayload()
  314. payload.write(
  315. "\r\n".join(
  316. [
  317. "--" + client.BOUNDARY,
  318. f'Content-Disposition: form-data; name="file"; '
  319. f'filename="{file_name}"',
  320. "Content-Type: application/octet-stream",
  321. "",
  322. "You got pwnd.\r\n",
  323. ]
  324. )
  325. )
  326. payload.write("\r\n--" + client.BOUNDARY + "--\r\n")
  327. r = {
  328. "CONTENT_LENGTH": len(payload),
  329. "CONTENT_TYPE": client.MULTIPART_CONTENT,
  330. "PATH_INFO": "/echo/",
  331. "REQUEST_METHOD": "POST",
  332. "wsgi.input": payload,
  333. }
  334. response = self.client.request(**r)
  335. # Non-printable chars are sanitized.
  336. received = response.json()
  337. self.assertEqual(received["file"], "non-printable_chars.txt")
  338. def test_dangerous_file_names(self):
  339. """Uploaded file names should be sanitized before ever reaching the view."""
  340. # This test simulates possible directory traversal attacks by a
  341. # malicious uploader We have to do some monkeybusiness here to construct
  342. # a malicious payload with an invalid file name (containing os.sep or
  343. # os.pardir). This similar to what an attacker would need to do when
  344. # trying such an attack.
  345. payload = client.FakePayload()
  346. for i, name in enumerate(CANDIDATE_TRAVERSAL_FILE_NAMES):
  347. payload.write(
  348. "\r\n".join(
  349. [
  350. "--" + client.BOUNDARY,
  351. 'Content-Disposition: form-data; name="file%s"; filename="%s"'
  352. % (i, name),
  353. "Content-Type: application/octet-stream",
  354. "",
  355. "You got pwnd.\r\n",
  356. ]
  357. )
  358. )
  359. payload.write("\r\n--" + client.BOUNDARY + "--\r\n")
  360. r = {
  361. "CONTENT_LENGTH": len(payload),
  362. "CONTENT_TYPE": client.MULTIPART_CONTENT,
  363. "PATH_INFO": "/echo/",
  364. "REQUEST_METHOD": "POST",
  365. "wsgi.input": payload,
  366. }
  367. response = self.client.request(**r)
  368. # The filenames should have been sanitized by the time it got to the view.
  369. received = response.json()
  370. for i, name in enumerate(CANDIDATE_TRAVERSAL_FILE_NAMES):
  371. got = received["file%s" % i]
  372. self.assertEqual(got, "hax0rd.txt")
  373. def test_filename_overflow(self):
  374. """File names over 256 characters (dangerous on some platforms) get fixed up."""
  375. long_str = "f" * 300
  376. cases = [
  377. # field name, filename, expected
  378. ("long_filename", "%s.txt" % long_str, "%s.txt" % long_str[:251]),
  379. ("long_extension", "foo.%s" % long_str, ".%s" % long_str[:254]),
  380. ("no_extension", long_str, long_str[:255]),
  381. ("no_filename", ".%s" % long_str, ".%s" % long_str[:254]),
  382. ("long_everything", "%s.%s" % (long_str, long_str), ".%s" % long_str[:254]),
  383. ]
  384. payload = client.FakePayload()
  385. for name, filename, _ in cases:
  386. payload.write(
  387. "\r\n".join(
  388. [
  389. "--" + client.BOUNDARY,
  390. 'Content-Disposition: form-data; name="{}"; filename="{}"',
  391. "Content-Type: application/octet-stream",
  392. "",
  393. "Oops.",
  394. "",
  395. ]
  396. ).format(name, filename)
  397. )
  398. payload.write("\r\n--" + client.BOUNDARY + "--\r\n")
  399. r = {
  400. "CONTENT_LENGTH": len(payload),
  401. "CONTENT_TYPE": client.MULTIPART_CONTENT,
  402. "PATH_INFO": "/echo/",
  403. "REQUEST_METHOD": "POST",
  404. "wsgi.input": payload,
  405. }
  406. response = self.client.request(**r)
  407. result = response.json()
  408. for name, _, expected in cases:
  409. got = result[name]
  410. self.assertEqual(expected, got, "Mismatch for {}".format(name))
  411. self.assertLess(
  412. len(got), 256, "Got a long file name (%s characters)." % len(got)
  413. )
  414. def test_file_content(self):
  415. file = tempfile.NamedTemporaryFile
  416. with file(suffix=".ctype_extra") as no_content_type, file(
  417. suffix=".ctype_extra"
  418. ) as simple_file:
  419. no_content_type.write(b"no content")
  420. no_content_type.seek(0)
  421. simple_file.write(b"text content")
  422. simple_file.seek(0)
  423. simple_file.content_type = "text/plain"
  424. string_io = StringIO("string content")
  425. bytes_io = BytesIO(b"binary content")
  426. response = self.client.post(
  427. "/echo_content/",
  428. {
  429. "no_content_type": no_content_type,
  430. "simple_file": simple_file,
  431. "string": string_io,
  432. "binary": bytes_io,
  433. },
  434. )
  435. received = response.json()
  436. self.assertEqual(received["no_content_type"], "no content")
  437. self.assertEqual(received["simple_file"], "text content")
  438. self.assertEqual(received["string"], "string content")
  439. self.assertEqual(received["binary"], "binary content")
  440. def test_content_type_extra(self):
  441. """Uploaded files may have content type parameters available."""
  442. file = tempfile.NamedTemporaryFile
  443. with file(suffix=".ctype_extra") as no_content_type, file(
  444. suffix=".ctype_extra"
  445. ) as simple_file:
  446. no_content_type.write(b"something")
  447. no_content_type.seek(0)
  448. simple_file.write(b"something")
  449. simple_file.seek(0)
  450. simple_file.content_type = "text/plain; test-key=test_value"
  451. response = self.client.post(
  452. "/echo_content_type_extra/",
  453. {
  454. "no_content_type": no_content_type,
  455. "simple_file": simple_file,
  456. },
  457. )
  458. received = response.json()
  459. self.assertEqual(received["no_content_type"], {})
  460. self.assertEqual(received["simple_file"], {"test-key": "test_value"})
  461. def test_truncated_multipart_handled_gracefully(self):
  462. """
  463. If passed an incomplete multipart message, MultiPartParser does not
  464. attempt to read beyond the end of the stream, and simply will handle
  465. the part that can be parsed gracefully.
  466. """
  467. payload_str = "\r\n".join(
  468. [
  469. "--" + client.BOUNDARY,
  470. 'Content-Disposition: form-data; name="file"; filename="foo.txt"',
  471. "Content-Type: application/octet-stream",
  472. "",
  473. "file contents" "--" + client.BOUNDARY + "--",
  474. "",
  475. ]
  476. )
  477. payload = client.FakePayload(payload_str[:-10])
  478. r = {
  479. "CONTENT_LENGTH": len(payload),
  480. "CONTENT_TYPE": client.MULTIPART_CONTENT,
  481. "PATH_INFO": "/echo/",
  482. "REQUEST_METHOD": "POST",
  483. "wsgi.input": payload,
  484. }
  485. self.assertEqual(self.client.request(**r).json(), {})
  486. def test_empty_multipart_handled_gracefully(self):
  487. """
  488. If passed an empty multipart message, MultiPartParser will return
  489. an empty QueryDict.
  490. """
  491. r = {
  492. "CONTENT_LENGTH": 0,
  493. "CONTENT_TYPE": client.MULTIPART_CONTENT,
  494. "PATH_INFO": "/echo/",
  495. "REQUEST_METHOD": "POST",
  496. "wsgi.input": client.FakePayload(b""),
  497. }
  498. self.assertEqual(self.client.request(**r).json(), {})
  499. def test_custom_upload_handler(self):
  500. file = tempfile.NamedTemporaryFile
  501. with file() as smallfile, file() as bigfile:
  502. # A small file (under the 5M quota)
  503. smallfile.write(b"a" * (2**21))
  504. smallfile.seek(0)
  505. # A big file (over the quota)
  506. bigfile.write(b"a" * (10 * 2**20))
  507. bigfile.seek(0)
  508. # Small file posting should work.
  509. self.assertIn("f", self.client.post("/quota/", {"f": smallfile}).json())
  510. # Large files don't go through.
  511. self.assertNotIn("f", self.client.post("/quota/", {"f": bigfile}).json())
  512. def test_broken_custom_upload_handler(self):
  513. with tempfile.NamedTemporaryFile() as file:
  514. file.write(b"a" * (2**21))
  515. file.seek(0)
  516. msg = (
  517. "You cannot alter upload handlers after the upload has been processed."
  518. )
  519. with self.assertRaisesMessage(AttributeError, msg):
  520. self.client.post("/quota/broken/", {"f": file})
  521. def test_stop_upload_temporary_file_handler(self):
  522. with tempfile.NamedTemporaryFile() as temp_file:
  523. temp_file.write(b"a")
  524. temp_file.seek(0)
  525. response = self.client.post("/temp_file/stop_upload/", {"file": temp_file})
  526. temp_path = response.json()["temp_path"]
  527. self.assertIs(os.path.exists(temp_path), False)
  528. def test_upload_interrupted_temporary_file_handler(self):
  529. # Simulate an interrupted upload by omitting the closing boundary.
  530. class MockedParser(Parser):
  531. def __iter__(self):
  532. for item in super().__iter__():
  533. item_type, meta_data, field_stream = item
  534. yield item_type, meta_data, field_stream
  535. if item_type == FILE:
  536. return
  537. with tempfile.NamedTemporaryFile() as temp_file:
  538. temp_file.write(b"a")
  539. temp_file.seek(0)
  540. with mock.patch(
  541. "django.http.multipartparser.Parser",
  542. MockedParser,
  543. ):
  544. response = self.client.post(
  545. "/temp_file/upload_interrupted/",
  546. {"file": temp_file},
  547. )
  548. temp_path = response.json()["temp_path"]
  549. self.assertIs(os.path.exists(temp_path), False)
  550. def test_fileupload_getlist(self):
  551. file = tempfile.NamedTemporaryFile
  552. with file() as file1, file() as file2, file() as file2a:
  553. file1.write(b"a" * (2**23))
  554. file1.seek(0)
  555. file2.write(b"a" * (2 * 2**18))
  556. file2.seek(0)
  557. file2a.write(b"a" * (5 * 2**20))
  558. file2a.seek(0)
  559. response = self.client.post(
  560. "/getlist_count/",
  561. {
  562. "file1": file1,
  563. "field1": "test",
  564. "field2": "test3",
  565. "field3": "test5",
  566. "field4": "test6",
  567. "field5": "test7",
  568. "file2": (file2, file2a),
  569. },
  570. )
  571. got = response.json()
  572. self.assertEqual(got.get("file1"), 1)
  573. self.assertEqual(got.get("file2"), 2)
  574. def test_fileuploads_closed_at_request_end(self):
  575. file = tempfile.NamedTemporaryFile
  576. with file() as f1, file() as f2a, file() as f2b:
  577. response = self.client.post(
  578. "/fd_closing/t/",
  579. {
  580. "file": f1,
  581. "file2": (f2a, f2b),
  582. },
  583. )
  584. request = response.wsgi_request
  585. # The files were parsed.
  586. self.assertTrue(hasattr(request, "_files"))
  587. file = request._files["file"]
  588. self.assertTrue(file.closed)
  589. files = request._files.getlist("file2")
  590. self.assertTrue(files[0].closed)
  591. self.assertTrue(files[1].closed)
  592. def test_no_parsing_triggered_by_fd_closing(self):
  593. file = tempfile.NamedTemporaryFile
  594. with file() as f1, file() as f2a, file() as f2b:
  595. response = self.client.post(
  596. "/fd_closing/f/",
  597. {
  598. "file": f1,
  599. "file2": (f2a, f2b),
  600. },
  601. )
  602. request = response.wsgi_request
  603. # The fd closing logic doesn't trigger parsing of the stream
  604. self.assertFalse(hasattr(request, "_files"))
  605. def test_file_error_blocking(self):
  606. """
  607. The server should not block when there are upload errors (bug #8622).
  608. This can happen if something -- i.e. an exception handler -- tries to
  609. access POST while handling an error in parsing POST. This shouldn't
  610. cause an infinite loop!
  611. """
  612. class POSTAccessingHandler(client.ClientHandler):
  613. """A handler that'll access POST during an exception."""
  614. def handle_uncaught_exception(self, request, resolver, exc_info):
  615. ret = super().handle_uncaught_exception(request, resolver, exc_info)
  616. request.POST # evaluate
  617. return ret
  618. # Maybe this is a little more complicated that it needs to be; but if
  619. # the django.test.client.FakePayload.read() implementation changes then
  620. # this test would fail. So we need to know exactly what kind of error
  621. # it raises when there is an attempt to read more than the available bytes:
  622. try:
  623. client.FakePayload(b"a").read(2)
  624. except Exception as err:
  625. reference_error = err
  626. # install the custom handler that tries to access request.POST
  627. self.client.handler = POSTAccessingHandler()
  628. with open(__file__, "rb") as fp:
  629. post_data = {
  630. "name": "Ringo",
  631. "file_field": fp,
  632. }
  633. try:
  634. self.client.post("/upload_errors/", post_data)
  635. except reference_error.__class__ as err:
  636. self.assertNotEqual(
  637. str(err),
  638. str(reference_error),
  639. "Caught a repeated exception that'll cause an infinite loop in "
  640. "file uploads.",
  641. )
  642. except Exception as err:
  643. # CustomUploadError is the error that should have been raised
  644. self.assertEqual(err.__class__, uploadhandler.CustomUploadError)
  645. def test_filename_case_preservation(self):
  646. """
  647. The storage backend shouldn't mess with the case of the filenames
  648. uploaded.
  649. """
  650. # Synthesize the contents of a file upload with a mixed case filename
  651. # so we don't have to carry such a file in the Django tests source code
  652. # tree.
  653. vars = {"boundary": "oUrBoUnDaRyStRiNg"}
  654. post_data = [
  655. "--%(boundary)s",
  656. 'Content-Disposition: form-data; name="file_field"; '
  657. 'filename="MiXeD_cAsE.txt"',
  658. "Content-Type: application/octet-stream",
  659. "",
  660. "file contents\n",
  661. "--%(boundary)s--\r\n",
  662. ]
  663. response = self.client.post(
  664. "/filename_case/",
  665. "\r\n".join(post_data) % vars,
  666. "multipart/form-data; boundary=%(boundary)s" % vars,
  667. )
  668. self.assertEqual(response.status_code, 200)
  669. id = int(response.content)
  670. obj = FileModel.objects.get(pk=id)
  671. # The name of the file uploaded and the file stored in the server-side
  672. # shouldn't differ.
  673. self.assertEqual(os.path.basename(obj.testfile.path), "MiXeD_cAsE.txt")
  674. def test_filename_traversal_upload(self):
  675. os.makedirs(UPLOAD_TO, exist_ok=True)
  676. tests = [
  677. "../test.txt",
  678. "../test.txt",
  679. ]
  680. for file_name in tests:
  681. with self.subTest(file_name=file_name):
  682. payload = client.FakePayload()
  683. payload.write(
  684. "\r\n".join(
  685. [
  686. "--" + client.BOUNDARY,
  687. 'Content-Disposition: form-data; name="my_file"; '
  688. 'filename="%s";' % file_name,
  689. "Content-Type: text/plain",
  690. "",
  691. "file contents.\r\n",
  692. "\r\n--" + client.BOUNDARY + "--\r\n",
  693. ]
  694. ),
  695. )
  696. r = {
  697. "CONTENT_LENGTH": len(payload),
  698. "CONTENT_TYPE": client.MULTIPART_CONTENT,
  699. "PATH_INFO": "/upload_traversal/",
  700. "REQUEST_METHOD": "POST",
  701. "wsgi.input": payload,
  702. }
  703. response = self.client.request(**r)
  704. result = response.json()
  705. self.assertEqual(response.status_code, 200)
  706. self.assertEqual(result["file_name"], "test.txt")
  707. self.assertIs(
  708. os.path.exists(os.path.join(MEDIA_ROOT, "test.txt")),
  709. False,
  710. )
  711. self.assertIs(
  712. os.path.exists(os.path.join(UPLOAD_TO, "test.txt")),
  713. True,
  714. )
  715. @override_settings(MEDIA_ROOT=MEDIA_ROOT)
  716. class DirectoryCreationTests(SimpleTestCase):
  717. """
  718. Tests for error handling during directory creation
  719. via _save_FIELD_file (ticket #6450)
  720. """
  721. @classmethod
  722. def setUpClass(cls):
  723. super().setUpClass()
  724. os.makedirs(MEDIA_ROOT, exist_ok=True)
  725. cls.addClassCleanup(shutil.rmtree, MEDIA_ROOT)
  726. def setUp(self):
  727. self.obj = FileModel()
  728. @unittest.skipIf(
  729. sys.platform == "win32", "Python on Windows doesn't have working os.chmod()."
  730. )
  731. def test_readonly_root(self):
  732. """Permission errors are not swallowed"""
  733. os.chmod(MEDIA_ROOT, 0o500)
  734. self.addCleanup(os.chmod, MEDIA_ROOT, 0o700)
  735. with self.assertRaises(PermissionError):
  736. self.obj.testfile.save(
  737. "foo.txt", SimpleUploadedFile("foo.txt", b"x"), save=False
  738. )
  739. def test_not_a_directory(self):
  740. # Create a file with the upload directory name
  741. open(UPLOAD_TO, "wb").close()
  742. self.addCleanup(os.remove, UPLOAD_TO)
  743. msg = "%s exists and is not a directory." % UPLOAD_TO
  744. with self.assertRaisesMessage(FileExistsError, msg):
  745. with SimpleUploadedFile("foo.txt", b"x") as file:
  746. self.obj.testfile.save("foo.txt", file, save=False)
  747. class MultiParserTests(SimpleTestCase):
  748. def test_empty_upload_handlers(self):
  749. # We're not actually parsing here; just checking if the parser properly
  750. # instantiates with empty upload handlers.
  751. MultiPartParser(
  752. {
  753. "CONTENT_TYPE": "multipart/form-data; boundary=_foo",
  754. "CONTENT_LENGTH": "1",
  755. },
  756. StringIO("x"),
  757. [],
  758. "utf-8",
  759. )
  760. def test_invalid_content_type(self):
  761. with self.assertRaisesMessage(
  762. MultiPartParserError, "Invalid Content-Type: text/plain"
  763. ):
  764. MultiPartParser(
  765. {
  766. "CONTENT_TYPE": "text/plain",
  767. "CONTENT_LENGTH": "1",
  768. },
  769. StringIO("x"),
  770. [],
  771. "utf-8",
  772. )
  773. def test_negative_content_length(self):
  774. with self.assertRaisesMessage(
  775. MultiPartParserError, "Invalid content length: -1"
  776. ):
  777. MultiPartParser(
  778. {
  779. "CONTENT_TYPE": "multipart/form-data; boundary=_foo",
  780. "CONTENT_LENGTH": -1,
  781. },
  782. StringIO("x"),
  783. [],
  784. "utf-8",
  785. )
  786. def test_bad_type_content_length(self):
  787. multipart_parser = MultiPartParser(
  788. {
  789. "CONTENT_TYPE": "multipart/form-data; boundary=_foo",
  790. "CONTENT_LENGTH": "a",
  791. },
  792. StringIO("x"),
  793. [],
  794. "utf-8",
  795. )
  796. self.assertEqual(multipart_parser._content_length, 0)
  797. def test_sanitize_file_name(self):
  798. parser = MultiPartParser(
  799. {
  800. "CONTENT_TYPE": "multipart/form-data; boundary=_foo",
  801. "CONTENT_LENGTH": "1",
  802. },
  803. StringIO("x"),
  804. [],
  805. "utf-8",
  806. )
  807. for file_name in CANDIDATE_TRAVERSAL_FILE_NAMES:
  808. with self.subTest(file_name=file_name):
  809. self.assertEqual(parser.sanitize_file_name(file_name), "hax0rd.txt")
  810. def test_sanitize_invalid_file_name(self):
  811. parser = MultiPartParser(
  812. {
  813. "CONTENT_TYPE": "multipart/form-data; boundary=_foo",
  814. "CONTENT_LENGTH": "1",
  815. },
  816. StringIO("x"),
  817. [],
  818. "utf-8",
  819. )
  820. for file_name in CANDIDATE_INVALID_FILE_NAMES:
  821. with self.subTest(file_name=file_name):
  822. self.assertIsNone(parser.sanitize_file_name(file_name))