test_media.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2020 Dirk Klimpel
  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 json
  16. import os
  17. from binascii import unhexlify
  18. import synapse.rest.admin
  19. from synapse.api.errors import Codes
  20. from synapse.rest.client.v1 import login, profile, room
  21. from synapse.rest.media.v1.filepath import MediaFilePaths
  22. from tests import unittest
  23. from tests.server import FakeSite, make_request
  24. class DeleteMediaByIDTestCase(unittest.HomeserverTestCase):
  25. servlets = [
  26. synapse.rest.admin.register_servlets,
  27. synapse.rest.admin.register_servlets_for_media_repo,
  28. login.register_servlets,
  29. ]
  30. def prepare(self, reactor, clock, hs):
  31. self.media_repo = hs.get_media_repository_resource()
  32. self.server_name = hs.hostname
  33. self.admin_user = self.register_user("admin", "pass", admin=True)
  34. self.admin_user_tok = self.login("admin", "pass")
  35. self.filepaths = MediaFilePaths(hs.config.media_store_path)
  36. def test_no_auth(self):
  37. """
  38. Try to delete media without authentication.
  39. """
  40. url = "/_synapse/admin/v1/media/%s/%s" % (self.server_name, "12345")
  41. channel = self.make_request("DELETE", url, b"{}")
  42. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  43. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  44. def test_requester_is_no_admin(self):
  45. """
  46. If the user is not a server admin, an error is returned.
  47. """
  48. self.other_user = self.register_user("user", "pass")
  49. self.other_user_token = self.login("user", "pass")
  50. url = "/_synapse/admin/v1/media/%s/%s" % (self.server_name, "12345")
  51. channel = self.make_request("DELETE", url, access_token=self.other_user_token,)
  52. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  53. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  54. def test_media_does_not_exist(self):
  55. """
  56. Tests that a lookup for a media that does not exist returns a 404
  57. """
  58. url = "/_synapse/admin/v1/media/%s/%s" % (self.server_name, "12345")
  59. channel = self.make_request("DELETE", url, access_token=self.admin_user_tok,)
  60. self.assertEqual(404, channel.code, msg=channel.json_body)
  61. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  62. def test_media_is_not_local(self):
  63. """
  64. Tests that a lookup for a media that is not a local returns a 400
  65. """
  66. url = "/_synapse/admin/v1/media/%s/%s" % ("unknown_domain", "12345")
  67. channel = self.make_request("DELETE", url, access_token=self.admin_user_tok,)
  68. self.assertEqual(400, channel.code, msg=channel.json_body)
  69. self.assertEqual("Can only delete local media", channel.json_body["error"])
  70. def test_delete_media(self):
  71. """
  72. Tests that delete a media is successfully
  73. """
  74. download_resource = self.media_repo.children[b"download"]
  75. upload_resource = self.media_repo.children[b"upload"]
  76. image_data = unhexlify(
  77. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  78. b"0000001f15c4890000000a49444154789c63000100000500010d"
  79. b"0a2db40000000049454e44ae426082"
  80. )
  81. # Upload some media into the room
  82. response = self.helper.upload_media(
  83. upload_resource, image_data, tok=self.admin_user_tok, expect_code=200
  84. )
  85. # Extract media ID from the response
  86. server_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
  87. server_name, media_id = server_and_media_id.split("/")
  88. self.assertEqual(server_name, self.server_name)
  89. # Attempt to access media
  90. channel = make_request(
  91. self.reactor,
  92. FakeSite(download_resource),
  93. "GET",
  94. server_and_media_id,
  95. shorthand=False,
  96. access_token=self.admin_user_tok,
  97. )
  98. # Should be successful
  99. self.assertEqual(
  100. 200,
  101. channel.code,
  102. msg=(
  103. "Expected to receive a 200 on accessing media: %s" % server_and_media_id
  104. ),
  105. )
  106. # Test if the file exists
  107. local_path = self.filepaths.local_media_filepath(media_id)
  108. self.assertTrue(os.path.exists(local_path))
  109. url = "/_synapse/admin/v1/media/%s/%s" % (self.server_name, media_id)
  110. # Delete media
  111. channel = self.make_request("DELETE", url, access_token=self.admin_user_tok,)
  112. self.assertEqual(200, channel.code, msg=channel.json_body)
  113. self.assertEqual(1, channel.json_body["total"])
  114. self.assertEqual(
  115. media_id, channel.json_body["deleted_media"][0],
  116. )
  117. # Attempt to access media
  118. channel = make_request(
  119. self.reactor,
  120. FakeSite(download_resource),
  121. "GET",
  122. server_and_media_id,
  123. shorthand=False,
  124. access_token=self.admin_user_tok,
  125. )
  126. self.assertEqual(
  127. 404,
  128. channel.code,
  129. msg=(
  130. "Expected to receive a 404 on accessing deleted media: %s"
  131. % server_and_media_id
  132. ),
  133. )
  134. # Test if the file is deleted
  135. self.assertFalse(os.path.exists(local_path))
  136. class DeleteMediaByDateSizeTestCase(unittest.HomeserverTestCase):
  137. servlets = [
  138. synapse.rest.admin.register_servlets,
  139. synapse.rest.admin.register_servlets_for_media_repo,
  140. login.register_servlets,
  141. profile.register_servlets,
  142. room.register_servlets,
  143. ]
  144. def prepare(self, reactor, clock, hs):
  145. self.media_repo = hs.get_media_repository_resource()
  146. self.server_name = hs.hostname
  147. self.admin_user = self.register_user("admin", "pass", admin=True)
  148. self.admin_user_tok = self.login("admin", "pass")
  149. self.filepaths = MediaFilePaths(hs.config.media_store_path)
  150. self.url = "/_synapse/admin/v1/media/%s/delete" % self.server_name
  151. def test_no_auth(self):
  152. """
  153. Try to delete media without authentication.
  154. """
  155. channel = self.make_request("POST", self.url, b"{}")
  156. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  157. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  158. def test_requester_is_no_admin(self):
  159. """
  160. If the user is not a server admin, an error is returned.
  161. """
  162. self.other_user = self.register_user("user", "pass")
  163. self.other_user_token = self.login("user", "pass")
  164. channel = self.make_request(
  165. "POST", self.url, access_token=self.other_user_token,
  166. )
  167. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  168. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  169. def test_media_is_not_local(self):
  170. """
  171. Tests that a lookup for media that is not local returns a 400
  172. """
  173. url = "/_synapse/admin/v1/media/%s/delete" % "unknown_domain"
  174. channel = self.make_request(
  175. "POST", url + "?before_ts=1234", access_token=self.admin_user_tok,
  176. )
  177. self.assertEqual(400, channel.code, msg=channel.json_body)
  178. self.assertEqual("Can only delete local media", channel.json_body["error"])
  179. def test_missing_parameter(self):
  180. """
  181. If the parameter `before_ts` is missing, an error is returned.
  182. """
  183. channel = self.make_request("POST", self.url, access_token=self.admin_user_tok,)
  184. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  185. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  186. self.assertEqual(
  187. "Missing integer query parameter b'before_ts'", channel.json_body["error"]
  188. )
  189. def test_invalid_parameter(self):
  190. """
  191. If parameters are invalid, an error is returned.
  192. """
  193. channel = self.make_request(
  194. "POST", self.url + "?before_ts=-1234", access_token=self.admin_user_tok,
  195. )
  196. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  197. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  198. self.assertEqual(
  199. "Query parameter before_ts must be a string representing a positive integer.",
  200. channel.json_body["error"],
  201. )
  202. channel = self.make_request(
  203. "POST",
  204. self.url + "?before_ts=1234&size_gt=-1234",
  205. access_token=self.admin_user_tok,
  206. )
  207. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  208. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  209. self.assertEqual(
  210. "Query parameter size_gt must be a string representing a positive integer.",
  211. channel.json_body["error"],
  212. )
  213. channel = self.make_request(
  214. "POST",
  215. self.url + "?before_ts=1234&keep_profiles=not_bool",
  216. access_token=self.admin_user_tok,
  217. )
  218. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  219. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  220. self.assertEqual(
  221. "Boolean query parameter b'keep_profiles' must be one of ['true', 'false']",
  222. channel.json_body["error"],
  223. )
  224. def test_delete_media_never_accessed(self):
  225. """
  226. Tests that media deleted if it is older than `before_ts` and never accessed
  227. `last_access_ts` is `NULL` and `created_ts` < `before_ts`
  228. """
  229. # upload and do not access
  230. server_and_media_id = self._create_media()
  231. self.pump(1.0)
  232. # test that the file exists
  233. media_id = server_and_media_id.split("/")[1]
  234. local_path = self.filepaths.local_media_filepath(media_id)
  235. self.assertTrue(os.path.exists(local_path))
  236. # timestamp after upload/create
  237. now_ms = self.clock.time_msec()
  238. channel = self.make_request(
  239. "POST",
  240. self.url + "?before_ts=" + str(now_ms),
  241. access_token=self.admin_user_tok,
  242. )
  243. self.assertEqual(200, channel.code, msg=channel.json_body)
  244. self.assertEqual(1, channel.json_body["total"])
  245. self.assertEqual(
  246. media_id, channel.json_body["deleted_media"][0],
  247. )
  248. self._access_media(server_and_media_id, False)
  249. def test_keep_media_by_date(self):
  250. """
  251. Tests that media is not deleted if it is newer than `before_ts`
  252. """
  253. # timestamp before upload
  254. now_ms = self.clock.time_msec()
  255. server_and_media_id = self._create_media()
  256. self._access_media(server_and_media_id)
  257. channel = self.make_request(
  258. "POST",
  259. self.url + "?before_ts=" + str(now_ms),
  260. access_token=self.admin_user_tok,
  261. )
  262. self.assertEqual(200, channel.code, msg=channel.json_body)
  263. self.assertEqual(0, channel.json_body["total"])
  264. self._access_media(server_and_media_id)
  265. # timestamp after upload
  266. now_ms = self.clock.time_msec()
  267. channel = self.make_request(
  268. "POST",
  269. self.url + "?before_ts=" + str(now_ms),
  270. access_token=self.admin_user_tok,
  271. )
  272. self.assertEqual(200, channel.code, msg=channel.json_body)
  273. self.assertEqual(1, channel.json_body["total"])
  274. self.assertEqual(
  275. server_and_media_id.split("/")[1], channel.json_body["deleted_media"][0],
  276. )
  277. self._access_media(server_and_media_id, False)
  278. def test_keep_media_by_size(self):
  279. """
  280. Tests that media is not deleted if its size is smaller than or equal
  281. to `size_gt`
  282. """
  283. server_and_media_id = self._create_media()
  284. self._access_media(server_and_media_id)
  285. now_ms = self.clock.time_msec()
  286. channel = self.make_request(
  287. "POST",
  288. self.url + "?before_ts=" + str(now_ms) + "&size_gt=67",
  289. access_token=self.admin_user_tok,
  290. )
  291. self.assertEqual(200, channel.code, msg=channel.json_body)
  292. self.assertEqual(0, channel.json_body["total"])
  293. self._access_media(server_and_media_id)
  294. now_ms = self.clock.time_msec()
  295. channel = self.make_request(
  296. "POST",
  297. self.url + "?before_ts=" + str(now_ms) + "&size_gt=66",
  298. access_token=self.admin_user_tok,
  299. )
  300. self.assertEqual(200, channel.code, msg=channel.json_body)
  301. self.assertEqual(1, channel.json_body["total"])
  302. self.assertEqual(
  303. server_and_media_id.split("/")[1], channel.json_body["deleted_media"][0],
  304. )
  305. self._access_media(server_and_media_id, False)
  306. def test_keep_media_by_user_avatar(self):
  307. """
  308. Tests that we do not delete media if is used as a user avatar
  309. Tests parameter `keep_profiles`
  310. """
  311. server_and_media_id = self._create_media()
  312. self._access_media(server_and_media_id)
  313. # set media as avatar
  314. channel = self.make_request(
  315. "PUT",
  316. "/profile/%s/avatar_url" % (self.admin_user,),
  317. content=json.dumps({"avatar_url": "mxc://%s" % (server_and_media_id,)}),
  318. access_token=self.admin_user_tok,
  319. )
  320. self.assertEqual(200, channel.code, msg=channel.json_body)
  321. now_ms = self.clock.time_msec()
  322. channel = self.make_request(
  323. "POST",
  324. self.url + "?before_ts=" + str(now_ms) + "&keep_profiles=true",
  325. access_token=self.admin_user_tok,
  326. )
  327. self.assertEqual(200, channel.code, msg=channel.json_body)
  328. self.assertEqual(0, channel.json_body["total"])
  329. self._access_media(server_and_media_id)
  330. now_ms = self.clock.time_msec()
  331. channel = self.make_request(
  332. "POST",
  333. self.url + "?before_ts=" + str(now_ms) + "&keep_profiles=false",
  334. access_token=self.admin_user_tok,
  335. )
  336. self.assertEqual(200, channel.code, msg=channel.json_body)
  337. self.assertEqual(1, channel.json_body["total"])
  338. self.assertEqual(
  339. server_and_media_id.split("/")[1], channel.json_body["deleted_media"][0],
  340. )
  341. self._access_media(server_and_media_id, False)
  342. def test_keep_media_by_room_avatar(self):
  343. """
  344. Tests that we do not delete media if it is used as a room avatar
  345. Tests parameter `keep_profiles`
  346. """
  347. server_and_media_id = self._create_media()
  348. self._access_media(server_and_media_id)
  349. # set media as room avatar
  350. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  351. channel = self.make_request(
  352. "PUT",
  353. "/rooms/%s/state/m.room.avatar" % (room_id,),
  354. content=json.dumps({"url": "mxc://%s" % (server_and_media_id,)}),
  355. access_token=self.admin_user_tok,
  356. )
  357. self.assertEqual(200, channel.code, msg=channel.json_body)
  358. now_ms = self.clock.time_msec()
  359. channel = self.make_request(
  360. "POST",
  361. self.url + "?before_ts=" + str(now_ms) + "&keep_profiles=true",
  362. access_token=self.admin_user_tok,
  363. )
  364. self.assertEqual(200, channel.code, msg=channel.json_body)
  365. self.assertEqual(0, channel.json_body["total"])
  366. self._access_media(server_and_media_id)
  367. now_ms = self.clock.time_msec()
  368. channel = self.make_request(
  369. "POST",
  370. self.url + "?before_ts=" + str(now_ms) + "&keep_profiles=false",
  371. access_token=self.admin_user_tok,
  372. )
  373. self.assertEqual(200, channel.code, msg=channel.json_body)
  374. self.assertEqual(1, channel.json_body["total"])
  375. self.assertEqual(
  376. server_and_media_id.split("/")[1], channel.json_body["deleted_media"][0],
  377. )
  378. self._access_media(server_and_media_id, False)
  379. def _create_media(self):
  380. """
  381. Create a media and return media_id and server_and_media_id
  382. """
  383. upload_resource = self.media_repo.children[b"upload"]
  384. # file size is 67 Byte
  385. image_data = unhexlify(
  386. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  387. b"0000001f15c4890000000a49444154789c63000100000500010d"
  388. b"0a2db40000000049454e44ae426082"
  389. )
  390. # Upload some media into the room
  391. response = self.helper.upload_media(
  392. upload_resource, image_data, tok=self.admin_user_tok, expect_code=200
  393. )
  394. # Extract media ID from the response
  395. server_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
  396. server_name = server_and_media_id.split("/")[0]
  397. # Check that new media is a local and not remote
  398. self.assertEqual(server_name, self.server_name)
  399. return server_and_media_id
  400. def _access_media(self, server_and_media_id, expect_success=True):
  401. """
  402. Try to access a media and check the result
  403. """
  404. download_resource = self.media_repo.children[b"download"]
  405. media_id = server_and_media_id.split("/")[1]
  406. local_path = self.filepaths.local_media_filepath(media_id)
  407. channel = make_request(
  408. self.reactor,
  409. FakeSite(download_resource),
  410. "GET",
  411. server_and_media_id,
  412. shorthand=False,
  413. access_token=self.admin_user_tok,
  414. )
  415. if expect_success:
  416. self.assertEqual(
  417. 200,
  418. channel.code,
  419. msg=(
  420. "Expected to receive a 200 on accessing media: %s"
  421. % server_and_media_id
  422. ),
  423. )
  424. # Test that the file exists
  425. self.assertTrue(os.path.exists(local_path))
  426. else:
  427. self.assertEqual(
  428. 404,
  429. channel.code,
  430. msg=(
  431. "Expected to receive a 404 on accessing deleted media: %s"
  432. % (server_and_media_id)
  433. ),
  434. )
  435. # Test that the file is deleted
  436. self.assertFalse(os.path.exists(local_path))