1
0

test_profile.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. # Copyright 2014-2016 OpenMarket Ltd
  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. from typing import Any, Awaitable, Callable, Dict
  15. from unittest.mock import Mock
  16. from parameterized import parameterized
  17. from twisted.test.proto_helpers import MemoryReactor
  18. import synapse.types
  19. from synapse.api.errors import AuthError, SynapseError
  20. from synapse.rest import admin
  21. from synapse.server import HomeServer
  22. from synapse.types import JsonDict, UserID
  23. from synapse.util import Clock
  24. from tests import unittest
  25. from tests.test_utils import make_awaitable
  26. class ProfileTestCase(unittest.HomeserverTestCase):
  27. """Tests profile management."""
  28. servlets = [admin.register_servlets]
  29. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  30. self.mock_federation = Mock()
  31. self.mock_registry = Mock()
  32. self.query_handlers: Dict[str, Callable[[dict], Awaitable[JsonDict]]] = {}
  33. def register_query_handler(
  34. query_type: str, handler: Callable[[dict], Awaitable[JsonDict]]
  35. ) -> None:
  36. self.query_handlers[query_type] = handler
  37. self.mock_registry.register_query_handler = register_query_handler
  38. hs = self.setup_test_homeserver(
  39. federation_client=self.mock_federation,
  40. federation_server=Mock(),
  41. federation_registry=self.mock_registry,
  42. )
  43. return hs
  44. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  45. self.store = hs.get_datastores().main
  46. self.frank = UserID.from_string("@1234abcd:test")
  47. self.bob = UserID.from_string("@4567:test")
  48. self.alice = UserID.from_string("@alice:remote")
  49. self.register_user(self.frank.localpart, "frankpassword")
  50. self.handler = hs.get_profile_handler()
  51. def test_get_my_name(self) -> None:
  52. self.get_success(
  53. self.store.set_profile_displayname(self.frank.localpart, "Frank")
  54. )
  55. displayname = self.get_success(self.handler.get_displayname(self.frank))
  56. self.assertEqual("Frank", displayname)
  57. def test_set_my_name(self) -> None:
  58. self.get_success(
  59. self.handler.set_displayname(
  60. self.frank, synapse.types.create_requester(self.frank), "Frank Jr."
  61. )
  62. )
  63. self.assertEqual(
  64. (
  65. self.get_success(
  66. self.store.get_profile_displayname(self.frank.localpart)
  67. )
  68. ),
  69. "Frank Jr.",
  70. )
  71. # Set displayname again
  72. self.get_success(
  73. self.handler.set_displayname(
  74. self.frank, synapse.types.create_requester(self.frank), "Frank"
  75. )
  76. )
  77. self.assertEqual(
  78. (
  79. self.get_success(
  80. self.store.get_profile_displayname(self.frank.localpart)
  81. )
  82. ),
  83. "Frank",
  84. )
  85. # Set displayname to an empty string
  86. self.get_success(
  87. self.handler.set_displayname(
  88. self.frank, synapse.types.create_requester(self.frank), ""
  89. )
  90. )
  91. self.assertIsNone(
  92. self.get_success(self.store.get_profile_displayname(self.frank.localpart))
  93. )
  94. def test_set_my_name_if_disabled(self) -> None:
  95. self.hs.config.registration.enable_set_displayname = False
  96. # Setting displayname for the first time is allowed
  97. self.get_success(
  98. self.store.set_profile_displayname(self.frank.localpart, "Frank")
  99. )
  100. self.assertEqual(
  101. (
  102. self.get_success(
  103. self.store.get_profile_displayname(self.frank.localpart)
  104. )
  105. ),
  106. "Frank",
  107. )
  108. # Setting displayname a second time is forbidden
  109. self.get_failure(
  110. self.handler.set_displayname(
  111. self.frank, synapse.types.create_requester(self.frank), "Frank Jr."
  112. ),
  113. SynapseError,
  114. )
  115. def test_set_my_name_noauth(self) -> None:
  116. self.get_failure(
  117. self.handler.set_displayname(
  118. self.frank, synapse.types.create_requester(self.bob), "Frank Jr."
  119. ),
  120. AuthError,
  121. )
  122. def test_get_other_name(self) -> None:
  123. self.mock_federation.make_query.return_value = make_awaitable(
  124. {"displayname": "Alice"}
  125. )
  126. displayname = self.get_success(self.handler.get_displayname(self.alice))
  127. self.assertEqual(displayname, "Alice")
  128. self.mock_federation.make_query.assert_called_with(
  129. destination="remote",
  130. query_type="profile",
  131. args={"user_id": "@alice:remote", "field": "displayname"},
  132. ignore_backoff=True,
  133. )
  134. def test_incoming_fed_query(self) -> None:
  135. self.get_success(self.store.create_profile("caroline"))
  136. self.get_success(self.store.set_profile_displayname("caroline", "Caroline"))
  137. response = self.get_success(
  138. self.query_handlers["profile"](
  139. {
  140. "user_id": "@caroline:test",
  141. "field": "displayname",
  142. "origin": "servername.tld",
  143. }
  144. )
  145. )
  146. self.assertEqual({"displayname": "Caroline"}, response)
  147. def test_get_my_avatar(self) -> None:
  148. self.get_success(
  149. self.store.set_profile_avatar_url(
  150. self.frank.localpart, "http://my.server/me.png"
  151. )
  152. )
  153. avatar_url = self.get_success(self.handler.get_avatar_url(self.frank))
  154. self.assertEqual("http://my.server/me.png", avatar_url)
  155. def test_set_my_avatar(self) -> None:
  156. self.get_success(
  157. self.handler.set_avatar_url(
  158. self.frank,
  159. synapse.types.create_requester(self.frank),
  160. "http://my.server/pic.gif",
  161. )
  162. )
  163. self.assertEqual(
  164. (self.get_success(self.store.get_profile_avatar_url(self.frank.localpart))),
  165. "http://my.server/pic.gif",
  166. )
  167. # Set avatar again
  168. self.get_success(
  169. self.handler.set_avatar_url(
  170. self.frank,
  171. synapse.types.create_requester(self.frank),
  172. "http://my.server/me.png",
  173. )
  174. )
  175. self.assertEqual(
  176. (self.get_success(self.store.get_profile_avatar_url(self.frank.localpart))),
  177. "http://my.server/me.png",
  178. )
  179. # Set avatar to an empty string
  180. self.get_success(
  181. self.handler.set_avatar_url(
  182. self.frank,
  183. synapse.types.create_requester(self.frank),
  184. "",
  185. )
  186. )
  187. self.assertIsNone(
  188. (self.get_success(self.store.get_profile_avatar_url(self.frank.localpart))),
  189. )
  190. def test_set_my_avatar_if_disabled(self) -> None:
  191. self.hs.config.registration.enable_set_avatar_url = False
  192. # Setting displayname for the first time is allowed
  193. self.get_success(
  194. self.store.set_profile_avatar_url(
  195. self.frank.localpart, "http://my.server/me.png"
  196. )
  197. )
  198. self.assertEqual(
  199. (self.get_success(self.store.get_profile_avatar_url(self.frank.localpart))),
  200. "http://my.server/me.png",
  201. )
  202. # Set avatar a second time is forbidden
  203. self.get_failure(
  204. self.handler.set_avatar_url(
  205. self.frank,
  206. synapse.types.create_requester(self.frank),
  207. "http://my.server/pic.gif",
  208. ),
  209. SynapseError,
  210. )
  211. def test_avatar_constraints_no_config(self) -> None:
  212. """Tests that the method to check an avatar against configured constraints skips
  213. all of its check if no constraint is configured.
  214. """
  215. # The first check that's done by this method is whether the file exists; if we
  216. # don't get an error on a non-existing file then it means all of the checks were
  217. # successfully skipped.
  218. res = self.get_success(
  219. self.handler.check_avatar_size_and_mime_type("mxc://test/unknown_file")
  220. )
  221. self.assertTrue(res)
  222. @unittest.override_config({"max_avatar_size": 50})
  223. def test_avatar_constraints_allow_empty_avatar_url(self) -> None:
  224. """An empty avatar is always permitted."""
  225. res = self.get_success(self.handler.check_avatar_size_and_mime_type(""))
  226. self.assertTrue(res)
  227. @unittest.override_config({"max_avatar_size": 50})
  228. def test_avatar_constraints_missing(self) -> None:
  229. """Tests that an avatar isn't allowed if the file at the given MXC URI couldn't
  230. be found.
  231. """
  232. res = self.get_success(
  233. self.handler.check_avatar_size_and_mime_type("mxc://test/unknown_file")
  234. )
  235. self.assertFalse(res)
  236. @unittest.override_config({"max_avatar_size": 50})
  237. def test_avatar_constraints_file_size(self) -> None:
  238. """Tests that a file that's above the allowed file size is forbidden but one
  239. that's below it is allowed.
  240. """
  241. self._setup_local_files(
  242. {
  243. "small": {"size": 40},
  244. "big": {"size": 60},
  245. }
  246. )
  247. res = self.get_success(
  248. self.handler.check_avatar_size_and_mime_type("mxc://test/small")
  249. )
  250. self.assertTrue(res)
  251. res = self.get_success(
  252. self.handler.check_avatar_size_and_mime_type("mxc://test/big")
  253. )
  254. self.assertFalse(res)
  255. @unittest.override_config({"allowed_avatar_mimetypes": ["image/png"]})
  256. def test_avatar_constraint_mime_type(self) -> None:
  257. """Tests that a file with an unauthorised MIME type is forbidden but one with
  258. an authorised content type is allowed.
  259. """
  260. self._setup_local_files(
  261. {
  262. "good": {"mimetype": "image/png"},
  263. "bad": {"mimetype": "application/octet-stream"},
  264. }
  265. )
  266. res = self.get_success(
  267. self.handler.check_avatar_size_and_mime_type("mxc://test/good")
  268. )
  269. self.assertTrue(res)
  270. res = self.get_success(
  271. self.handler.check_avatar_size_and_mime_type("mxc://test/bad")
  272. )
  273. self.assertFalse(res)
  274. @unittest.override_config(
  275. {"server_name": "test:8888", "allowed_avatar_mimetypes": ["image/png"]}
  276. )
  277. def test_avatar_constraint_on_local_server_with_port(self) -> None:
  278. """Test that avatar metadata is correctly fetched when the media is on a local
  279. server and the server has an explicit port.
  280. (This was previously a bug)
  281. """
  282. local_server_name = self.hs.config.server.server_name
  283. media_id = "local"
  284. local_mxc = f"mxc://{local_server_name}/{media_id}"
  285. # mock up the existence of the avatar file
  286. self._setup_local_files({media_id: {"mimetype": "image/png"}})
  287. # and now check that check_avatar_size_and_mime_type is happy
  288. self.assertTrue(
  289. self.get_success(self.handler.check_avatar_size_and_mime_type(local_mxc))
  290. )
  291. @parameterized.expand([("remote",), ("remote:1234",)])
  292. @unittest.override_config({"allowed_avatar_mimetypes": ["image/png"]})
  293. def test_check_avatar_on_remote_server(self, remote_server_name: str) -> None:
  294. """Test that avatar metadata is correctly fetched from a remote server"""
  295. media_id = "remote"
  296. remote_mxc = f"mxc://{remote_server_name}/{media_id}"
  297. # if the media is remote, check_avatar_size_and_mime_type just checks the
  298. # media cache, so we don't need to instantiate a real remote server. It is
  299. # sufficient to poke an entry into the db.
  300. self.get_success(
  301. self.hs.get_datastores().main.store_cached_remote_media(
  302. media_id=media_id,
  303. media_type="image/png",
  304. media_length=50,
  305. origin=remote_server_name,
  306. time_now_ms=self.clock.time_msec(),
  307. upload_name=None,
  308. filesystem_id="xyz",
  309. )
  310. )
  311. self.assertTrue(
  312. self.get_success(self.handler.check_avatar_size_and_mime_type(remote_mxc))
  313. )
  314. def _setup_local_files(self, names_and_props: Dict[str, Dict[str, Any]]) -> None:
  315. """Stores metadata about files in the database.
  316. Args:
  317. names_and_props: A dictionary with one entry per file, with the key being the
  318. file's name, and the value being a dictionary of properties. Supported
  319. properties are "mimetype" (for the file's type) and "size" (for the
  320. file's size).
  321. """
  322. store = self.hs.get_datastores().main
  323. for name, props in names_and_props.items():
  324. self.get_success(
  325. store.store_local_media(
  326. media_id=name,
  327. media_type=props.get("mimetype", "image/png"),
  328. time_now_ms=self.clock.time_msec(),
  329. upload_name=None,
  330. media_length=props.get("size", 50),
  331. user_id=UserID.from_string("@rin:test"),
  332. )
  333. )