test_media_storage.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os
  16. import shutil
  17. import tempfile
  18. from binascii import unhexlify
  19. from io import BytesIO
  20. from typing import Optional
  21. from urllib import parse
  22. from mock import Mock
  23. import attr
  24. import PIL.Image as Image
  25. from parameterized import parameterized_class
  26. from twisted.internet.defer import Deferred
  27. from synapse.logging.context import make_deferred_yieldable
  28. from synapse.rest.media.v1._base import FileInfo
  29. from synapse.rest.media.v1.filepath import MediaFilePaths
  30. from synapse.rest.media.v1.media_storage import MediaStorage
  31. from synapse.rest.media.v1.storage_provider import FileStorageProviderBackend
  32. from tests import unittest
  33. class MediaStorageTests(unittest.HomeserverTestCase):
  34. needs_threadpool = True
  35. def prepare(self, reactor, clock, hs):
  36. self.test_dir = tempfile.mkdtemp(prefix="synapse-tests-")
  37. self.addCleanup(shutil.rmtree, self.test_dir)
  38. self.primary_base_path = os.path.join(self.test_dir, "primary")
  39. self.secondary_base_path = os.path.join(self.test_dir, "secondary")
  40. hs.config.media_store_path = self.primary_base_path
  41. storage_providers = [FileStorageProviderBackend(hs, self.secondary_base_path)]
  42. self.filepaths = MediaFilePaths(self.primary_base_path)
  43. self.media_storage = MediaStorage(
  44. hs, self.primary_base_path, self.filepaths, storage_providers
  45. )
  46. def test_ensure_media_is_in_local_cache(self):
  47. media_id = "some_media_id"
  48. test_body = "Test\n"
  49. # First we create a file that is in a storage provider but not in the
  50. # local primary media store
  51. rel_path = self.filepaths.local_media_filepath_rel(media_id)
  52. secondary_path = os.path.join(self.secondary_base_path, rel_path)
  53. os.makedirs(os.path.dirname(secondary_path))
  54. with open(secondary_path, "w") as f:
  55. f.write(test_body)
  56. # Now we run ensure_media_is_in_local_cache, which should copy the file
  57. # to the local cache.
  58. file_info = FileInfo(None, media_id)
  59. # This uses a real blocking threadpool so we have to wait for it to be
  60. # actually done :/
  61. x = self.media_storage.ensure_media_is_in_local_cache(file_info)
  62. # Hotloop until the threadpool does its job...
  63. self.wait_on_thread(x)
  64. local_path = self.get_success(x)
  65. self.assertTrue(os.path.exists(local_path))
  66. # Asserts the file is under the expected local cache directory
  67. self.assertEquals(
  68. os.path.commonprefix([self.primary_base_path, local_path]),
  69. self.primary_base_path,
  70. )
  71. with open(local_path) as f:
  72. body = f.read()
  73. self.assertEqual(test_body, body)
  74. @attr.s
  75. class _TestImage:
  76. """An image for testing thumbnailing with the expected results
  77. Attributes:
  78. data: The raw image to thumbnail
  79. content_type: The type of the image as a content type, e.g. "image/png"
  80. extension: The extension associated with the format, e.g. ".png"
  81. expected_cropped: The expected bytes from cropped thumbnailing, or None if
  82. test should just check for success.
  83. expected_scaled: The expected bytes from scaled thumbnailing, or None if
  84. test should just check for a valid image returned.
  85. """
  86. data = attr.ib(type=bytes)
  87. content_type = attr.ib(type=bytes)
  88. extension = attr.ib(type=bytes)
  89. expected_cropped = attr.ib(type=Optional[bytes])
  90. expected_scaled = attr.ib(type=Optional[bytes])
  91. @parameterized_class(
  92. ("test_image",),
  93. [
  94. # smol png
  95. (
  96. _TestImage(
  97. unhexlify(
  98. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  99. b"0000001f15c4890000000a49444154789c63000100000500010d"
  100. b"0a2db40000000049454e44ae426082"
  101. ),
  102. b"image/png",
  103. b".png",
  104. unhexlify(
  105. b"89504e470d0a1a0a0000000d4948445200000020000000200806"
  106. b"000000737a7af40000001a49444154789cedc101010000008220"
  107. b"ffaf6e484001000000ef0610200001194334ee0000000049454e"
  108. b"44ae426082"
  109. ),
  110. unhexlify(
  111. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  112. b"0000001f15c4890000000d49444154789c636060606000000005"
  113. b"0001a5f645400000000049454e44ae426082"
  114. ),
  115. ),
  116. ),
  117. # small lossless webp
  118. (
  119. _TestImage(
  120. unhexlify(
  121. b"524946461a000000574542505650384c0d0000002f0000001007"
  122. b"1011118888fe0700"
  123. ),
  124. b"image/webp",
  125. b".webp",
  126. None,
  127. None,
  128. ),
  129. ),
  130. ],
  131. )
  132. class MediaRepoTests(unittest.HomeserverTestCase):
  133. hijack_auth = True
  134. user_id = "@test:user"
  135. def make_homeserver(self, reactor, clock):
  136. self.fetches = []
  137. def get_file(destination, path, output_stream, args=None, max_size=None):
  138. """
  139. Returns tuple[int,dict,str,int] of file length, response headers,
  140. absolute URI, and response code.
  141. """
  142. def write_to(r):
  143. data, response = r
  144. output_stream.write(data)
  145. return response
  146. d = Deferred()
  147. d.addCallback(write_to)
  148. self.fetches.append((d, destination, path, args))
  149. return make_deferred_yieldable(d)
  150. client = Mock()
  151. client.get_file = get_file
  152. self.storage_path = self.mktemp()
  153. self.media_store_path = self.mktemp()
  154. os.mkdir(self.storage_path)
  155. os.mkdir(self.media_store_path)
  156. config = self.default_config()
  157. config["media_store_path"] = self.media_store_path
  158. config["thumbnail_requirements"] = {}
  159. config["max_image_pixels"] = 2000000
  160. provider_config = {
  161. "module": "synapse.rest.media.v1.storage_provider.FileStorageProviderBackend",
  162. "store_local": True,
  163. "store_synchronous": False,
  164. "store_remote": True,
  165. "config": {"directory": self.storage_path},
  166. }
  167. config["media_storage_providers"] = [provider_config]
  168. hs = self.setup_test_homeserver(config=config, http_client=client)
  169. return hs
  170. def prepare(self, reactor, clock, hs):
  171. self.media_repo = hs.get_media_repository_resource()
  172. self.download_resource = self.media_repo.children[b"download"]
  173. self.thumbnail_resource = self.media_repo.children[b"thumbnail"]
  174. self.media_id = "example.com/12345"
  175. def _req(self, content_disposition):
  176. request, channel = self.make_request("GET", self.media_id, shorthand=False)
  177. request.render(self.download_resource)
  178. self.pump()
  179. # We've made one fetch, to example.com, using the media URL, and asking
  180. # the other server not to do a remote fetch
  181. self.assertEqual(len(self.fetches), 1)
  182. self.assertEqual(self.fetches[0][1], "example.com")
  183. self.assertEqual(
  184. self.fetches[0][2], "/_matrix/media/v1/download/" + self.media_id
  185. )
  186. self.assertEqual(self.fetches[0][3], {"allow_remote": "false"})
  187. headers = {
  188. b"Content-Length": [b"%d" % (len(self.test_image.data))],
  189. b"Content-Type": [self.test_image.content_type],
  190. }
  191. if content_disposition:
  192. headers[b"Content-Disposition"] = [content_disposition]
  193. self.fetches[0][0].callback(
  194. (self.test_image.data, (len(self.test_image.data), headers))
  195. )
  196. self.pump()
  197. self.assertEqual(channel.code, 200)
  198. return channel
  199. def test_disposition_filename_ascii(self):
  200. """
  201. If the filename is filename=<ascii> then Synapse will decode it as an
  202. ASCII string, and use filename= in the response.
  203. """
  204. channel = self._req(b"inline; filename=out" + self.test_image.extension)
  205. headers = channel.headers
  206. self.assertEqual(
  207. headers.getRawHeaders(b"Content-Type"), [self.test_image.content_type]
  208. )
  209. self.assertEqual(
  210. headers.getRawHeaders(b"Content-Disposition"),
  211. [b"inline; filename=out" + self.test_image.extension],
  212. )
  213. def test_disposition_filenamestar_utf8escaped(self):
  214. """
  215. If the filename is filename=*utf8''<utf8 escaped> then Synapse will
  216. correctly decode it as the UTF-8 string, and use filename* in the
  217. response.
  218. """
  219. filename = parse.quote("\u2603".encode("utf8")).encode("ascii")
  220. channel = self._req(
  221. b"inline; filename*=utf-8''" + filename + self.test_image.extension
  222. )
  223. headers = channel.headers
  224. self.assertEqual(
  225. headers.getRawHeaders(b"Content-Type"), [self.test_image.content_type]
  226. )
  227. self.assertEqual(
  228. headers.getRawHeaders(b"Content-Disposition"),
  229. [b"inline; filename*=utf-8''" + filename + self.test_image.extension],
  230. )
  231. def test_disposition_none(self):
  232. """
  233. If there is no filename, one isn't passed on in the Content-Disposition
  234. of the request.
  235. """
  236. channel = self._req(None)
  237. headers = channel.headers
  238. self.assertEqual(
  239. headers.getRawHeaders(b"Content-Type"), [self.test_image.content_type]
  240. )
  241. self.assertEqual(headers.getRawHeaders(b"Content-Disposition"), None)
  242. def test_thumbnail_crop(self):
  243. self._test_thumbnail("crop", self.test_image.expected_cropped)
  244. def test_thumbnail_scale(self):
  245. self._test_thumbnail("scale", self.test_image.expected_scaled)
  246. def _test_thumbnail(self, method, expected_body):
  247. params = "?width=32&height=32&method=" + method
  248. request, channel = self.make_request(
  249. "GET", self.media_id + params, shorthand=False
  250. )
  251. request.render(self.thumbnail_resource)
  252. self.pump()
  253. headers = {
  254. b"Content-Length": [b"%d" % (len(self.test_image.data))],
  255. b"Content-Type": [self.test_image.content_type],
  256. }
  257. self.fetches[0][0].callback(
  258. (self.test_image.data, (len(self.test_image.data), headers))
  259. )
  260. self.pump()
  261. self.assertEqual(channel.code, 200)
  262. if expected_body is not None:
  263. self.assertEqual(
  264. channel.result["body"], expected_body, channel.result["body"]
  265. )
  266. else:
  267. # ensure that the result is at least some valid image
  268. Image.open(BytesIO(channel.result["body"]))