test_profile.py 12 KB

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