test_profile.py 14 KB

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