test_media.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. # Copyright 2020 Dirk Klimpel
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import json
  15. import os
  16. from binascii import unhexlify
  17. from parameterized import parameterized
  18. import synapse.rest.admin
  19. from synapse.api.errors import Codes
  20. from synapse.rest.client 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(
  52. "DELETE",
  53. url,
  54. access_token=self.other_user_token,
  55. )
  56. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  57. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  58. def test_media_does_not_exist(self):
  59. """
  60. Tests that a lookup for a media that does not exist returns a 404
  61. """
  62. url = "/_synapse/admin/v1/media/%s/%s" % (self.server_name, "12345")
  63. channel = self.make_request(
  64. "DELETE",
  65. url,
  66. access_token=self.admin_user_tok,
  67. )
  68. self.assertEqual(404, channel.code, msg=channel.json_body)
  69. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  70. def test_media_is_not_local(self):
  71. """
  72. Tests that a lookup for a media that is not a local returns a 400
  73. """
  74. url = "/_synapse/admin/v1/media/%s/%s" % ("unknown_domain", "12345")
  75. channel = self.make_request(
  76. "DELETE",
  77. url,
  78. access_token=self.admin_user_tok,
  79. )
  80. self.assertEqual(400, channel.code, msg=channel.json_body)
  81. self.assertEqual("Can only delete local media", channel.json_body["error"])
  82. def test_delete_media(self):
  83. """
  84. Tests that delete a media is successfully
  85. """
  86. download_resource = self.media_repo.children[b"download"]
  87. upload_resource = self.media_repo.children[b"upload"]
  88. image_data = unhexlify(
  89. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  90. b"0000001f15c4890000000a49444154789c63000100000500010d"
  91. b"0a2db40000000049454e44ae426082"
  92. )
  93. # Upload some media into the room
  94. response = self.helper.upload_media(
  95. upload_resource, image_data, tok=self.admin_user_tok, expect_code=200
  96. )
  97. # Extract media ID from the response
  98. server_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
  99. server_name, media_id = server_and_media_id.split("/")
  100. self.assertEqual(server_name, self.server_name)
  101. # Attempt to access media
  102. channel = make_request(
  103. self.reactor,
  104. FakeSite(download_resource),
  105. "GET",
  106. server_and_media_id,
  107. shorthand=False,
  108. access_token=self.admin_user_tok,
  109. )
  110. # Should be successful
  111. self.assertEqual(
  112. 200,
  113. channel.code,
  114. msg=(
  115. "Expected to receive a 200 on accessing media: %s" % server_and_media_id
  116. ),
  117. )
  118. # Test if the file exists
  119. local_path = self.filepaths.local_media_filepath(media_id)
  120. self.assertTrue(os.path.exists(local_path))
  121. url = "/_synapse/admin/v1/media/%s/%s" % (self.server_name, media_id)
  122. # Delete media
  123. channel = self.make_request(
  124. "DELETE",
  125. url,
  126. access_token=self.admin_user_tok,
  127. )
  128. self.assertEqual(200, channel.code, msg=channel.json_body)
  129. self.assertEqual(1, channel.json_body["total"])
  130. self.assertEqual(
  131. media_id,
  132. channel.json_body["deleted_media"][0],
  133. )
  134. # Attempt to access media
  135. channel = make_request(
  136. self.reactor,
  137. FakeSite(download_resource),
  138. "GET",
  139. server_and_media_id,
  140. shorthand=False,
  141. access_token=self.admin_user_tok,
  142. )
  143. self.assertEqual(
  144. 404,
  145. channel.code,
  146. msg=(
  147. "Expected to receive a 404 on accessing deleted media: %s"
  148. % server_and_media_id
  149. ),
  150. )
  151. # Test if the file is deleted
  152. self.assertFalse(os.path.exists(local_path))
  153. class DeleteMediaByDateSizeTestCase(unittest.HomeserverTestCase):
  154. servlets = [
  155. synapse.rest.admin.register_servlets,
  156. synapse.rest.admin.register_servlets_for_media_repo,
  157. login.register_servlets,
  158. profile.register_servlets,
  159. room.register_servlets,
  160. ]
  161. def prepare(self, reactor, clock, hs):
  162. self.media_repo = hs.get_media_repository_resource()
  163. self.server_name = hs.hostname
  164. self.admin_user = self.register_user("admin", "pass", admin=True)
  165. self.admin_user_tok = self.login("admin", "pass")
  166. self.filepaths = MediaFilePaths(hs.config.media_store_path)
  167. self.url = "/_synapse/admin/v1/media/%s/delete" % self.server_name
  168. def test_no_auth(self):
  169. """
  170. Try to delete media without authentication.
  171. """
  172. channel = self.make_request("POST", self.url, b"{}")
  173. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  174. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  175. def test_requester_is_no_admin(self):
  176. """
  177. If the user is not a server admin, an error is returned.
  178. """
  179. self.other_user = self.register_user("user", "pass")
  180. self.other_user_token = self.login("user", "pass")
  181. channel = self.make_request(
  182. "POST",
  183. self.url,
  184. access_token=self.other_user_token,
  185. )
  186. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  187. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  188. def test_media_is_not_local(self):
  189. """
  190. Tests that a lookup for media that is not local returns a 400
  191. """
  192. url = "/_synapse/admin/v1/media/%s/delete" % "unknown_domain"
  193. channel = self.make_request(
  194. "POST",
  195. url + "?before_ts=1234",
  196. access_token=self.admin_user_tok,
  197. )
  198. self.assertEqual(400, channel.code, msg=channel.json_body)
  199. self.assertEqual("Can only delete local media", channel.json_body["error"])
  200. def test_missing_parameter(self):
  201. """
  202. If the parameter `before_ts` is missing, an error is returned.
  203. """
  204. channel = self.make_request(
  205. "POST",
  206. self.url,
  207. access_token=self.admin_user_tok,
  208. )
  209. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  210. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  211. self.assertEqual(
  212. "Missing integer query parameter 'before_ts'", channel.json_body["error"]
  213. )
  214. def test_invalid_parameter(self):
  215. """
  216. If parameters are invalid, an error is returned.
  217. """
  218. channel = self.make_request(
  219. "POST",
  220. self.url + "?before_ts=-1234",
  221. access_token=self.admin_user_tok,
  222. )
  223. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  224. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  225. self.assertEqual(
  226. "Query parameter before_ts must be a string representing a positive integer.",
  227. channel.json_body["error"],
  228. )
  229. channel = self.make_request(
  230. "POST",
  231. self.url + "?before_ts=1234&size_gt=-1234",
  232. access_token=self.admin_user_tok,
  233. )
  234. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  235. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  236. self.assertEqual(
  237. "Query parameter size_gt must be a string representing a positive integer.",
  238. channel.json_body["error"],
  239. )
  240. channel = self.make_request(
  241. "POST",
  242. self.url + "?before_ts=1234&keep_profiles=not_bool",
  243. access_token=self.admin_user_tok,
  244. )
  245. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  246. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  247. self.assertEqual(
  248. "Boolean query parameter 'keep_profiles' must be one of ['true', 'false']",
  249. channel.json_body["error"],
  250. )
  251. def test_delete_media_never_accessed(self):
  252. """
  253. Tests that media deleted if it is older than `before_ts` and never accessed
  254. `last_access_ts` is `NULL` and `created_ts` < `before_ts`
  255. """
  256. # upload and do not access
  257. server_and_media_id = self._create_media()
  258. self.pump(1.0)
  259. # test that the file exists
  260. media_id = server_and_media_id.split("/")[1]
  261. local_path = self.filepaths.local_media_filepath(media_id)
  262. self.assertTrue(os.path.exists(local_path))
  263. # timestamp after upload/create
  264. now_ms = self.clock.time_msec()
  265. channel = self.make_request(
  266. "POST",
  267. self.url + "?before_ts=" + str(now_ms),
  268. access_token=self.admin_user_tok,
  269. )
  270. self.assertEqual(200, channel.code, msg=channel.json_body)
  271. self.assertEqual(1, channel.json_body["total"])
  272. self.assertEqual(
  273. media_id,
  274. channel.json_body["deleted_media"][0],
  275. )
  276. self._access_media(server_and_media_id, False)
  277. def test_keep_media_by_date(self):
  278. """
  279. Tests that media is not deleted if it is newer than `before_ts`
  280. """
  281. # timestamp before upload
  282. now_ms = self.clock.time_msec()
  283. server_and_media_id = self._create_media()
  284. self._access_media(server_and_media_id)
  285. channel = self.make_request(
  286. "POST",
  287. self.url + "?before_ts=" + str(now_ms),
  288. access_token=self.admin_user_tok,
  289. )
  290. self.assertEqual(200, channel.code, msg=channel.json_body)
  291. self.assertEqual(0, channel.json_body["total"])
  292. self._access_media(server_and_media_id)
  293. # timestamp after upload
  294. now_ms = self.clock.time_msec()
  295. channel = self.make_request(
  296. "POST",
  297. self.url + "?before_ts=" + str(now_ms),
  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],
  304. channel.json_body["deleted_media"][0],
  305. )
  306. self._access_media(server_and_media_id, False)
  307. def test_keep_media_by_size(self):
  308. """
  309. Tests that media is not deleted if its size is smaller than or equal
  310. to `size_gt`
  311. """
  312. server_and_media_id = self._create_media()
  313. self._access_media(server_and_media_id)
  314. now_ms = self.clock.time_msec()
  315. channel = self.make_request(
  316. "POST",
  317. self.url + "?before_ts=" + str(now_ms) + "&size_gt=67",
  318. access_token=self.admin_user_tok,
  319. )
  320. self.assertEqual(200, channel.code, msg=channel.json_body)
  321. self.assertEqual(0, channel.json_body["total"])
  322. self._access_media(server_and_media_id)
  323. now_ms = self.clock.time_msec()
  324. channel = self.make_request(
  325. "POST",
  326. self.url + "?before_ts=" + str(now_ms) + "&size_gt=66",
  327. access_token=self.admin_user_tok,
  328. )
  329. self.assertEqual(200, channel.code, msg=channel.json_body)
  330. self.assertEqual(1, channel.json_body["total"])
  331. self.assertEqual(
  332. server_and_media_id.split("/")[1],
  333. channel.json_body["deleted_media"][0],
  334. )
  335. self._access_media(server_and_media_id, False)
  336. def test_keep_media_by_user_avatar(self):
  337. """
  338. Tests that we do not delete media if is used as a user avatar
  339. Tests parameter `keep_profiles`
  340. """
  341. server_and_media_id = self._create_media()
  342. self._access_media(server_and_media_id)
  343. # set media as avatar
  344. channel = self.make_request(
  345. "PUT",
  346. "/profile/%s/avatar_url" % (self.admin_user,),
  347. content=json.dumps({"avatar_url": "mxc://%s" % (server_and_media_id,)}),
  348. access_token=self.admin_user_tok,
  349. )
  350. self.assertEqual(200, channel.code, msg=channel.json_body)
  351. now_ms = self.clock.time_msec()
  352. channel = self.make_request(
  353. "POST",
  354. self.url + "?before_ts=" + str(now_ms) + "&keep_profiles=true",
  355. access_token=self.admin_user_tok,
  356. )
  357. self.assertEqual(200, channel.code, msg=channel.json_body)
  358. self.assertEqual(0, channel.json_body["total"])
  359. self._access_media(server_and_media_id)
  360. now_ms = self.clock.time_msec()
  361. channel = self.make_request(
  362. "POST",
  363. self.url + "?before_ts=" + str(now_ms) + "&keep_profiles=false",
  364. access_token=self.admin_user_tok,
  365. )
  366. self.assertEqual(200, channel.code, msg=channel.json_body)
  367. self.assertEqual(1, channel.json_body["total"])
  368. self.assertEqual(
  369. server_and_media_id.split("/")[1],
  370. channel.json_body["deleted_media"][0],
  371. )
  372. self._access_media(server_and_media_id, False)
  373. def test_keep_media_by_room_avatar(self):
  374. """
  375. Tests that we do not delete media if it is used as a room avatar
  376. Tests parameter `keep_profiles`
  377. """
  378. server_and_media_id = self._create_media()
  379. self._access_media(server_and_media_id)
  380. # set media as room avatar
  381. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  382. channel = self.make_request(
  383. "PUT",
  384. "/rooms/%s/state/m.room.avatar" % (room_id,),
  385. content=json.dumps({"url": "mxc://%s" % (server_and_media_id,)}),
  386. access_token=self.admin_user_tok,
  387. )
  388. self.assertEqual(200, channel.code, msg=channel.json_body)
  389. now_ms = self.clock.time_msec()
  390. channel = self.make_request(
  391. "POST",
  392. self.url + "?before_ts=" + str(now_ms) + "&keep_profiles=true",
  393. access_token=self.admin_user_tok,
  394. )
  395. self.assertEqual(200, channel.code, msg=channel.json_body)
  396. self.assertEqual(0, channel.json_body["total"])
  397. self._access_media(server_and_media_id)
  398. now_ms = self.clock.time_msec()
  399. channel = self.make_request(
  400. "POST",
  401. self.url + "?before_ts=" + str(now_ms) + "&keep_profiles=false",
  402. access_token=self.admin_user_tok,
  403. )
  404. self.assertEqual(200, channel.code, msg=channel.json_body)
  405. self.assertEqual(1, channel.json_body["total"])
  406. self.assertEqual(
  407. server_and_media_id.split("/")[1],
  408. channel.json_body["deleted_media"][0],
  409. )
  410. self._access_media(server_and_media_id, False)
  411. def _create_media(self):
  412. """
  413. Create a media and return media_id and server_and_media_id
  414. """
  415. upload_resource = self.media_repo.children[b"upload"]
  416. # file size is 67 Byte
  417. image_data = unhexlify(
  418. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  419. b"0000001f15c4890000000a49444154789c63000100000500010d"
  420. b"0a2db40000000049454e44ae426082"
  421. )
  422. # Upload some media into the room
  423. response = self.helper.upload_media(
  424. upload_resource, image_data, tok=self.admin_user_tok, expect_code=200
  425. )
  426. # Extract media ID from the response
  427. server_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
  428. server_name = server_and_media_id.split("/")[0]
  429. # Check that new media is a local and not remote
  430. self.assertEqual(server_name, self.server_name)
  431. return server_and_media_id
  432. def _access_media(self, server_and_media_id, expect_success=True):
  433. """
  434. Try to access a media and check the result
  435. """
  436. download_resource = self.media_repo.children[b"download"]
  437. media_id = server_and_media_id.split("/")[1]
  438. local_path = self.filepaths.local_media_filepath(media_id)
  439. channel = make_request(
  440. self.reactor,
  441. FakeSite(download_resource),
  442. "GET",
  443. server_and_media_id,
  444. shorthand=False,
  445. access_token=self.admin_user_tok,
  446. )
  447. if expect_success:
  448. self.assertEqual(
  449. 200,
  450. channel.code,
  451. msg=(
  452. "Expected to receive a 200 on accessing media: %s"
  453. % server_and_media_id
  454. ),
  455. )
  456. # Test that the file exists
  457. self.assertTrue(os.path.exists(local_path))
  458. else:
  459. self.assertEqual(
  460. 404,
  461. channel.code,
  462. msg=(
  463. "Expected to receive a 404 on accessing deleted media: %s"
  464. % (server_and_media_id)
  465. ),
  466. )
  467. # Test that the file is deleted
  468. self.assertFalse(os.path.exists(local_path))
  469. class QuarantineMediaByIDTestCase(unittest.HomeserverTestCase):
  470. servlets = [
  471. synapse.rest.admin.register_servlets,
  472. synapse.rest.admin.register_servlets_for_media_repo,
  473. login.register_servlets,
  474. ]
  475. def prepare(self, reactor, clock, hs):
  476. media_repo = hs.get_media_repository_resource()
  477. self.store = hs.get_datastore()
  478. self.server_name = hs.hostname
  479. self.admin_user = self.register_user("admin", "pass", admin=True)
  480. self.admin_user_tok = self.login("admin", "pass")
  481. # Create media
  482. upload_resource = media_repo.children[b"upload"]
  483. # file size is 67 Byte
  484. image_data = unhexlify(
  485. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  486. b"0000001f15c4890000000a49444154789c63000100000500010d"
  487. b"0a2db40000000049454e44ae426082"
  488. )
  489. # Upload some media into the room
  490. response = self.helper.upload_media(
  491. upload_resource, image_data, tok=self.admin_user_tok, expect_code=200
  492. )
  493. # Extract media ID from the response
  494. server_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
  495. self.media_id = server_and_media_id.split("/")[1]
  496. self.url = "/_synapse/admin/v1/media/%s/%s/%s"
  497. @parameterized.expand(["quarantine", "unquarantine"])
  498. def test_no_auth(self, action: str):
  499. """
  500. Try to protect media without authentication.
  501. """
  502. channel = self.make_request(
  503. "POST",
  504. self.url % (action, self.server_name, self.media_id),
  505. b"{}",
  506. )
  507. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  508. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  509. @parameterized.expand(["quarantine", "unquarantine"])
  510. def test_requester_is_no_admin(self, action: str):
  511. """
  512. If the user is not a server admin, an error is returned.
  513. """
  514. self.other_user = self.register_user("user", "pass")
  515. self.other_user_token = self.login("user", "pass")
  516. channel = self.make_request(
  517. "POST",
  518. self.url % (action, self.server_name, self.media_id),
  519. access_token=self.other_user_token,
  520. )
  521. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  522. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  523. def test_quarantine_media(self):
  524. """
  525. Tests that quarantining and remove from quarantine a media is successfully
  526. """
  527. media_info = self.get_success(self.store.get_local_media(self.media_id))
  528. self.assertFalse(media_info["quarantined_by"])
  529. # quarantining
  530. channel = self.make_request(
  531. "POST",
  532. self.url % ("quarantine", self.server_name, self.media_id),
  533. access_token=self.admin_user_tok,
  534. )
  535. self.assertEqual(200, channel.code, msg=channel.json_body)
  536. self.assertFalse(channel.json_body)
  537. media_info = self.get_success(self.store.get_local_media(self.media_id))
  538. self.assertTrue(media_info["quarantined_by"])
  539. # remove from quarantine
  540. channel = self.make_request(
  541. "POST",
  542. self.url % ("unquarantine", self.server_name, self.media_id),
  543. access_token=self.admin_user_tok,
  544. )
  545. self.assertEqual(200, channel.code, msg=channel.json_body)
  546. self.assertFalse(channel.json_body)
  547. media_info = self.get_success(self.store.get_local_media(self.media_id))
  548. self.assertFalse(media_info["quarantined_by"])
  549. def test_quarantine_protected_media(self):
  550. """
  551. Tests that quarantining from protected media fails
  552. """
  553. # protect
  554. self.get_success(self.store.mark_local_media_as_safe(self.media_id, safe=True))
  555. # verify protection
  556. media_info = self.get_success(self.store.get_local_media(self.media_id))
  557. self.assertTrue(media_info["safe_from_quarantine"])
  558. # quarantining
  559. channel = self.make_request(
  560. "POST",
  561. self.url % ("quarantine", self.server_name, self.media_id),
  562. access_token=self.admin_user_tok,
  563. )
  564. self.assertEqual(200, channel.code, msg=channel.json_body)
  565. self.assertFalse(channel.json_body)
  566. # verify that is not in quarantine
  567. media_info = self.get_success(self.store.get_local_media(self.media_id))
  568. self.assertFalse(media_info["quarantined_by"])
  569. class ProtectMediaByIDTestCase(unittest.HomeserverTestCase):
  570. servlets = [
  571. synapse.rest.admin.register_servlets,
  572. synapse.rest.admin.register_servlets_for_media_repo,
  573. login.register_servlets,
  574. ]
  575. def prepare(self, reactor, clock, hs):
  576. media_repo = hs.get_media_repository_resource()
  577. self.store = hs.get_datastore()
  578. self.admin_user = self.register_user("admin", "pass", admin=True)
  579. self.admin_user_tok = self.login("admin", "pass")
  580. # Create media
  581. upload_resource = media_repo.children[b"upload"]
  582. # file size is 67 Byte
  583. image_data = unhexlify(
  584. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  585. b"0000001f15c4890000000a49444154789c63000100000500010d"
  586. b"0a2db40000000049454e44ae426082"
  587. )
  588. # Upload some media into the room
  589. response = self.helper.upload_media(
  590. upload_resource, image_data, tok=self.admin_user_tok, expect_code=200
  591. )
  592. # Extract media ID from the response
  593. server_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
  594. self.media_id = server_and_media_id.split("/")[1]
  595. self.url = "/_synapse/admin/v1/media/%s/%s"
  596. @parameterized.expand(["protect", "unprotect"])
  597. def test_no_auth(self, action: str):
  598. """
  599. Try to protect media without authentication.
  600. """
  601. channel = self.make_request("POST", self.url % (action, self.media_id), b"{}")
  602. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  603. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  604. @parameterized.expand(["protect", "unprotect"])
  605. def test_requester_is_no_admin(self, action: str):
  606. """
  607. If the user is not a server admin, an error is returned.
  608. """
  609. self.other_user = self.register_user("user", "pass")
  610. self.other_user_token = self.login("user", "pass")
  611. channel = self.make_request(
  612. "POST",
  613. self.url % (action, self.media_id),
  614. access_token=self.other_user_token,
  615. )
  616. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  617. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  618. def test_protect_media(self):
  619. """
  620. Tests that protect and unprotect a media is successfully
  621. """
  622. media_info = self.get_success(self.store.get_local_media(self.media_id))
  623. self.assertFalse(media_info["safe_from_quarantine"])
  624. # protect
  625. channel = self.make_request(
  626. "POST",
  627. self.url % ("protect", self.media_id),
  628. access_token=self.admin_user_tok,
  629. )
  630. self.assertEqual(200, channel.code, msg=channel.json_body)
  631. self.assertFalse(channel.json_body)
  632. media_info = self.get_success(self.store.get_local_media(self.media_id))
  633. self.assertTrue(media_info["safe_from_quarantine"])
  634. # unprotect
  635. channel = self.make_request(
  636. "POST",
  637. self.url % ("unprotect", self.media_id),
  638. access_token=self.admin_user_tok,
  639. )
  640. self.assertEqual(200, channel.code, msg=channel.json_body)
  641. self.assertFalse(channel.json_body)
  642. media_info = self.get_success(self.store.get_local_media(self.media_id))
  643. self.assertFalse(media_info["safe_from_quarantine"])