test_rooms.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2017 Vector Creations Ltd
  4. # Copyright 2018-2019 New Vector Ltd
  5. # Copyright 2019 The Matrix.org Foundation C.I.C.
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. """Tests REST events for /rooms paths."""
  19. import json
  20. from mock import Mock, NonCallableMock
  21. from six.moves.urllib import parse as urlparse
  22. from twisted.internet import defer
  23. import synapse.rest.admin
  24. from synapse.api.constants import EventContentFields, EventTypes, Membership
  25. from synapse.handlers.pagination import PurgeStatus
  26. from synapse.rest.client.v1 import login, profile, room
  27. from synapse.rest.client.v2_alpha import account
  28. from synapse.util.stringutils import random_string
  29. from tests import unittest
  30. PATH_PREFIX = b"/_matrix/client/api/v1"
  31. class RoomBase(unittest.HomeserverTestCase):
  32. rmcreator_id = None
  33. servlets = [room.register_servlets, room.register_deprecated_servlets]
  34. def make_homeserver(self, reactor, clock):
  35. self.hs = self.setup_test_homeserver(
  36. "red",
  37. http_client=None,
  38. federation_client=Mock(),
  39. ratelimiter=NonCallableMock(spec_set=["can_do_action"]),
  40. )
  41. self.ratelimiter = self.hs.get_ratelimiter()
  42. self.ratelimiter.can_do_action.return_value = (True, 0)
  43. self.hs.get_federation_handler = Mock(return_value=Mock())
  44. def _insert_client_ip(*args, **kwargs):
  45. return defer.succeed(None)
  46. self.hs.get_datastore().insert_client_ip = _insert_client_ip
  47. return self.hs
  48. class RoomPermissionsTestCase(RoomBase):
  49. """ Tests room permissions. """
  50. user_id = "@sid1:red"
  51. rmcreator_id = "@notme:red"
  52. def prepare(self, reactor, clock, hs):
  53. self.helper.auth_user_id = self.rmcreator_id
  54. # create some rooms under the name rmcreator_id
  55. self.uncreated_rmid = "!aa:test"
  56. self.created_rmid = self.helper.create_room_as(
  57. self.rmcreator_id, is_public=False
  58. )
  59. self.created_public_rmid = self.helper.create_room_as(
  60. self.rmcreator_id, is_public=True
  61. )
  62. # send a message in one of the rooms
  63. self.created_rmid_msg_path = (
  64. "rooms/%s/send/m.room.message/a1" % (self.created_rmid)
  65. ).encode("ascii")
  66. request, channel = self.make_request(
  67. "PUT", self.created_rmid_msg_path, b'{"msgtype":"m.text","body":"test msg"}'
  68. )
  69. self.render(request)
  70. self.assertEquals(200, channel.code, channel.result)
  71. # set topic for public room
  72. request, channel = self.make_request(
  73. "PUT",
  74. ("rooms/%s/state/m.room.topic" % self.created_public_rmid).encode("ascii"),
  75. b'{"topic":"Public Room Topic"}',
  76. )
  77. self.render(request)
  78. self.assertEquals(200, channel.code, channel.result)
  79. # auth as user_id now
  80. self.helper.auth_user_id = self.user_id
  81. def test_can_do_action(self):
  82. msg_content = b'{"msgtype":"m.text","body":"hello"}'
  83. seq = iter(range(100))
  84. def send_msg_path():
  85. return "/rooms/%s/send/m.room.message/mid%s" % (
  86. self.created_rmid,
  87. str(next(seq)),
  88. )
  89. # send message in uncreated room, expect 403
  90. request, channel = self.make_request(
  91. "PUT",
  92. "/rooms/%s/send/m.room.message/mid2" % (self.uncreated_rmid,),
  93. msg_content,
  94. )
  95. self.render(request)
  96. self.assertEquals(403, channel.code, msg=channel.result["body"])
  97. # send message in created room not joined (no state), expect 403
  98. request, channel = self.make_request("PUT", send_msg_path(), msg_content)
  99. self.render(request)
  100. self.assertEquals(403, channel.code, msg=channel.result["body"])
  101. # send message in created room and invited, expect 403
  102. self.helper.invite(
  103. room=self.created_rmid, src=self.rmcreator_id, targ=self.user_id
  104. )
  105. request, channel = self.make_request("PUT", send_msg_path(), msg_content)
  106. self.render(request)
  107. self.assertEquals(403, channel.code, msg=channel.result["body"])
  108. # send message in created room and joined, expect 200
  109. self.helper.join(room=self.created_rmid, user=self.user_id)
  110. request, channel = self.make_request("PUT", send_msg_path(), msg_content)
  111. self.render(request)
  112. self.assertEquals(200, channel.code, msg=channel.result["body"])
  113. # send message in created room and left, expect 403
  114. self.helper.leave(room=self.created_rmid, user=self.user_id)
  115. request, channel = self.make_request("PUT", send_msg_path(), msg_content)
  116. self.render(request)
  117. self.assertEquals(403, channel.code, msg=channel.result["body"])
  118. def test_topic_perms(self):
  119. topic_content = b'{"topic":"My Topic Name"}'
  120. topic_path = "/rooms/%s/state/m.room.topic" % self.created_rmid
  121. # set/get topic in uncreated room, expect 403
  122. request, channel = self.make_request(
  123. "PUT", "/rooms/%s/state/m.room.topic" % self.uncreated_rmid, topic_content
  124. )
  125. self.render(request)
  126. self.assertEquals(403, channel.code, msg=channel.result["body"])
  127. request, channel = self.make_request(
  128. "GET", "/rooms/%s/state/m.room.topic" % self.uncreated_rmid
  129. )
  130. self.render(request)
  131. self.assertEquals(403, channel.code, msg=channel.result["body"])
  132. # set/get topic in created PRIVATE room not joined, expect 403
  133. request, channel = self.make_request("PUT", topic_path, topic_content)
  134. self.render(request)
  135. self.assertEquals(403, channel.code, msg=channel.result["body"])
  136. request, channel = self.make_request("GET", topic_path)
  137. self.render(request)
  138. self.assertEquals(403, channel.code, msg=channel.result["body"])
  139. # set topic in created PRIVATE room and invited, expect 403
  140. self.helper.invite(
  141. room=self.created_rmid, src=self.rmcreator_id, targ=self.user_id
  142. )
  143. request, channel = self.make_request("PUT", topic_path, topic_content)
  144. self.render(request)
  145. self.assertEquals(403, channel.code, msg=channel.result["body"])
  146. # get topic in created PRIVATE room and invited, expect 403
  147. request, channel = self.make_request("GET", topic_path)
  148. self.render(request)
  149. self.assertEquals(403, channel.code, msg=channel.result["body"])
  150. # set/get topic in created PRIVATE room and joined, expect 200
  151. self.helper.join(room=self.created_rmid, user=self.user_id)
  152. # Only room ops can set topic by default
  153. self.helper.auth_user_id = self.rmcreator_id
  154. request, channel = self.make_request("PUT", topic_path, topic_content)
  155. self.render(request)
  156. self.assertEquals(200, channel.code, msg=channel.result["body"])
  157. self.helper.auth_user_id = self.user_id
  158. request, channel = self.make_request("GET", topic_path)
  159. self.render(request)
  160. self.assertEquals(200, channel.code, msg=channel.result["body"])
  161. self.assert_dict(json.loads(topic_content.decode("utf8")), channel.json_body)
  162. # set/get topic in created PRIVATE room and left, expect 403
  163. self.helper.leave(room=self.created_rmid, user=self.user_id)
  164. request, channel = self.make_request("PUT", topic_path, topic_content)
  165. self.render(request)
  166. self.assertEquals(403, channel.code, msg=channel.result["body"])
  167. request, channel = self.make_request("GET", topic_path)
  168. self.render(request)
  169. self.assertEquals(200, channel.code, msg=channel.result["body"])
  170. # get topic in PUBLIC room, not joined, expect 403
  171. request, channel = self.make_request(
  172. "GET", "/rooms/%s/state/m.room.topic" % self.created_public_rmid
  173. )
  174. self.render(request)
  175. self.assertEquals(403, channel.code, msg=channel.result["body"])
  176. # set topic in PUBLIC room, not joined, expect 403
  177. request, channel = self.make_request(
  178. "PUT",
  179. "/rooms/%s/state/m.room.topic" % self.created_public_rmid,
  180. topic_content,
  181. )
  182. self.render(request)
  183. self.assertEquals(403, channel.code, msg=channel.result["body"])
  184. def _test_get_membership(self, room=None, members=[], expect_code=None):
  185. for member in members:
  186. path = "/rooms/%s/state/m.room.member/%s" % (room, member)
  187. request, channel = self.make_request("GET", path)
  188. self.render(request)
  189. self.assertEquals(expect_code, channel.code)
  190. def test_membership_basic_room_perms(self):
  191. # === room does not exist ===
  192. room = self.uncreated_rmid
  193. # get membership of self, get membership of other, uncreated room
  194. # expect all 403s
  195. self._test_get_membership(
  196. members=[self.user_id, self.rmcreator_id], room=room, expect_code=403
  197. )
  198. # trying to invite people to this room should 403
  199. self.helper.invite(
  200. room=room, src=self.user_id, targ=self.rmcreator_id, expect_code=403
  201. )
  202. # set [invite/join/left] of self, set [invite/join/left] of other,
  203. # expect all 404s because room doesn't exist on any server
  204. for usr in [self.user_id, self.rmcreator_id]:
  205. self.helper.join(room=room, user=usr, expect_code=404)
  206. self.helper.leave(room=room, user=usr, expect_code=404)
  207. def test_membership_private_room_perms(self):
  208. room = self.created_rmid
  209. # get membership of self, get membership of other, private room + invite
  210. # expect all 403s
  211. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  212. self._test_get_membership(
  213. members=[self.user_id, self.rmcreator_id], room=room, expect_code=403
  214. )
  215. # get membership of self, get membership of other, private room + joined
  216. # expect all 200s
  217. self.helper.join(room=room, user=self.user_id)
  218. self._test_get_membership(
  219. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  220. )
  221. # get membership of self, get membership of other, private room + left
  222. # expect all 200s
  223. self.helper.leave(room=room, user=self.user_id)
  224. self._test_get_membership(
  225. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  226. )
  227. def test_membership_public_room_perms(self):
  228. room = self.created_public_rmid
  229. # get membership of self, get membership of other, public room + invite
  230. # expect 403
  231. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  232. self._test_get_membership(
  233. members=[self.user_id, self.rmcreator_id], room=room, expect_code=403
  234. )
  235. # get membership of self, get membership of other, public room + joined
  236. # expect all 200s
  237. self.helper.join(room=room, user=self.user_id)
  238. self._test_get_membership(
  239. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  240. )
  241. # get membership of self, get membership of other, public room + left
  242. # expect 200.
  243. self.helper.leave(room=room, user=self.user_id)
  244. self._test_get_membership(
  245. members=[self.user_id, self.rmcreator_id], room=room, expect_code=200
  246. )
  247. def test_invited_permissions(self):
  248. room = self.created_rmid
  249. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  250. # set [invite/join/left] of other user, expect 403s
  251. self.helper.invite(
  252. room=room, src=self.user_id, targ=self.rmcreator_id, expect_code=403
  253. )
  254. self.helper.change_membership(
  255. room=room,
  256. src=self.user_id,
  257. targ=self.rmcreator_id,
  258. membership=Membership.JOIN,
  259. expect_code=403,
  260. )
  261. self.helper.change_membership(
  262. room=room,
  263. src=self.user_id,
  264. targ=self.rmcreator_id,
  265. membership=Membership.LEAVE,
  266. expect_code=403,
  267. )
  268. def test_joined_permissions(self):
  269. room = self.created_rmid
  270. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  271. self.helper.join(room=room, user=self.user_id)
  272. # set invited of self, expect 403
  273. self.helper.invite(
  274. room=room, src=self.user_id, targ=self.user_id, expect_code=403
  275. )
  276. # set joined of self, expect 200 (NOOP)
  277. self.helper.join(room=room, user=self.user_id)
  278. other = "@burgundy:red"
  279. # set invited of other, expect 200
  280. self.helper.invite(room=room, src=self.user_id, targ=other, expect_code=200)
  281. # set joined of other, expect 403
  282. self.helper.change_membership(
  283. room=room,
  284. src=self.user_id,
  285. targ=other,
  286. membership=Membership.JOIN,
  287. expect_code=403,
  288. )
  289. # set left of other, expect 403
  290. self.helper.change_membership(
  291. room=room,
  292. src=self.user_id,
  293. targ=other,
  294. membership=Membership.LEAVE,
  295. expect_code=403,
  296. )
  297. # set left of self, expect 200
  298. self.helper.leave(room=room, user=self.user_id)
  299. def test_leave_permissions(self):
  300. room = self.created_rmid
  301. self.helper.invite(room=room, src=self.rmcreator_id, targ=self.user_id)
  302. self.helper.join(room=room, user=self.user_id)
  303. self.helper.leave(room=room, user=self.user_id)
  304. # set [invite/join/left] of self, set [invite/join/left] of other,
  305. # expect all 403s
  306. for usr in [self.user_id, self.rmcreator_id]:
  307. self.helper.change_membership(
  308. room=room,
  309. src=self.user_id,
  310. targ=usr,
  311. membership=Membership.INVITE,
  312. expect_code=403,
  313. )
  314. self.helper.change_membership(
  315. room=room,
  316. src=self.user_id,
  317. targ=usr,
  318. membership=Membership.JOIN,
  319. expect_code=403,
  320. )
  321. # It is always valid to LEAVE if you've already left (currently.)
  322. self.helper.change_membership(
  323. room=room,
  324. src=self.user_id,
  325. targ=self.rmcreator_id,
  326. membership=Membership.LEAVE,
  327. expect_code=403,
  328. )
  329. class RoomsMemberListTestCase(RoomBase):
  330. """ Tests /rooms/$room_id/members/list REST events."""
  331. user_id = "@sid1:red"
  332. def test_get_member_list(self):
  333. room_id = self.helper.create_room_as(self.user_id)
  334. request, channel = self.make_request("GET", "/rooms/%s/members" % room_id)
  335. self.render(request)
  336. self.assertEquals(200, channel.code, msg=channel.result["body"])
  337. def test_get_member_list_no_room(self):
  338. request, channel = self.make_request("GET", "/rooms/roomdoesnotexist/members")
  339. self.render(request)
  340. self.assertEquals(403, channel.code, msg=channel.result["body"])
  341. def test_get_member_list_no_permission(self):
  342. room_id = self.helper.create_room_as("@some_other_guy:red")
  343. request, channel = self.make_request("GET", "/rooms/%s/members" % room_id)
  344. self.render(request)
  345. self.assertEquals(403, channel.code, msg=channel.result["body"])
  346. def test_get_member_list_mixed_memberships(self):
  347. room_creator = "@some_other_guy:red"
  348. room_id = self.helper.create_room_as(room_creator)
  349. room_path = "/rooms/%s/members" % room_id
  350. self.helper.invite(room=room_id, src=room_creator, targ=self.user_id)
  351. # can't see list if you're just invited.
  352. request, channel = self.make_request("GET", room_path)
  353. self.render(request)
  354. self.assertEquals(403, channel.code, msg=channel.result["body"])
  355. self.helper.join(room=room_id, user=self.user_id)
  356. # can see list now joined
  357. request, channel = self.make_request("GET", room_path)
  358. self.render(request)
  359. self.assertEquals(200, channel.code, msg=channel.result["body"])
  360. self.helper.leave(room=room_id, user=self.user_id)
  361. # can see old list once left
  362. request, channel = self.make_request("GET", room_path)
  363. self.render(request)
  364. self.assertEquals(200, channel.code, msg=channel.result["body"])
  365. class RoomsCreateTestCase(RoomBase):
  366. """ Tests /rooms and /rooms/$room_id REST events. """
  367. user_id = "@sid1:red"
  368. def test_post_room_no_keys(self):
  369. # POST with no config keys, expect new room id
  370. request, channel = self.make_request("POST", "/createRoom", "{}")
  371. self.render(request)
  372. self.assertEquals(200, channel.code, channel.result)
  373. self.assertTrue("room_id" in channel.json_body)
  374. def test_post_room_visibility_key(self):
  375. # POST with visibility config key, expect new room id
  376. request, channel = self.make_request(
  377. "POST", "/createRoom", b'{"visibility":"private"}'
  378. )
  379. self.render(request)
  380. self.assertEquals(200, channel.code)
  381. self.assertTrue("room_id" in channel.json_body)
  382. def test_post_room_custom_key(self):
  383. # POST with custom config keys, expect new room id
  384. request, channel = self.make_request(
  385. "POST", "/createRoom", b'{"custom":"stuff"}'
  386. )
  387. self.render(request)
  388. self.assertEquals(200, channel.code)
  389. self.assertTrue("room_id" in channel.json_body)
  390. def test_post_room_known_and_unknown_keys(self):
  391. # POST with custom + known config keys, expect new room id
  392. request, channel = self.make_request(
  393. "POST", "/createRoom", b'{"visibility":"private","custom":"things"}'
  394. )
  395. self.render(request)
  396. self.assertEquals(200, channel.code)
  397. self.assertTrue("room_id" in channel.json_body)
  398. def test_post_room_invalid_content(self):
  399. # POST with invalid content / paths, expect 400
  400. request, channel = self.make_request("POST", "/createRoom", b'{"visibili')
  401. self.render(request)
  402. self.assertEquals(400, channel.code)
  403. request, channel = self.make_request("POST", "/createRoom", b'["hello"]')
  404. self.render(request)
  405. self.assertEquals(400, channel.code)
  406. def test_post_room_invitees_invalid_mxid(self):
  407. # POST with invalid invitee, see https://github.com/matrix-org/synapse/issues/4088
  408. # Note the trailing space in the MXID here!
  409. request, channel = self.make_request(
  410. "POST", "/createRoom", b'{"invite":["@alice:example.com "]}'
  411. )
  412. self.render(request)
  413. self.assertEquals(400, channel.code)
  414. class RoomTopicTestCase(RoomBase):
  415. """ Tests /rooms/$room_id/topic REST events. """
  416. user_id = "@sid1:red"
  417. def prepare(self, reactor, clock, hs):
  418. # create the room
  419. self.room_id = self.helper.create_room_as(self.user_id)
  420. self.path = "/rooms/%s/state/m.room.topic" % (self.room_id,)
  421. def test_invalid_puts(self):
  422. # missing keys or invalid json
  423. request, channel = self.make_request("PUT", self.path, "{}")
  424. self.render(request)
  425. self.assertEquals(400, channel.code, msg=channel.result["body"])
  426. request, channel = self.make_request("PUT", self.path, '{"_name":"bo"}')
  427. self.render(request)
  428. self.assertEquals(400, channel.code, msg=channel.result["body"])
  429. request, channel = self.make_request("PUT", self.path, '{"nao')
  430. self.render(request)
  431. self.assertEquals(400, channel.code, msg=channel.result["body"])
  432. request, channel = self.make_request(
  433. "PUT", self.path, '[{"_name":"bo"},{"_name":"jill"}]'
  434. )
  435. self.render(request)
  436. self.assertEquals(400, channel.code, msg=channel.result["body"])
  437. request, channel = self.make_request("PUT", self.path, "text only")
  438. self.render(request)
  439. self.assertEquals(400, channel.code, msg=channel.result["body"])
  440. request, channel = self.make_request("PUT", self.path, "")
  441. self.render(request)
  442. self.assertEquals(400, channel.code, msg=channel.result["body"])
  443. # valid key, wrong type
  444. content = '{"topic":["Topic name"]}'
  445. request, channel = self.make_request("PUT", self.path, content)
  446. self.render(request)
  447. self.assertEquals(400, channel.code, msg=channel.result["body"])
  448. def test_rooms_topic(self):
  449. # nothing should be there
  450. request, channel = self.make_request("GET", self.path)
  451. self.render(request)
  452. self.assertEquals(404, channel.code, msg=channel.result["body"])
  453. # valid put
  454. content = '{"topic":"Topic name"}'
  455. request, channel = self.make_request("PUT", self.path, content)
  456. self.render(request)
  457. self.assertEquals(200, channel.code, msg=channel.result["body"])
  458. # valid get
  459. request, channel = self.make_request("GET", self.path)
  460. self.render(request)
  461. self.assertEquals(200, channel.code, msg=channel.result["body"])
  462. self.assert_dict(json.loads(content), channel.json_body)
  463. def test_rooms_topic_with_extra_keys(self):
  464. # valid put with extra keys
  465. content = '{"topic":"Seasons","subtopic":"Summer"}'
  466. request, channel = self.make_request("PUT", self.path, content)
  467. self.render(request)
  468. self.assertEquals(200, channel.code, msg=channel.result["body"])
  469. # valid get
  470. request, channel = self.make_request("GET", self.path)
  471. self.render(request)
  472. self.assertEquals(200, channel.code, msg=channel.result["body"])
  473. self.assert_dict(json.loads(content), channel.json_body)
  474. class RoomMemberStateTestCase(RoomBase):
  475. """ Tests /rooms/$room_id/members/$user_id/state REST events. """
  476. user_id = "@sid1:red"
  477. def prepare(self, reactor, clock, hs):
  478. self.room_id = self.helper.create_room_as(self.user_id)
  479. def test_invalid_puts(self):
  480. path = "/rooms/%s/state/m.room.member/%s" % (self.room_id, self.user_id)
  481. # missing keys or invalid json
  482. request, channel = self.make_request("PUT", path, "{}")
  483. self.render(request)
  484. self.assertEquals(400, channel.code, msg=channel.result["body"])
  485. request, channel = self.make_request("PUT", path, '{"_name":"bo"}')
  486. self.render(request)
  487. self.assertEquals(400, channel.code, msg=channel.result["body"])
  488. request, channel = self.make_request("PUT", path, '{"nao')
  489. self.render(request)
  490. self.assertEquals(400, channel.code, msg=channel.result["body"])
  491. request, channel = self.make_request(
  492. "PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]'
  493. )
  494. self.render(request)
  495. self.assertEquals(400, channel.code, msg=channel.result["body"])
  496. request, channel = self.make_request("PUT", path, "text only")
  497. self.render(request)
  498. self.assertEquals(400, channel.code, msg=channel.result["body"])
  499. request, channel = self.make_request("PUT", path, "")
  500. self.render(request)
  501. self.assertEquals(400, channel.code, msg=channel.result["body"])
  502. # valid keys, wrong types
  503. content = '{"membership":["%s","%s","%s"]}' % (
  504. Membership.INVITE,
  505. Membership.JOIN,
  506. Membership.LEAVE,
  507. )
  508. request, channel = self.make_request("PUT", path, content.encode("ascii"))
  509. self.render(request)
  510. self.assertEquals(400, channel.code, msg=channel.result["body"])
  511. def test_rooms_members_self(self):
  512. path = "/rooms/%s/state/m.room.member/%s" % (
  513. urlparse.quote(self.room_id),
  514. self.user_id,
  515. )
  516. # valid join message (NOOP since we made the room)
  517. content = '{"membership":"%s"}' % Membership.JOIN
  518. request, channel = self.make_request("PUT", path, content.encode("ascii"))
  519. self.render(request)
  520. self.assertEquals(200, channel.code, msg=channel.result["body"])
  521. request, channel = self.make_request("GET", path, None)
  522. self.render(request)
  523. self.assertEquals(200, channel.code, msg=channel.result["body"])
  524. expected_response = {"membership": Membership.JOIN}
  525. self.assertEquals(expected_response, channel.json_body)
  526. def test_rooms_members_other(self):
  527. self.other_id = "@zzsid1:red"
  528. path = "/rooms/%s/state/m.room.member/%s" % (
  529. urlparse.quote(self.room_id),
  530. self.other_id,
  531. )
  532. # valid invite message
  533. content = '{"membership":"%s"}' % Membership.INVITE
  534. request, channel = self.make_request("PUT", path, content)
  535. self.render(request)
  536. self.assertEquals(200, channel.code, msg=channel.result["body"])
  537. request, channel = self.make_request("GET", path, None)
  538. self.render(request)
  539. self.assertEquals(200, channel.code, msg=channel.result["body"])
  540. self.assertEquals(json.loads(content), channel.json_body)
  541. def test_rooms_members_other_custom_keys(self):
  542. self.other_id = "@zzsid1:red"
  543. path = "/rooms/%s/state/m.room.member/%s" % (
  544. urlparse.quote(self.room_id),
  545. self.other_id,
  546. )
  547. # valid invite message with custom key
  548. content = '{"membership":"%s","invite_text":"%s"}' % (
  549. Membership.INVITE,
  550. "Join us!",
  551. )
  552. request, channel = self.make_request("PUT", path, content)
  553. self.render(request)
  554. self.assertEquals(200, channel.code, msg=channel.result["body"])
  555. request, channel = self.make_request("GET", path, None)
  556. self.render(request)
  557. self.assertEquals(200, channel.code, msg=channel.result["body"])
  558. self.assertEquals(json.loads(content), channel.json_body)
  559. class RoomMessagesTestCase(RoomBase):
  560. """ Tests /rooms/$room_id/messages/$user_id/$msg_id REST events. """
  561. user_id = "@sid1:red"
  562. def prepare(self, reactor, clock, hs):
  563. self.room_id = self.helper.create_room_as(self.user_id)
  564. def test_invalid_puts(self):
  565. path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id))
  566. # missing keys or invalid json
  567. request, channel = self.make_request("PUT", path, b"{}")
  568. self.render(request)
  569. self.assertEquals(400, channel.code, msg=channel.result["body"])
  570. request, channel = self.make_request("PUT", path, b'{"_name":"bo"}')
  571. self.render(request)
  572. self.assertEquals(400, channel.code, msg=channel.result["body"])
  573. request, channel = self.make_request("PUT", path, b'{"nao')
  574. self.render(request)
  575. self.assertEquals(400, channel.code, msg=channel.result["body"])
  576. request, channel = self.make_request(
  577. "PUT", path, b'[{"_name":"bo"},{"_name":"jill"}]'
  578. )
  579. self.render(request)
  580. self.assertEquals(400, channel.code, msg=channel.result["body"])
  581. request, channel = self.make_request("PUT", path, b"text only")
  582. self.render(request)
  583. self.assertEquals(400, channel.code, msg=channel.result["body"])
  584. request, channel = self.make_request("PUT", path, b"")
  585. self.render(request)
  586. self.assertEquals(400, channel.code, msg=channel.result["body"])
  587. def test_rooms_messages_sent(self):
  588. path = "/rooms/%s/send/m.room.message/mid1" % (urlparse.quote(self.room_id))
  589. content = b'{"body":"test","msgtype":{"type":"a"}}'
  590. request, channel = self.make_request("PUT", path, content)
  591. self.render(request)
  592. self.assertEquals(400, channel.code, msg=channel.result["body"])
  593. # custom message types
  594. content = b'{"body":"test","msgtype":"test.custom.text"}'
  595. request, channel = self.make_request("PUT", path, content)
  596. self.render(request)
  597. self.assertEquals(200, channel.code, msg=channel.result["body"])
  598. # m.text message type
  599. path = "/rooms/%s/send/m.room.message/mid2" % (urlparse.quote(self.room_id))
  600. content = b'{"body":"test2","msgtype":"m.text"}'
  601. request, channel = self.make_request("PUT", path, content)
  602. self.render(request)
  603. self.assertEquals(200, channel.code, msg=channel.result["body"])
  604. class RoomInitialSyncTestCase(RoomBase):
  605. """ Tests /rooms/$room_id/initialSync. """
  606. user_id = "@sid1:red"
  607. def prepare(self, reactor, clock, hs):
  608. # create the room
  609. self.room_id = self.helper.create_room_as(self.user_id)
  610. def test_initial_sync(self):
  611. request, channel = self.make_request(
  612. "GET", "/rooms/%s/initialSync" % self.room_id
  613. )
  614. self.render(request)
  615. self.assertEquals(200, channel.code)
  616. self.assertEquals(self.room_id, channel.json_body["room_id"])
  617. self.assertEquals("join", channel.json_body["membership"])
  618. # Room state is easier to assert on if we unpack it into a dict
  619. state = {}
  620. for event in channel.json_body["state"]:
  621. if "state_key" not in event:
  622. continue
  623. t = event["type"]
  624. if t not in state:
  625. state[t] = []
  626. state[t].append(event)
  627. self.assertTrue("m.room.create" in state)
  628. self.assertTrue("messages" in channel.json_body)
  629. self.assertTrue("chunk" in channel.json_body["messages"])
  630. self.assertTrue("end" in channel.json_body["messages"])
  631. self.assertTrue("presence" in channel.json_body)
  632. presence_by_user = {
  633. e["content"]["user_id"]: e for e in channel.json_body["presence"]
  634. }
  635. self.assertTrue(self.user_id in presence_by_user)
  636. self.assertEquals("m.presence", presence_by_user[self.user_id]["type"])
  637. class RoomMessageListTestCase(RoomBase):
  638. """ Tests /rooms/$room_id/messages REST events. """
  639. user_id = "@sid1:red"
  640. def prepare(self, reactor, clock, hs):
  641. self.room_id = self.helper.create_room_as(self.user_id)
  642. def test_topo_token_is_accepted(self):
  643. token = "t1-0_0_0_0_0_0_0_0_0"
  644. request, channel = self.make_request(
  645. "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token)
  646. )
  647. self.render(request)
  648. self.assertEquals(200, channel.code)
  649. self.assertTrue("start" in channel.json_body)
  650. self.assertEquals(token, channel.json_body["start"])
  651. self.assertTrue("chunk" in channel.json_body)
  652. self.assertTrue("end" in channel.json_body)
  653. def test_stream_token_is_accepted_for_fwd_pagianation(self):
  654. token = "s0_0_0_0_0_0_0_0_0"
  655. request, channel = self.make_request(
  656. "GET", "/rooms/%s/messages?access_token=x&from=%s" % (self.room_id, token)
  657. )
  658. self.render(request)
  659. self.assertEquals(200, channel.code)
  660. self.assertTrue("start" in channel.json_body)
  661. self.assertEquals(token, channel.json_body["start"])
  662. self.assertTrue("chunk" in channel.json_body)
  663. self.assertTrue("end" in channel.json_body)
  664. def test_room_messages_purge(self):
  665. store = self.hs.get_datastore()
  666. pagination_handler = self.hs.get_pagination_handler()
  667. # Send a first message in the room, which will be removed by the purge.
  668. first_event_id = self.helper.send(self.room_id, "message 1")["event_id"]
  669. first_token = self.get_success(
  670. store.get_topological_token_for_event(first_event_id)
  671. )
  672. # Send a second message in the room, which won't be removed, and which we'll
  673. # use as the marker to purge events before.
  674. second_event_id = self.helper.send(self.room_id, "message 2")["event_id"]
  675. second_token = self.get_success(
  676. store.get_topological_token_for_event(second_event_id)
  677. )
  678. # Send a third event in the room to ensure we don't fall under any edge case
  679. # due to our marker being the latest forward extremity in the room.
  680. self.helper.send(self.room_id, "message 3")
  681. # Check that we get the first and second message when querying /messages.
  682. request, channel = self.make_request(
  683. "GET",
  684. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  685. % (self.room_id, second_token, json.dumps({"types": [EventTypes.Message]})),
  686. )
  687. self.render(request)
  688. self.assertEqual(channel.code, 200, channel.json_body)
  689. chunk = channel.json_body["chunk"]
  690. self.assertEqual(len(chunk), 2, [event["content"] for event in chunk])
  691. # Purge every event before the second event.
  692. purge_id = random_string(16)
  693. pagination_handler._purges_by_id[purge_id] = PurgeStatus()
  694. self.get_success(
  695. pagination_handler._purge_history(
  696. purge_id=purge_id,
  697. room_id=self.room_id,
  698. token=second_token,
  699. delete_local_events=True,
  700. )
  701. )
  702. # Check that we only get the second message through /message now that the first
  703. # has been purged.
  704. request, channel = self.make_request(
  705. "GET",
  706. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  707. % (self.room_id, second_token, json.dumps({"types": [EventTypes.Message]})),
  708. )
  709. self.render(request)
  710. self.assertEqual(channel.code, 200, channel.json_body)
  711. chunk = channel.json_body["chunk"]
  712. self.assertEqual(len(chunk), 1, [event["content"] for event in chunk])
  713. # Check that we get no event, but also no error, when querying /messages with
  714. # the token that was pointing at the first event, because we don't have it
  715. # anymore.
  716. request, channel = self.make_request(
  717. "GET",
  718. "/rooms/%s/messages?access_token=x&from=%s&dir=b&filter=%s"
  719. % (self.room_id, first_token, json.dumps({"types": [EventTypes.Message]})),
  720. )
  721. self.render(request)
  722. self.assertEqual(channel.code, 200, channel.json_body)
  723. chunk = channel.json_body["chunk"]
  724. self.assertEqual(len(chunk), 0, [event["content"] for event in chunk])
  725. class RoomSearchTestCase(unittest.HomeserverTestCase):
  726. servlets = [
  727. synapse.rest.admin.register_servlets_for_client_rest_resource,
  728. room.register_servlets,
  729. login.register_servlets,
  730. ]
  731. user_id = True
  732. hijack_auth = False
  733. def prepare(self, reactor, clock, hs):
  734. # Register the user who does the searching
  735. self.user_id = self.register_user("user", "pass")
  736. self.access_token = self.login("user", "pass")
  737. # Register the user who sends the message
  738. self.other_user_id = self.register_user("otheruser", "pass")
  739. self.other_access_token = self.login("otheruser", "pass")
  740. # Create a room
  741. self.room = self.helper.create_room_as(self.user_id, tok=self.access_token)
  742. # Invite the other person
  743. self.helper.invite(
  744. room=self.room,
  745. src=self.user_id,
  746. tok=self.access_token,
  747. targ=self.other_user_id,
  748. )
  749. # The other user joins
  750. self.helper.join(
  751. room=self.room, user=self.other_user_id, tok=self.other_access_token
  752. )
  753. def test_finds_message(self):
  754. """
  755. The search functionality will search for content in messages if asked to
  756. do so.
  757. """
  758. # The other user sends some messages
  759. self.helper.send(self.room, body="Hi!", tok=self.other_access_token)
  760. self.helper.send(self.room, body="There!", tok=self.other_access_token)
  761. request, channel = self.make_request(
  762. "POST",
  763. "/search?access_token=%s" % (self.access_token,),
  764. {
  765. "search_categories": {
  766. "room_events": {"keys": ["content.body"], "search_term": "Hi"}
  767. }
  768. },
  769. )
  770. self.render(request)
  771. # Check we get the results we expect -- one search result, of the sent
  772. # messages
  773. self.assertEqual(channel.code, 200)
  774. results = channel.json_body["search_categories"]["room_events"]
  775. self.assertEqual(results["count"], 1)
  776. self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!")
  777. # No context was requested, so we should get none.
  778. self.assertEqual(results["results"][0]["context"], {})
  779. def test_include_context(self):
  780. """
  781. When event_context includes include_profile, profile information will be
  782. included in the search response.
  783. """
  784. # The other user sends some messages
  785. self.helper.send(self.room, body="Hi!", tok=self.other_access_token)
  786. self.helper.send(self.room, body="There!", tok=self.other_access_token)
  787. request, channel = self.make_request(
  788. "POST",
  789. "/search?access_token=%s" % (self.access_token,),
  790. {
  791. "search_categories": {
  792. "room_events": {
  793. "keys": ["content.body"],
  794. "search_term": "Hi",
  795. "event_context": {"include_profile": True},
  796. }
  797. }
  798. },
  799. )
  800. self.render(request)
  801. # Check we get the results we expect -- one search result, of the sent
  802. # messages
  803. self.assertEqual(channel.code, 200)
  804. results = channel.json_body["search_categories"]["room_events"]
  805. self.assertEqual(results["count"], 1)
  806. self.assertEqual(results["results"][0]["result"]["content"]["body"], "Hi!")
  807. # We should get context info, like the two users, and the display names.
  808. context = results["results"][0]["context"]
  809. self.assertEqual(len(context["profile_info"].keys()), 2)
  810. self.assertEqual(
  811. context["profile_info"][self.other_user_id]["displayname"], "otheruser"
  812. )
  813. class PublicRoomsRestrictedTestCase(unittest.HomeserverTestCase):
  814. servlets = [
  815. synapse.rest.admin.register_servlets_for_client_rest_resource,
  816. room.register_servlets,
  817. login.register_servlets,
  818. ]
  819. def make_homeserver(self, reactor, clock):
  820. self.url = b"/_matrix/client/r0/publicRooms"
  821. config = self.default_config()
  822. config["allow_public_rooms_without_auth"] = False
  823. self.hs = self.setup_test_homeserver(config=config)
  824. return self.hs
  825. def test_restricted_no_auth(self):
  826. request, channel = self.make_request("GET", self.url)
  827. self.render(request)
  828. self.assertEqual(channel.code, 401, channel.result)
  829. def test_restricted_auth(self):
  830. self.register_user("user", "pass")
  831. tok = self.login("user", "pass")
  832. request, channel = self.make_request("GET", self.url, access_token=tok)
  833. self.render(request)
  834. self.assertEqual(channel.code, 200, channel.result)
  835. class PerRoomProfilesForbiddenTestCase(unittest.HomeserverTestCase):
  836. servlets = [
  837. synapse.rest.admin.register_servlets_for_client_rest_resource,
  838. room.register_servlets,
  839. login.register_servlets,
  840. profile.register_servlets,
  841. ]
  842. def make_homeserver(self, reactor, clock):
  843. config = self.default_config()
  844. config["allow_per_room_profiles"] = False
  845. self.hs = self.setup_test_homeserver(config=config)
  846. return self.hs
  847. def prepare(self, reactor, clock, homeserver):
  848. self.user_id = self.register_user("test", "test")
  849. self.tok = self.login("test", "test")
  850. # Set a profile for the test user
  851. self.displayname = "test user"
  852. data = {"displayname": self.displayname}
  853. request_data = json.dumps(data)
  854. request, channel = self.make_request(
  855. "PUT",
  856. "/_matrix/client/r0/profile/%s/displayname" % (self.user_id,),
  857. request_data,
  858. access_token=self.tok,
  859. )
  860. self.render(request)
  861. self.assertEqual(channel.code, 200, channel.result)
  862. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  863. def test_per_room_profile_forbidden(self):
  864. data = {"membership": "join", "displayname": "other test user"}
  865. request_data = json.dumps(data)
  866. request, channel = self.make_request(
  867. "PUT",
  868. "/_matrix/client/r0/rooms/%s/state/m.room.member/%s"
  869. % (self.room_id, self.user_id),
  870. request_data,
  871. access_token=self.tok,
  872. )
  873. self.render(request)
  874. self.assertEqual(channel.code, 200, channel.result)
  875. event_id = channel.json_body["event_id"]
  876. request, channel = self.make_request(
  877. "GET",
  878. "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, event_id),
  879. access_token=self.tok,
  880. )
  881. self.render(request)
  882. self.assertEqual(channel.code, 200, channel.result)
  883. res_displayname = channel.json_body["content"]["displayname"]
  884. self.assertEqual(res_displayname, self.displayname, channel.result)
  885. class RoomMembershipReasonTestCase(unittest.HomeserverTestCase):
  886. """Tests that clients can add a "reason" field to membership events and
  887. that they get correctly added to the generated events and propagated.
  888. """
  889. servlets = [
  890. synapse.rest.admin.register_servlets_for_client_rest_resource,
  891. room.register_servlets,
  892. login.register_servlets,
  893. ]
  894. def prepare(self, reactor, clock, homeserver):
  895. self.creator = self.register_user("creator", "test")
  896. self.creator_tok = self.login("creator", "test")
  897. self.second_user_id = self.register_user("second", "test")
  898. self.second_tok = self.login("second", "test")
  899. self.room_id = self.helper.create_room_as(self.creator, tok=self.creator_tok)
  900. def test_join_reason(self):
  901. reason = "hello"
  902. request, channel = self.make_request(
  903. "POST",
  904. "/_matrix/client/r0/rooms/{}/join".format(self.room_id),
  905. content={"reason": reason},
  906. access_token=self.second_tok,
  907. )
  908. self.render(request)
  909. self.assertEqual(channel.code, 200, channel.result)
  910. self._check_for_reason(reason)
  911. def test_leave_reason(self):
  912. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  913. reason = "hello"
  914. request, channel = self.make_request(
  915. "POST",
  916. "/_matrix/client/r0/rooms/{}/leave".format(self.room_id),
  917. content={"reason": reason},
  918. access_token=self.second_tok,
  919. )
  920. self.render(request)
  921. self.assertEqual(channel.code, 200, channel.result)
  922. self._check_for_reason(reason)
  923. def test_kick_reason(self):
  924. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  925. reason = "hello"
  926. request, channel = self.make_request(
  927. "POST",
  928. "/_matrix/client/r0/rooms/{}/kick".format(self.room_id),
  929. content={"reason": reason, "user_id": self.second_user_id},
  930. access_token=self.second_tok,
  931. )
  932. self.render(request)
  933. self.assertEqual(channel.code, 200, channel.result)
  934. self._check_for_reason(reason)
  935. def test_ban_reason(self):
  936. self.helper.join(self.room_id, user=self.second_user_id, tok=self.second_tok)
  937. reason = "hello"
  938. request, channel = self.make_request(
  939. "POST",
  940. "/_matrix/client/r0/rooms/{}/ban".format(self.room_id),
  941. content={"reason": reason, "user_id": self.second_user_id},
  942. access_token=self.creator_tok,
  943. )
  944. self.render(request)
  945. self.assertEqual(channel.code, 200, channel.result)
  946. self._check_for_reason(reason)
  947. def test_unban_reason(self):
  948. reason = "hello"
  949. request, channel = self.make_request(
  950. "POST",
  951. "/_matrix/client/r0/rooms/{}/unban".format(self.room_id),
  952. content={"reason": reason, "user_id": self.second_user_id},
  953. access_token=self.creator_tok,
  954. )
  955. self.render(request)
  956. self.assertEqual(channel.code, 200, channel.result)
  957. self._check_for_reason(reason)
  958. def test_invite_reason(self):
  959. reason = "hello"
  960. request, channel = self.make_request(
  961. "POST",
  962. "/_matrix/client/r0/rooms/{}/invite".format(self.room_id),
  963. content={"reason": reason, "user_id": self.second_user_id},
  964. access_token=self.creator_tok,
  965. )
  966. self.render(request)
  967. self.assertEqual(channel.code, 200, channel.result)
  968. self._check_for_reason(reason)
  969. def test_reject_invite_reason(self):
  970. self.helper.invite(
  971. self.room_id,
  972. src=self.creator,
  973. targ=self.second_user_id,
  974. tok=self.creator_tok,
  975. )
  976. reason = "hello"
  977. request, channel = self.make_request(
  978. "POST",
  979. "/_matrix/client/r0/rooms/{}/leave".format(self.room_id),
  980. content={"reason": reason},
  981. access_token=self.second_tok,
  982. )
  983. self.render(request)
  984. self.assertEqual(channel.code, 200, channel.result)
  985. self._check_for_reason(reason)
  986. def _check_for_reason(self, reason):
  987. request, channel = self.make_request(
  988. "GET",
  989. "/_matrix/client/r0/rooms/{}/state/m.room.member/{}".format(
  990. self.room_id, self.second_user_id
  991. ),
  992. access_token=self.creator_tok,
  993. )
  994. self.render(request)
  995. self.assertEqual(channel.code, 200, channel.result)
  996. event_content = channel.json_body
  997. self.assertEqual(event_content.get("reason"), reason, channel.result)
  998. class LabelsTestCase(unittest.HomeserverTestCase):
  999. servlets = [
  1000. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1001. room.register_servlets,
  1002. login.register_servlets,
  1003. profile.register_servlets,
  1004. ]
  1005. # Filter that should only catch messages with the label "#fun".
  1006. FILTER_LABELS = {
  1007. "types": [EventTypes.Message],
  1008. "org.matrix.labels": ["#fun"],
  1009. }
  1010. # Filter that should only catch messages without the label "#fun".
  1011. FILTER_NOT_LABELS = {
  1012. "types": [EventTypes.Message],
  1013. "org.matrix.not_labels": ["#fun"],
  1014. }
  1015. # Filter that should only catch messages with the label "#work" but without the label
  1016. # "#notfun".
  1017. FILTER_LABELS_NOT_LABELS = {
  1018. "types": [EventTypes.Message],
  1019. "org.matrix.labels": ["#work"],
  1020. "org.matrix.not_labels": ["#notfun"],
  1021. }
  1022. def prepare(self, reactor, clock, homeserver):
  1023. self.user_id = self.register_user("test", "test")
  1024. self.tok = self.login("test", "test")
  1025. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  1026. def test_context_filter_labels(self):
  1027. """Test that we can filter by a label on a /context request."""
  1028. event_id = self._send_labelled_messages_in_room()
  1029. request, channel = self.make_request(
  1030. "GET",
  1031. "/rooms/%s/context/%s?filter=%s"
  1032. % (self.room_id, event_id, json.dumps(self.FILTER_LABELS)),
  1033. access_token=self.tok,
  1034. )
  1035. self.render(request)
  1036. self.assertEqual(channel.code, 200, channel.result)
  1037. events_before = channel.json_body["events_before"]
  1038. self.assertEqual(
  1039. len(events_before), 1, [event["content"] for event in events_before]
  1040. )
  1041. self.assertEqual(
  1042. events_before[0]["content"]["body"], "with right label", events_before[0]
  1043. )
  1044. events_after = channel.json_body["events_before"]
  1045. self.assertEqual(
  1046. len(events_after), 1, [event["content"] for event in events_after]
  1047. )
  1048. self.assertEqual(
  1049. events_after[0]["content"]["body"], "with right label", events_after[0]
  1050. )
  1051. def test_context_filter_not_labels(self):
  1052. """Test that we can filter by the absence of a label on a /context request."""
  1053. event_id = self._send_labelled_messages_in_room()
  1054. request, channel = self.make_request(
  1055. "GET",
  1056. "/rooms/%s/context/%s?filter=%s"
  1057. % (self.room_id, event_id, json.dumps(self.FILTER_NOT_LABELS)),
  1058. access_token=self.tok,
  1059. )
  1060. self.render(request)
  1061. self.assertEqual(channel.code, 200, channel.result)
  1062. events_before = channel.json_body["events_before"]
  1063. self.assertEqual(
  1064. len(events_before), 1, [event["content"] for event in events_before]
  1065. )
  1066. self.assertEqual(
  1067. events_before[0]["content"]["body"], "without label", events_before[0]
  1068. )
  1069. events_after = channel.json_body["events_after"]
  1070. self.assertEqual(
  1071. len(events_after), 2, [event["content"] for event in events_after]
  1072. )
  1073. self.assertEqual(
  1074. events_after[0]["content"]["body"], "with wrong label", events_after[0]
  1075. )
  1076. self.assertEqual(
  1077. events_after[1]["content"]["body"], "with two wrong labels", events_after[1]
  1078. )
  1079. def test_context_filter_labels_not_labels(self):
  1080. """Test that we can filter by both a label and the absence of another label on a
  1081. /context request.
  1082. """
  1083. event_id = self._send_labelled_messages_in_room()
  1084. request, channel = self.make_request(
  1085. "GET",
  1086. "/rooms/%s/context/%s?filter=%s"
  1087. % (self.room_id, event_id, json.dumps(self.FILTER_LABELS_NOT_LABELS)),
  1088. access_token=self.tok,
  1089. )
  1090. self.render(request)
  1091. self.assertEqual(channel.code, 200, channel.result)
  1092. events_before = channel.json_body["events_before"]
  1093. self.assertEqual(
  1094. len(events_before), 0, [event["content"] for event in events_before]
  1095. )
  1096. events_after = channel.json_body["events_after"]
  1097. self.assertEqual(
  1098. len(events_after), 1, [event["content"] for event in events_after]
  1099. )
  1100. self.assertEqual(
  1101. events_after[0]["content"]["body"], "with wrong label", events_after[0]
  1102. )
  1103. def test_messages_filter_labels(self):
  1104. """Test that we can filter by a label on a /messages request."""
  1105. self._send_labelled_messages_in_room()
  1106. token = "s0_0_0_0_0_0_0_0_0"
  1107. request, channel = self.make_request(
  1108. "GET",
  1109. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  1110. % (self.room_id, self.tok, token, json.dumps(self.FILTER_LABELS)),
  1111. )
  1112. self.render(request)
  1113. events = channel.json_body["chunk"]
  1114. self.assertEqual(len(events), 2, [event["content"] for event in events])
  1115. self.assertEqual(events[0]["content"]["body"], "with right label", events[0])
  1116. self.assertEqual(events[1]["content"]["body"], "with right label", events[1])
  1117. def test_messages_filter_not_labels(self):
  1118. """Test that we can filter by the absence of a label on a /messages request."""
  1119. self._send_labelled_messages_in_room()
  1120. token = "s0_0_0_0_0_0_0_0_0"
  1121. request, channel = self.make_request(
  1122. "GET",
  1123. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  1124. % (self.room_id, self.tok, token, json.dumps(self.FILTER_NOT_LABELS)),
  1125. )
  1126. self.render(request)
  1127. events = channel.json_body["chunk"]
  1128. self.assertEqual(len(events), 4, [event["content"] for event in events])
  1129. self.assertEqual(events[0]["content"]["body"], "without label", events[0])
  1130. self.assertEqual(events[1]["content"]["body"], "without label", events[1])
  1131. self.assertEqual(events[2]["content"]["body"], "with wrong label", events[2])
  1132. self.assertEqual(
  1133. events[3]["content"]["body"], "with two wrong labels", events[3]
  1134. )
  1135. def test_messages_filter_labels_not_labels(self):
  1136. """Test that we can filter by both a label and the absence of another label on a
  1137. /messages request.
  1138. """
  1139. self._send_labelled_messages_in_room()
  1140. token = "s0_0_0_0_0_0_0_0_0"
  1141. request, channel = self.make_request(
  1142. "GET",
  1143. "/rooms/%s/messages?access_token=%s&from=%s&filter=%s"
  1144. % (
  1145. self.room_id,
  1146. self.tok,
  1147. token,
  1148. json.dumps(self.FILTER_LABELS_NOT_LABELS),
  1149. ),
  1150. )
  1151. self.render(request)
  1152. events = channel.json_body["chunk"]
  1153. self.assertEqual(len(events), 1, [event["content"] for event in events])
  1154. self.assertEqual(events[0]["content"]["body"], "with wrong label", events[0])
  1155. def test_search_filter_labels(self):
  1156. """Test that we can filter by a label on a /search request."""
  1157. request_data = json.dumps(
  1158. {
  1159. "search_categories": {
  1160. "room_events": {
  1161. "search_term": "label",
  1162. "filter": self.FILTER_LABELS,
  1163. }
  1164. }
  1165. }
  1166. )
  1167. self._send_labelled_messages_in_room()
  1168. request, channel = self.make_request(
  1169. "POST", "/search?access_token=%s" % self.tok, request_data
  1170. )
  1171. self.render(request)
  1172. results = channel.json_body["search_categories"]["room_events"]["results"]
  1173. self.assertEqual(
  1174. len(results), 2, [result["result"]["content"] for result in results],
  1175. )
  1176. self.assertEqual(
  1177. results[0]["result"]["content"]["body"],
  1178. "with right label",
  1179. results[0]["result"]["content"]["body"],
  1180. )
  1181. self.assertEqual(
  1182. results[1]["result"]["content"]["body"],
  1183. "with right label",
  1184. results[1]["result"]["content"]["body"],
  1185. )
  1186. def test_search_filter_not_labels(self):
  1187. """Test that we can filter by the absence of a label on a /search request."""
  1188. request_data = json.dumps(
  1189. {
  1190. "search_categories": {
  1191. "room_events": {
  1192. "search_term": "label",
  1193. "filter": self.FILTER_NOT_LABELS,
  1194. }
  1195. }
  1196. }
  1197. )
  1198. self._send_labelled_messages_in_room()
  1199. request, channel = self.make_request(
  1200. "POST", "/search?access_token=%s" % self.tok, request_data
  1201. )
  1202. self.render(request)
  1203. results = channel.json_body["search_categories"]["room_events"]["results"]
  1204. self.assertEqual(
  1205. len(results), 4, [result["result"]["content"] for result in results],
  1206. )
  1207. self.assertEqual(
  1208. results[0]["result"]["content"]["body"],
  1209. "without label",
  1210. results[0]["result"]["content"]["body"],
  1211. )
  1212. self.assertEqual(
  1213. results[1]["result"]["content"]["body"],
  1214. "without label",
  1215. results[1]["result"]["content"]["body"],
  1216. )
  1217. self.assertEqual(
  1218. results[2]["result"]["content"]["body"],
  1219. "with wrong label",
  1220. results[2]["result"]["content"]["body"],
  1221. )
  1222. self.assertEqual(
  1223. results[3]["result"]["content"]["body"],
  1224. "with two wrong labels",
  1225. results[3]["result"]["content"]["body"],
  1226. )
  1227. def test_search_filter_labels_not_labels(self):
  1228. """Test that we can filter by both a label and the absence of another label on a
  1229. /search request.
  1230. """
  1231. request_data = json.dumps(
  1232. {
  1233. "search_categories": {
  1234. "room_events": {
  1235. "search_term": "label",
  1236. "filter": self.FILTER_LABELS_NOT_LABELS,
  1237. }
  1238. }
  1239. }
  1240. )
  1241. self._send_labelled_messages_in_room()
  1242. request, channel = self.make_request(
  1243. "POST", "/search?access_token=%s" % self.tok, request_data
  1244. )
  1245. self.render(request)
  1246. results = channel.json_body["search_categories"]["room_events"]["results"]
  1247. self.assertEqual(
  1248. len(results), 1, [result["result"]["content"] for result in results],
  1249. )
  1250. self.assertEqual(
  1251. results[0]["result"]["content"]["body"],
  1252. "with wrong label",
  1253. results[0]["result"]["content"]["body"],
  1254. )
  1255. def _send_labelled_messages_in_room(self):
  1256. """Sends several messages to a room with different labels (or without any) to test
  1257. filtering by label.
  1258. Returns:
  1259. The ID of the event to use if we're testing filtering on /context.
  1260. """
  1261. self.helper.send_event(
  1262. room_id=self.room_id,
  1263. type=EventTypes.Message,
  1264. content={
  1265. "msgtype": "m.text",
  1266. "body": "with right label",
  1267. EventContentFields.LABELS: ["#fun"],
  1268. },
  1269. tok=self.tok,
  1270. )
  1271. self.helper.send_event(
  1272. room_id=self.room_id,
  1273. type=EventTypes.Message,
  1274. content={"msgtype": "m.text", "body": "without label"},
  1275. tok=self.tok,
  1276. )
  1277. res = self.helper.send_event(
  1278. room_id=self.room_id,
  1279. type=EventTypes.Message,
  1280. content={"msgtype": "m.text", "body": "without label"},
  1281. tok=self.tok,
  1282. )
  1283. # Return this event's ID when we test filtering in /context requests.
  1284. event_id = res["event_id"]
  1285. self.helper.send_event(
  1286. room_id=self.room_id,
  1287. type=EventTypes.Message,
  1288. content={
  1289. "msgtype": "m.text",
  1290. "body": "with wrong label",
  1291. EventContentFields.LABELS: ["#work"],
  1292. },
  1293. tok=self.tok,
  1294. )
  1295. self.helper.send_event(
  1296. room_id=self.room_id,
  1297. type=EventTypes.Message,
  1298. content={
  1299. "msgtype": "m.text",
  1300. "body": "with two wrong labels",
  1301. EventContentFields.LABELS: ["#work", "#notfun"],
  1302. },
  1303. tok=self.tok,
  1304. )
  1305. self.helper.send_event(
  1306. room_id=self.room_id,
  1307. type=EventTypes.Message,
  1308. content={
  1309. "msgtype": "m.text",
  1310. "body": "with right label",
  1311. EventContentFields.LABELS: ["#fun"],
  1312. },
  1313. tok=self.tok,
  1314. )
  1315. return event_id
  1316. class ContextTestCase(unittest.HomeserverTestCase):
  1317. servlets = [
  1318. synapse.rest.admin.register_servlets_for_client_rest_resource,
  1319. room.register_servlets,
  1320. login.register_servlets,
  1321. account.register_servlets,
  1322. ]
  1323. def prepare(self, reactor, clock, homeserver):
  1324. self.user_id = self.register_user("user", "password")
  1325. self.tok = self.login("user", "password")
  1326. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  1327. self.other_user_id = self.register_user("user2", "password")
  1328. self.other_tok = self.login("user2", "password")
  1329. self.helper.invite(self.room_id, self.user_id, self.other_user_id, tok=self.tok)
  1330. self.helper.join(self.room_id, self.other_user_id, tok=self.other_tok)
  1331. def test_erased_sender(self):
  1332. """Test that an erasure request results in the requester's events being hidden
  1333. from any new member of the room.
  1334. """
  1335. # Send a bunch of events in the room.
  1336. self.helper.send(self.room_id, "message 1", tok=self.tok)
  1337. self.helper.send(self.room_id, "message 2", tok=self.tok)
  1338. event_id = self.helper.send(self.room_id, "message 3", tok=self.tok)["event_id"]
  1339. self.helper.send(self.room_id, "message 4", tok=self.tok)
  1340. self.helper.send(self.room_id, "message 5", tok=self.tok)
  1341. # Check that we can still see the messages before the erasure request.
  1342. request, channel = self.make_request(
  1343. "GET",
  1344. '/rooms/%s/context/%s?filter={"types":["m.room.message"]}'
  1345. % (self.room_id, event_id),
  1346. access_token=self.tok,
  1347. )
  1348. self.render(request)
  1349. self.assertEqual(channel.code, 200, channel.result)
  1350. events_before = channel.json_body["events_before"]
  1351. self.assertEqual(len(events_before), 2, events_before)
  1352. self.assertEqual(
  1353. events_before[0].get("content", {}).get("body"),
  1354. "message 2",
  1355. events_before[0],
  1356. )
  1357. self.assertEqual(
  1358. events_before[1].get("content", {}).get("body"),
  1359. "message 1",
  1360. events_before[1],
  1361. )
  1362. self.assertEqual(
  1363. channel.json_body["event"].get("content", {}).get("body"),
  1364. "message 3",
  1365. channel.json_body["event"],
  1366. )
  1367. events_after = channel.json_body["events_after"]
  1368. self.assertEqual(len(events_after), 2, events_after)
  1369. self.assertEqual(
  1370. events_after[0].get("content", {}).get("body"),
  1371. "message 4",
  1372. events_after[0],
  1373. )
  1374. self.assertEqual(
  1375. events_after[1].get("content", {}).get("body"),
  1376. "message 5",
  1377. events_after[1],
  1378. )
  1379. # Deactivate the first account and erase the user's data.
  1380. deactivate_account_handler = self.hs.get_deactivate_account_handler()
  1381. self.get_success(
  1382. deactivate_account_handler.deactivate_account(self.user_id, erase_data=True)
  1383. )
  1384. # Invite another user in the room. This is needed because messages will be
  1385. # pruned only if the user wasn't a member of the room when the messages were
  1386. # sent.
  1387. invited_user_id = self.register_user("user3", "password")
  1388. invited_tok = self.login("user3", "password")
  1389. self.helper.invite(
  1390. self.room_id, self.other_user_id, invited_user_id, tok=self.other_tok
  1391. )
  1392. self.helper.join(self.room_id, invited_user_id, tok=invited_tok)
  1393. # Check that a user that joined the room after the erasure request can't see
  1394. # the messages anymore.
  1395. request, channel = self.make_request(
  1396. "GET",
  1397. '/rooms/%s/context/%s?filter={"types":["m.room.message"]}'
  1398. % (self.room_id, event_id),
  1399. access_token=invited_tok,
  1400. )
  1401. self.render(request)
  1402. self.assertEqual(channel.code, 200, channel.result)
  1403. events_before = channel.json_body["events_before"]
  1404. self.assertEqual(len(events_before), 2, events_before)
  1405. self.assertDictEqual(events_before[0].get("content"), {}, events_before[0])
  1406. self.assertDictEqual(events_before[1].get("content"), {}, events_before[1])
  1407. self.assertDictEqual(
  1408. channel.json_body["event"].get("content"), {}, channel.json_body["event"]
  1409. )
  1410. events_after = channel.json_body["events_after"]
  1411. self.assertEqual(len(events_after), 2, events_after)
  1412. self.assertDictEqual(events_after[0].get("content"), {}, events_after[0])
  1413. self.assertEqual(events_after[1].get("content"), {}, events_after[1])