test_profile.py 14 KB

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