Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 65e6c64

Browse files
authored
Add an admin API for unprotecting local media from quarantine (#10040)
Signed-off-by: Dirk Klimpel [email protected]
1 parent 3e1beb7 commit 65e6c64

File tree

5 files changed

+151
-5
lines changed

5 files changed

+151
-5
lines changed

changelog.d/10040.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add an admin API for unprotecting local media from quarantine. Contributed by @dklimpel.

docs/admin_api/media_admin_api.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
* [Quarantining media in a room](#quarantining-media-in-a-room)
88
* [Quarantining all media of a user](#quarantining-all-media-of-a-user)
99
* [Protecting media from being quarantined](#protecting-media-from-being-quarantined)
10+
* [Unprotecting media from being quarantined](#unprotecting-media-from-being-quarantined)
1011
- [Delete local media](#delete-local-media)
1112
* [Delete a specific local media](#delete-a-specific-local-media)
1213
* [Delete local media by date or size](#delete-local-media-by-date-or-size)
@@ -159,6 +160,26 @@ Response:
159160
{}
160161
```
161162

163+
## Unprotecting media from being quarantined
164+
165+
This API reverts the protection of a media.
166+
167+
Request:
168+
169+
```
170+
POST /_synapse/admin/v1/media/unprotect/<media_id>
171+
172+
{}
173+
```
174+
175+
Where `media_id` is in the form of `abcdefg12345...`.
176+
177+
Response:
178+
179+
```json
180+
{}
181+
```
182+
162183
# Delete local media
163184
This API deletes the *local* media from the disk of your own server.
164185
This includes any local thumbnails and copies of media downloaded from

synapse/rest/admin/media.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,31 @@ async def on_POST(
137137

138138
logging.info("Protecting local media by ID: %s", media_id)
139139

140-
# Quarantine this media id
141-
await self.store.mark_local_media_as_safe(media_id)
140+
# Protect this media id
141+
await self.store.mark_local_media_as_safe(media_id, safe=True)
142+
143+
return 200, {}
144+
145+
146+
class UnprotectMediaByID(RestServlet):
147+
"""Unprotect local media from being quarantined."""
148+
149+
PATTERNS = admin_patterns("/media/unprotect/(?P<media_id>[^/]+)")
150+
151+
def __init__(self, hs: "HomeServer"):
152+
self.store = hs.get_datastore()
153+
self.auth = hs.get_auth()
154+
155+
async def on_POST(
156+
self, request: SynapseRequest, media_id: str
157+
) -> Tuple[int, JsonDict]:
158+
requester = await self.auth.get_user_by_req(request)
159+
await assert_user_is_admin(self.auth, requester.user)
160+
161+
logging.info("Unprotecting local media by ID: %s", media_id)
162+
163+
# Unprotect this media id
164+
await self.store.mark_local_media_as_safe(media_id, safe=False)
142165

143166
return 200, {}
144167

@@ -269,6 +292,7 @@ def register_servlets_for_media_repo(hs: "HomeServer", http_server):
269292
QuarantineMediaByID(hs).register(http_server)
270293
QuarantineMediaByUser(hs).register(http_server)
271294
ProtectMediaByID(hs).register(http_server)
295+
UnprotectMediaByID(hs).register(http_server)
272296
ListMediaInRoom(hs).register(http_server)
273297
DeleteMediaByID(hs).register(http_server)
274298
DeleteMediaByDateSize(hs).register(http_server)

synapse/storage/databases/main/media_repository.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ async def get_local_media(self, media_id: str) -> Optional[Dict[str, Any]]:
143143
"created_ts",
144144
"quarantined_by",
145145
"url_cache",
146+
"safe_from_quarantine",
146147
),
147148
allow_none=True,
148149
desc="get_local_media",
@@ -296,12 +297,12 @@ async def store_local_media(
296297
desc="store_local_media",
297298
)
298299

299-
async def mark_local_media_as_safe(self, media_id: str) -> None:
300-
"""Mark a local media as safe from quarantining."""
300+
async def mark_local_media_as_safe(self, media_id: str, safe: bool = True) -> None:
301+
"""Mark a local media as safe or unsafe from quarantining."""
301302
await self.db_pool.simple_update_one(
302303
table="local_media_repository",
303304
keyvalues={"media_id": media_id},
304-
updatevalues={"safe_from_quarantine": True},
305+
updatevalues={"safe_from_quarantine": safe},
305306
desc="mark_local_media_as_safe",
306307
)
307308

tests/rest/admin/test_media.py

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
import os
1717
from binascii import unhexlify
1818

19+
from parameterized import parameterized
20+
1921
import synapse.rest.admin
2022
from synapse.api.errors import Codes
2123
from synapse.rest.client.v1 import login, profile, room
@@ -562,3 +564,100 @@ def _access_media(self, server_and_media_id, expect_success=True):
562564
)
563565
# Test that the file is deleted
564566
self.assertFalse(os.path.exists(local_path))
567+
568+
569+
class ProtectMediaByIDTestCase(unittest.HomeserverTestCase):
570+
571+
servlets = [
572+
synapse.rest.admin.register_servlets,
573+
synapse.rest.admin.register_servlets_for_media_repo,
574+
login.register_servlets,
575+
]
576+
577+
def prepare(self, reactor, clock, hs):
578+
media_repo = hs.get_media_repository_resource()
579+
self.store = hs.get_datastore()
580+
581+
self.admin_user = self.register_user("admin", "pass", admin=True)
582+
self.admin_user_tok = self.login("admin", "pass")
583+
584+
# Create media
585+
upload_resource = media_repo.children[b"upload"]
586+
# file size is 67 Byte
587+
image_data = unhexlify(
588+
b"89504e470d0a1a0a0000000d4948445200000001000000010806"
589+
b"0000001f15c4890000000a49444154789c63000100000500010d"
590+
b"0a2db40000000049454e44ae426082"
591+
)
592+
593+
# Upload some media into the room
594+
response = self.helper.upload_media(
595+
upload_resource, image_data, tok=self.admin_user_tok, expect_code=200
596+
)
597+
# Extract media ID from the response
598+
server_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
599+
self.media_id = server_and_media_id.split("/")[1]
600+
601+
self.url = "/_synapse/admin/v1/media/%s/%s"
602+
603+
@parameterized.expand(["protect", "unprotect"])
604+
def test_no_auth(self, action: str):
605+
"""
606+
Try to protect media without authentication.
607+
"""
608+
609+
channel = self.make_request("POST", self.url % (action, self.media_id), b"{}")
610+
611+
self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
612+
self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
613+
614+
@parameterized.expand(["protect", "unprotect"])
615+
def test_requester_is_no_admin(self, action: str):
616+
"""
617+
If the user is not a server admin, an error is returned.
618+
"""
619+
self.other_user = self.register_user("user", "pass")
620+
self.other_user_token = self.login("user", "pass")
621+
622+
channel = self.make_request(
623+
"POST",
624+
self.url % (action, self.media_id),
625+
access_token=self.other_user_token,
626+
)
627+
628+
self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
629+
self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
630+
631+
def test_protect_media(self):
632+
"""
633+
Tests that protect and unprotect a media is successfully
634+
"""
635+
636+
media_info = self.get_success(self.store.get_local_media(self.media_id))
637+
self.assertFalse(media_info["safe_from_quarantine"])
638+
639+
# protect
640+
channel = self.make_request(
641+
"POST",
642+
self.url % ("protect", self.media_id),
643+
access_token=self.admin_user_tok,
644+
)
645+
646+
self.assertEqual(200, channel.code, msg=channel.json_body)
647+
self.assertFalse(channel.json_body)
648+
649+
media_info = self.get_success(self.store.get_local_media(self.media_id))
650+
self.assertTrue(media_info["safe_from_quarantine"])
651+
652+
# unprotect
653+
channel = self.make_request(
654+
"POST",
655+
self.url % ("unprotect", self.media_id),
656+
access_token=self.admin_user_tok,
657+
)
658+
659+
self.assertEqual(200, channel.code, msg=channel.json_body)
660+
self.assertFalse(channel.json_body)
661+
662+
media_info = self.get_success(self.store.get_local_media(self.media_id))
663+
self.assertFalse(media_info["safe_from_quarantine"])

0 commit comments

Comments
 (0)