test_profile.py 16 KB

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