tests.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. #! -*- coding: utf-8 -*-
  2. from __future__ import absolute_import
  3. import base64
  4. import errno
  5. import hashlib
  6. import json
  7. import os
  8. import shutil
  9. from StringIO import StringIO
  10. from django.core.files import temp as tempfile
  11. from django.core.files.uploadedfile import SimpleUploadedFile
  12. from django.http.multipartparser import MultiPartParser
  13. from django.test import TestCase, client
  14. from django.utils import unittest
  15. from . import uploadhandler
  16. from .models import FileModel, temp_storage, UPLOAD_TO
  17. UNICODE_FILENAME = u'test-0123456789_中文_Orléans.jpg'
  18. class FileUploadTests(TestCase):
  19. def test_simple_upload(self):
  20. with open(__file__) as fp:
  21. post_data = {
  22. 'name': 'Ringo',
  23. 'file_field': fp,
  24. }
  25. response = self.client.post('/file_uploads/upload/', post_data)
  26. self.assertEqual(response.status_code, 200)
  27. def test_large_upload(self):
  28. tdir = tempfile.gettempdir()
  29. file1 = tempfile.NamedTemporaryFile(suffix=".file1", dir=tdir)
  30. file1.write('a' * (2 ** 21))
  31. file1.seek(0)
  32. file2 = tempfile.NamedTemporaryFile(suffix=".file2", dir=tdir)
  33. file2.write('a' * (10 * 2 ** 20))
  34. file2.seek(0)
  35. post_data = {
  36. 'name': 'Ringo',
  37. 'file_field1': file1,
  38. 'file_field2': file2,
  39. }
  40. for key in post_data.keys():
  41. try:
  42. post_data[key + '_hash'] = hashlib.sha1(post_data[key].read()).hexdigest()
  43. post_data[key].seek(0)
  44. except AttributeError:
  45. post_data[key + '_hash'] = hashlib.sha1(post_data[key]).hexdigest()
  46. response = self.client.post('/file_uploads/verify/', post_data)
  47. self.assertEqual(response.status_code, 200)
  48. def test_base64_upload(self):
  49. test_string = "This data will be transmitted base64-encoded."
  50. payload = "\r\n".join([
  51. '--' + client.BOUNDARY,
  52. 'Content-Disposition: form-data; name="file"; filename="test.txt"',
  53. 'Content-Type: application/octet-stream',
  54. 'Content-Transfer-Encoding: base64',
  55. '',
  56. base64.b64encode(test_string),
  57. '--' + client.BOUNDARY + '--',
  58. '',
  59. ])
  60. r = {
  61. 'CONTENT_LENGTH': len(payload),
  62. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  63. 'PATH_INFO': "/file_uploads/echo_content/",
  64. 'REQUEST_METHOD': 'POST',
  65. 'wsgi.input': client.FakePayload(payload),
  66. }
  67. response = self.client.request(**r)
  68. received = json.loads(response.content)
  69. self.assertEqual(received['file'], test_string)
  70. def test_unicode_file_name(self):
  71. tdir = tempfile.gettempdir()
  72. # This file contains chinese symbols and an accented char in the name.
  73. with open(os.path.join(tdir, UNICODE_FILENAME.encode('utf-8')), 'w+b') as file1:
  74. file1.write('b' * (2 ** 10))
  75. file1.seek(0)
  76. post_data = {
  77. 'file_unicode': file1,
  78. }
  79. response = self.client.post('/file_uploads/unicode_name/', post_data)
  80. try:
  81. os.unlink(file1.name)
  82. except:
  83. pass
  84. self.assertEqual(response.status_code, 200)
  85. def test_dangerous_file_names(self):
  86. """Uploaded file names should be sanitized before ever reaching the view."""
  87. # This test simulates possible directory traversal attacks by a
  88. # malicious uploader We have to do some monkeybusiness here to construct
  89. # a malicious payload with an invalid file name (containing os.sep or
  90. # os.pardir). This similar to what an attacker would need to do when
  91. # trying such an attack.
  92. scary_file_names = [
  93. "/tmp/hax0rd.txt", # Absolute path, *nix-style.
  94. "C:\\Windows\\hax0rd.txt", # Absolute path, win-syle.
  95. "C:/Windows/hax0rd.txt", # Absolute path, broken-style.
  96. "\\tmp\\hax0rd.txt", # Absolute path, broken in a different way.
  97. "/tmp\\hax0rd.txt", # Absolute path, broken by mixing.
  98. "subdir/hax0rd.txt", # Descendant path, *nix-style.
  99. "subdir\\hax0rd.txt", # Descendant path, win-style.
  100. "sub/dir\\hax0rd.txt", # Descendant path, mixed.
  101. "../../hax0rd.txt", # Relative path, *nix-style.
  102. "..\\..\\hax0rd.txt", # Relative path, win-style.
  103. "../..\\hax0rd.txt" # Relative path, mixed.
  104. ]
  105. payload = []
  106. for i, name in enumerate(scary_file_names):
  107. payload.extend([
  108. '--' + client.BOUNDARY,
  109. 'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name),
  110. 'Content-Type: application/octet-stream',
  111. '',
  112. 'You got pwnd.'
  113. ])
  114. payload.extend([
  115. '--' + client.BOUNDARY + '--',
  116. '',
  117. ])
  118. payload = "\r\n".join(payload)
  119. r = {
  120. 'CONTENT_LENGTH': len(payload),
  121. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  122. 'PATH_INFO': "/file_uploads/echo/",
  123. 'REQUEST_METHOD': 'POST',
  124. 'wsgi.input': client.FakePayload(payload),
  125. }
  126. response = self.client.request(**r)
  127. # The filenames should have been sanitized by the time it got to the view.
  128. recieved = json.loads(response.content)
  129. for i, name in enumerate(scary_file_names):
  130. got = recieved["file%s" % i]
  131. self.assertEqual(got, "hax0rd.txt")
  132. def test_filename_overflow(self):
  133. """File names over 256 characters (dangerous on some platforms) get fixed up."""
  134. name = "%s.txt" % ("f"*500)
  135. payload = "\r\n".join([
  136. '--' + client.BOUNDARY,
  137. 'Content-Disposition: form-data; name="file"; filename="%s"' % name,
  138. 'Content-Type: application/octet-stream',
  139. '',
  140. 'Oops.'
  141. '--' + client.BOUNDARY + '--',
  142. '',
  143. ])
  144. r = {
  145. 'CONTENT_LENGTH': len(payload),
  146. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  147. 'PATH_INFO': "/file_uploads/echo/",
  148. 'REQUEST_METHOD': 'POST',
  149. 'wsgi.input': client.FakePayload(payload),
  150. }
  151. got = json.loads(self.client.request(**r).content)
  152. self.assertTrue(len(got['file']) < 256, "Got a long file name (%s characters)." % len(got['file']))
  153. def test_truncated_multipart_handled_gracefully(self):
  154. """
  155. If passed an incomplete multipart message, MultiPartParser does not
  156. attempt to read beyond the end of the stream, and simply will handle
  157. the part that can be parsed gracefully.
  158. """
  159. payload = "\r\n".join([
  160. '--' + client.BOUNDARY,
  161. 'Content-Disposition: form-data; name="file"; filename="foo.txt"',
  162. 'Content-Type: application/octet-stream',
  163. '',
  164. 'file contents'
  165. '--' + client.BOUNDARY + '--',
  166. '',
  167. ])
  168. payload = payload[:-10]
  169. r = {
  170. 'CONTENT_LENGTH': len(payload),
  171. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  172. 'PATH_INFO': '/file_uploads/echo/',
  173. 'REQUEST_METHOD': 'POST',
  174. 'wsgi.input': client.FakePayload(payload),
  175. }
  176. got = json.loads(self.client.request(**r).content)
  177. self.assertEqual(got, {})
  178. def test_empty_multipart_handled_gracefully(self):
  179. """
  180. If passed an empty multipart message, MultiPartParser will return
  181. an empty QueryDict.
  182. """
  183. r = {
  184. 'CONTENT_LENGTH': 0,
  185. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  186. 'PATH_INFO': '/file_uploads/echo/',
  187. 'REQUEST_METHOD': 'POST',
  188. 'wsgi.input': client.FakePayload(''),
  189. }
  190. got = json.loads(self.client.request(**r).content)
  191. self.assertEqual(got, {})
  192. def test_custom_upload_handler(self):
  193. # A small file (under the 5M quota)
  194. smallfile = tempfile.NamedTemporaryFile()
  195. smallfile.write('a' * (2 ** 21))
  196. smallfile.seek(0)
  197. # A big file (over the quota)
  198. bigfile = tempfile.NamedTemporaryFile()
  199. bigfile.write('a' * (10 * 2 ** 20))
  200. bigfile.seek(0)
  201. # Small file posting should work.
  202. response = self.client.post('/file_uploads/quota/', {'f': smallfile})
  203. got = json.loads(response.content)
  204. self.assertTrue('f' in got)
  205. # Large files don't go through.
  206. response = self.client.post("/file_uploads/quota/", {'f': bigfile})
  207. got = json.loads(response.content)
  208. self.assertTrue('f' not in got)
  209. def test_broken_custom_upload_handler(self):
  210. f = tempfile.NamedTemporaryFile()
  211. f.write('a' * (2 ** 21))
  212. f.seek(0)
  213. # AttributeError: You cannot alter upload handlers after the upload has been processed.
  214. self.assertRaises(
  215. AttributeError,
  216. self.client.post,
  217. '/file_uploads/quota/broken/',
  218. {'f': f}
  219. )
  220. def test_fileupload_getlist(self):
  221. file1 = tempfile.NamedTemporaryFile()
  222. file1.write('a' * (2 ** 23))
  223. file1.seek(0)
  224. file2 = tempfile.NamedTemporaryFile()
  225. file2.write('a' * (2 * 2 ** 18))
  226. file2.seek(0)
  227. file2a = tempfile.NamedTemporaryFile()
  228. file2a.write('a' * (5 * 2 ** 20))
  229. file2a.seek(0)
  230. response = self.client.post('/file_uploads/getlist_count/', {
  231. 'file1': file1,
  232. 'field1': u'test',
  233. 'field2': u'test3',
  234. 'field3': u'test5',
  235. 'field4': u'test6',
  236. 'field5': u'test7',
  237. 'file2': (file2, file2a)
  238. })
  239. got = json.loads(response.content)
  240. self.assertEqual(got.get('file1'), 1)
  241. self.assertEqual(got.get('file2'), 2)
  242. def test_file_error_blocking(self):
  243. """
  244. The server should not block when there are upload errors (bug #8622).
  245. This can happen if something -- i.e. an exception handler -- tries to
  246. access POST while handling an error in parsing POST. This shouldn't
  247. cause an infinite loop!
  248. """
  249. class POSTAccessingHandler(client.ClientHandler):
  250. """A handler that'll access POST during an exception."""
  251. def handle_uncaught_exception(self, request, resolver, exc_info):
  252. ret = super(POSTAccessingHandler, self).handle_uncaught_exception(request, resolver, exc_info)
  253. p = request.POST
  254. return ret
  255. # Maybe this is a little more complicated that it needs to be; but if
  256. # the django.test.client.FakePayload.read() implementation changes then
  257. # this test would fail. So we need to know exactly what kind of error
  258. # it raises when there is an attempt to read more than the available bytes:
  259. try:
  260. client.FakePayload('a').read(2)
  261. except Exception as reference_error:
  262. pass
  263. # install the custom handler that tries to access request.POST
  264. self.client.handler = POSTAccessingHandler()
  265. with open(__file__) as fp:
  266. post_data = {
  267. 'name': 'Ringo',
  268. 'file_field': fp,
  269. }
  270. try:
  271. response = self.client.post('/file_uploads/upload_errors/', post_data)
  272. except reference_error.__class__ as err:
  273. self.assertFalse(
  274. str(err) == str(reference_error),
  275. "Caught a repeated exception that'll cause an infinite loop in file uploads."
  276. )
  277. except Exception as err:
  278. # CustomUploadError is the error that should have been raised
  279. self.assertEqual(err.__class__, uploadhandler.CustomUploadError)
  280. def test_filename_case_preservation(self):
  281. """
  282. The storage backend shouldn't mess with the case of the filenames
  283. uploaded.
  284. """
  285. # Synthesize the contents of a file upload with a mixed case filename
  286. # so we don't have to carry such a file in the Django tests source code
  287. # tree.
  288. vars = {'boundary': 'oUrBoUnDaRyStRiNg'}
  289. post_data = [
  290. '--%(boundary)s',
  291. 'Content-Disposition: form-data; name="file_field"; '
  292. 'filename="MiXeD_cAsE.txt"',
  293. 'Content-Type: application/octet-stream',
  294. '',
  295. 'file contents\n'
  296. '',
  297. '--%(boundary)s--\r\n',
  298. ]
  299. response = self.client.post(
  300. '/file_uploads/filename_case/',
  301. '\r\n'.join(post_data) % vars,
  302. 'multipart/form-data; boundary=%(boundary)s' % vars
  303. )
  304. self.assertEqual(response.status_code, 200)
  305. id = int(response.content)
  306. obj = FileModel.objects.get(pk=id)
  307. # The name of the file uploaded and the file stored in the server-side
  308. # shouldn't differ.
  309. self.assertEqual(os.path.basename(obj.testfile.path), 'MiXeD_cAsE.txt')
  310. class DirectoryCreationTests(unittest.TestCase):
  311. """
  312. Tests for error handling during directory creation
  313. via _save_FIELD_file (ticket #6450)
  314. """
  315. def setUp(self):
  316. self.obj = FileModel()
  317. if not os.path.isdir(temp_storage.location):
  318. os.makedirs(temp_storage.location)
  319. if os.path.isdir(UPLOAD_TO):
  320. os.chmod(UPLOAD_TO, 0700)
  321. shutil.rmtree(UPLOAD_TO)
  322. def tearDown(self):
  323. os.chmod(temp_storage.location, 0700)
  324. shutil.rmtree(temp_storage.location)
  325. def test_readonly_root(self):
  326. """Permission errors are not swallowed"""
  327. os.chmod(temp_storage.location, 0500)
  328. try:
  329. self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x'))
  330. except OSError as err:
  331. self.assertEqual(err.errno, errno.EACCES)
  332. except Exception:
  333. self.fail("OSError [Errno %s] not raised." % errno.EACCES)
  334. def test_not_a_directory(self):
  335. """The correct IOError is raised when the upload directory name exists but isn't a directory"""
  336. # Create a file with the upload directory name
  337. open(UPLOAD_TO, 'w').close()
  338. try:
  339. self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x'))
  340. except IOError as err:
  341. # The test needs to be done on a specific string as IOError
  342. # is raised even without the patch (just not early enough)
  343. self.assertEqual(err.args[0],
  344. "%s exists and is not a directory." % UPLOAD_TO)
  345. except:
  346. self.fail("IOError not raised")
  347. class MultiParserTests(unittest.TestCase):
  348. def test_empty_upload_handlers(self):
  349. # We're not actually parsing here; just checking if the parser properly
  350. # instantiates with empty upload handlers.
  351. parser = MultiPartParser({
  352. 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo',
  353. 'CONTENT_LENGTH': '1'
  354. }, StringIO('x'), [], 'utf-8')