test_profile.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. """Tests REST events for /profile paths."""
  15. from typing import Any, Dict, Optional
  16. from twisted.test.proto_helpers import MemoryReactor
  17. from synapse.api.errors import Codes
  18. from synapse.rest import admin
  19. from synapse.rest.client import login, profile, room
  20. from synapse.server import HomeServer
  21. from synapse.types import UserID
  22. from synapse.util import Clock
  23. from tests import unittest
  24. class ProfileTestCase(unittest.HomeserverTestCase):
  25. servlets = [
  26. admin.register_servlets_for_client_rest_resource,
  27. login.register_servlets,
  28. profile.register_servlets,
  29. room.register_servlets,
  30. ]
  31. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  32. self.hs = self.setup_test_homeserver()
  33. return self.hs
  34. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  35. self.owner = self.register_user("owner", "pass")
  36. self.owner_tok = self.login("owner", "pass")
  37. self.other = self.register_user("other", "pass", displayname="Bob")
  38. def test_get_displayname(self) -> None:
  39. res = self._get_displayname()
  40. self.assertEqual(res, "owner")
  41. def test_set_displayname(self) -> None:
  42. channel = self.make_request(
  43. "PUT",
  44. "/profile/%s/displayname" % (self.owner,),
  45. content={"displayname": "test"},
  46. access_token=self.owner_tok,
  47. )
  48. self.assertEqual(channel.code, 200, channel.result)
  49. res = self._get_displayname()
  50. self.assertEqual(res, "test")
  51. def test_set_displayname_noauth(self) -> None:
  52. channel = self.make_request(
  53. "PUT",
  54. "/profile/%s/displayname" % (self.owner,),
  55. content={"displayname": "test"},
  56. )
  57. self.assertEqual(channel.code, 401, channel.result)
  58. def test_set_displayname_too_long(self) -> None:
  59. """Attempts to set a stupid displayname should get a 400"""
  60. channel = self.make_request(
  61. "PUT",
  62. "/profile/%s/displayname" % (self.owner,),
  63. content={"displayname": "test" * 100},
  64. access_token=self.owner_tok,
  65. )
  66. self.assertEqual(channel.code, 400, channel.result)
  67. res = self._get_displayname()
  68. self.assertEqual(res, "owner")
  69. def test_get_displayname_other(self) -> None:
  70. res = self._get_displayname(self.other)
  71. self.assertEqual(res, "Bob")
  72. def test_set_displayname_other(self) -> None:
  73. channel = self.make_request(
  74. "PUT",
  75. "/profile/%s/displayname" % (self.other,),
  76. content={"displayname": "test"},
  77. access_token=self.owner_tok,
  78. )
  79. self.assertEqual(channel.code, 400, channel.result)
  80. def test_get_avatar_url(self) -> None:
  81. res = self._get_avatar_url()
  82. self.assertIsNone(res)
  83. def test_set_avatar_url(self) -> None:
  84. channel = self.make_request(
  85. "PUT",
  86. "/profile/%s/avatar_url" % (self.owner,),
  87. content={"avatar_url": "http://my.server/pic.gif"},
  88. access_token=self.owner_tok,
  89. )
  90. self.assertEqual(channel.code, 200, channel.result)
  91. res = self._get_avatar_url()
  92. self.assertEqual(res, "http://my.server/pic.gif")
  93. def test_set_avatar_url_noauth(self) -> None:
  94. channel = self.make_request(
  95. "PUT",
  96. "/profile/%s/avatar_url" % (self.owner,),
  97. content={"avatar_url": "http://my.server/pic.gif"},
  98. )
  99. self.assertEqual(channel.code, 401, channel.result)
  100. def test_set_avatar_url_too_long(self) -> None:
  101. """Attempts to set a stupid avatar_url should get a 400"""
  102. channel = self.make_request(
  103. "PUT",
  104. "/profile/%s/avatar_url" % (self.owner,),
  105. content={"avatar_url": "http://my.server/pic.gif" * 100},
  106. access_token=self.owner_tok,
  107. )
  108. self.assertEqual(channel.code, 400, channel.result)
  109. res = self._get_avatar_url()
  110. self.assertIsNone(res)
  111. def test_get_avatar_url_other(self) -> None:
  112. res = self._get_avatar_url(self.other)
  113. self.assertIsNone(res)
  114. def test_set_avatar_url_other(self) -> None:
  115. channel = self.make_request(
  116. "PUT",
  117. "/profile/%s/avatar_url" % (self.other,),
  118. content={"avatar_url": "http://my.server/pic.gif"},
  119. access_token=self.owner_tok,
  120. )
  121. self.assertEqual(channel.code, 400, channel.result)
  122. def _get_displayname(self, name: Optional[str] = None) -> str:
  123. channel = self.make_request(
  124. "GET", "/profile/%s/displayname" % (name or self.owner,)
  125. )
  126. self.assertEqual(channel.code, 200, channel.result)
  127. return channel.json_body["displayname"]
  128. def _get_avatar_url(self, name: Optional[str] = None) -> str:
  129. channel = self.make_request(
  130. "GET", "/profile/%s/avatar_url" % (name or self.owner,)
  131. )
  132. self.assertEqual(channel.code, 200, channel.result)
  133. return channel.json_body.get("avatar_url")
  134. @unittest.override_config({"max_avatar_size": 50})
  135. def test_avatar_size_limit_global(self) -> None:
  136. """Tests that the maximum size limit for avatars is enforced when updating a
  137. global profile.
  138. """
  139. self._setup_local_files(
  140. {
  141. "small": {"size": 40},
  142. "big": {"size": 60},
  143. }
  144. )
  145. channel = self.make_request(
  146. "PUT",
  147. f"/profile/{self.owner}/avatar_url",
  148. content={"avatar_url": "mxc://test/big"},
  149. access_token=self.owner_tok,
  150. )
  151. self.assertEqual(channel.code, 403, channel.result)
  152. self.assertEqual(
  153. channel.json_body["errcode"], Codes.FORBIDDEN, channel.json_body
  154. )
  155. channel = self.make_request(
  156. "PUT",
  157. f"/profile/{self.owner}/avatar_url",
  158. content={"avatar_url": "mxc://test/small"},
  159. access_token=self.owner_tok,
  160. )
  161. self.assertEqual(channel.code, 200, channel.result)
  162. @unittest.override_config({"max_avatar_size": 50})
  163. def test_avatar_size_limit_per_room(self) -> None:
  164. """Tests that the maximum size limit for avatars is enforced when updating a
  165. per-room profile.
  166. """
  167. self._setup_local_files(
  168. {
  169. "small": {"size": 40},
  170. "big": {"size": 60},
  171. }
  172. )
  173. room_id = self.helper.create_room_as(tok=self.owner_tok)
  174. channel = self.make_request(
  175. "PUT",
  176. f"/rooms/{room_id}/state/m.room.member/{self.owner}",
  177. content={"membership": "join", "avatar_url": "mxc://test/big"},
  178. access_token=self.owner_tok,
  179. )
  180. self.assertEqual(channel.code, 403, channel.result)
  181. self.assertEqual(
  182. channel.json_body["errcode"], Codes.FORBIDDEN, channel.json_body
  183. )
  184. channel = self.make_request(
  185. "PUT",
  186. f"/rooms/{room_id}/state/m.room.member/{self.owner}",
  187. content={"membership": "join", "avatar_url": "mxc://test/small"},
  188. access_token=self.owner_tok,
  189. )
  190. self.assertEqual(channel.code, 200, channel.result)
  191. @unittest.override_config({"allowed_avatar_mimetypes": ["image/png"]})
  192. def test_avatar_allowed_mime_type_global(self) -> None:
  193. """Tests that the MIME type whitelist for avatars is enforced when updating a
  194. global profile.
  195. """
  196. self._setup_local_files(
  197. {
  198. "good": {"mimetype": "image/png"},
  199. "bad": {"mimetype": "application/octet-stream"},
  200. }
  201. )
  202. channel = self.make_request(
  203. "PUT",
  204. f"/profile/{self.owner}/avatar_url",
  205. content={"avatar_url": "mxc://test/bad"},
  206. access_token=self.owner_tok,
  207. )
  208. self.assertEqual(channel.code, 403, channel.result)
  209. self.assertEqual(
  210. channel.json_body["errcode"], Codes.FORBIDDEN, channel.json_body
  211. )
  212. channel = self.make_request(
  213. "PUT",
  214. f"/profile/{self.owner}/avatar_url",
  215. content={"avatar_url": "mxc://test/good"},
  216. access_token=self.owner_tok,
  217. )
  218. self.assertEqual(channel.code, 200, channel.result)
  219. @unittest.override_config({"allowed_avatar_mimetypes": ["image/png"]})
  220. def test_avatar_allowed_mime_type_per_room(self) -> None:
  221. """Tests that the MIME type whitelist for avatars is enforced when updating a
  222. per-room profile.
  223. """
  224. self._setup_local_files(
  225. {
  226. "good": {"mimetype": "image/png"},
  227. "bad": {"mimetype": "application/octet-stream"},
  228. }
  229. )
  230. room_id = self.helper.create_room_as(tok=self.owner_tok)
  231. channel = self.make_request(
  232. "PUT",
  233. f"/rooms/{room_id}/state/m.room.member/{self.owner}",
  234. content={"membership": "join", "avatar_url": "mxc://test/bad"},
  235. access_token=self.owner_tok,
  236. )
  237. self.assertEqual(channel.code, 403, channel.result)
  238. self.assertEqual(
  239. channel.json_body["errcode"], Codes.FORBIDDEN, channel.json_body
  240. )
  241. channel = self.make_request(
  242. "PUT",
  243. f"/rooms/{room_id}/state/m.room.member/{self.owner}",
  244. content={"membership": "join", "avatar_url": "mxc://test/good"},
  245. access_token=self.owner_tok,
  246. )
  247. self.assertEqual(channel.code, 200, channel.result)
  248. def _setup_local_files(self, names_and_props: Dict[str, Dict[str, Any]]) -> None:
  249. """Stores metadata about files in the database.
  250. Args:
  251. names_and_props: A dictionary with one entry per file, with the key being the
  252. file's name, and the value being a dictionary of properties. Supported
  253. properties are "mimetype" (for the file's type) and "size" (for the
  254. file's size).
  255. """
  256. store = self.hs.get_datastores().main
  257. for name, props in names_and_props.items():
  258. self.get_success(
  259. store.store_local_media(
  260. media_id=name,
  261. media_type=props.get("mimetype", "image/png"),
  262. time_now_ms=self.clock.time_msec(),
  263. upload_name=None,
  264. media_length=props.get("size", 50),
  265. user_id=UserID.from_string("@rin:test"),
  266. )
  267. )
  268. class ProfilesRestrictedTestCase(unittest.HomeserverTestCase):
  269. servlets = [
  270. admin.register_servlets_for_client_rest_resource,
  271. login.register_servlets,
  272. profile.register_servlets,
  273. room.register_servlets,
  274. ]
  275. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  276. config = self.default_config()
  277. config["require_auth_for_profile_requests"] = True
  278. config["limit_profile_requests_to_users_who_share_rooms"] = True
  279. self.hs = self.setup_test_homeserver(config=config)
  280. return self.hs
  281. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  282. # User owning the requested profile.
  283. self.owner = self.register_user("owner", "pass")
  284. self.owner_tok = self.login("owner", "pass")
  285. self.profile_url = "/profile/%s" % (self.owner)
  286. # User requesting the profile.
  287. self.requester = self.register_user("requester", "pass")
  288. self.requester_tok = self.login("requester", "pass")
  289. self.room_id = self.helper.create_room_as(self.owner, tok=self.owner_tok)
  290. def test_no_auth(self) -> None:
  291. self.try_fetch_profile(401)
  292. def test_not_in_shared_room(self) -> None:
  293. self.ensure_requester_left_room()
  294. self.try_fetch_profile(403, access_token=self.requester_tok)
  295. def test_in_shared_room(self) -> None:
  296. self.ensure_requester_left_room()
  297. self.helper.join(room=self.room_id, user=self.requester, tok=self.requester_tok)
  298. self.try_fetch_profile(200, self.requester_tok)
  299. def try_fetch_profile(
  300. self, expected_code: int, access_token: Optional[str] = None
  301. ) -> None:
  302. self.request_profile(expected_code, access_token=access_token)
  303. self.request_profile(
  304. expected_code, url_suffix="/displayname", access_token=access_token
  305. )
  306. self.request_profile(
  307. expected_code, url_suffix="/avatar_url", access_token=access_token
  308. )
  309. def request_profile(
  310. self,
  311. expected_code: int,
  312. url_suffix: str = "",
  313. access_token: Optional[str] = None,
  314. ) -> None:
  315. channel = self.make_request(
  316. "GET", self.profile_url + url_suffix, access_token=access_token
  317. )
  318. self.assertEqual(channel.code, expected_code, channel.result)
  319. def ensure_requester_left_room(self) -> None:
  320. try:
  321. self.helper.leave(
  322. room=self.room_id, user=self.requester, tok=self.requester_tok
  323. )
  324. except AssertionError:
  325. # We don't care whether the leave request didn't return a 200 (e.g.
  326. # if the user isn't already in the room), because we only want to
  327. # make sure the user isn't in the room.
  328. pass
  329. class OwnProfileUnrestrictedTestCase(unittest.HomeserverTestCase):
  330. servlets = [
  331. admin.register_servlets_for_client_rest_resource,
  332. login.register_servlets,
  333. profile.register_servlets,
  334. ]
  335. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  336. config = self.default_config()
  337. config["require_auth_for_profile_requests"] = True
  338. config["limit_profile_requests_to_users_who_share_rooms"] = True
  339. self.hs = self.setup_test_homeserver(config=config)
  340. return self.hs
  341. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  342. # User requesting the profile.
  343. self.requester = self.register_user("requester", "pass")
  344. self.requester_tok = self.login("requester", "pass")
  345. def test_can_lookup_own_profile(self) -> None:
  346. """Tests that a user can lookup their own profile without having to be in a room
  347. if 'require_auth_for_profile_requests' is set to true in the server's config.
  348. """
  349. channel = self.make_request(
  350. "GET", "/profile/" + self.requester, access_token=self.requester_tok
  351. )
  352. self.assertEqual(channel.code, 200, channel.result)
  353. channel = self.make_request(
  354. "GET",
  355. "/profile/" + self.requester + "/displayname",
  356. access_token=self.requester_tok,
  357. )
  358. self.assertEqual(channel.code, 200, channel.result)
  359. channel = self.make_request(
  360. "GET",
  361. "/profile/" + self.requester + "/avatar_url",
  362. access_token=self.requester_tok,
  363. )
  364. self.assertEqual(channel.code, 200, channel.result)