test_room_summary.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Any, Iterable, List, Optional, Tuple
  15. from unittest import mock
  16. from twisted.internet.defer import ensureDeferred
  17. from synapse.api.constants import (
  18. EventContentFields,
  19. EventTypes,
  20. HistoryVisibility,
  21. JoinRules,
  22. Membership,
  23. RestrictedJoinRuleTypes,
  24. RoomTypes,
  25. )
  26. from synapse.api.errors import AuthError, NotFoundError, SynapseError
  27. from synapse.api.room_versions import RoomVersions
  28. from synapse.events import make_event_from_dict
  29. from synapse.handlers.room_summary import _child_events_comparison_key, _RoomEntry
  30. from synapse.rest import admin
  31. from synapse.rest.client import login, room
  32. from synapse.server import HomeServer
  33. from synapse.types import JsonDict, UserID
  34. from tests import unittest
  35. def _create_event(room_id: str, order: Optional[Any] = None, origin_server_ts: int = 0):
  36. result = mock.Mock(name=room_id)
  37. result.room_id = room_id
  38. result.content = {}
  39. result.origin_server_ts = origin_server_ts
  40. if order is not None:
  41. result.content["order"] = order
  42. return result
  43. def _order(*events):
  44. return sorted(events, key=_child_events_comparison_key)
  45. class TestSpaceSummarySort(unittest.TestCase):
  46. def test_no_order_last(self):
  47. """An event with no ordering is placed behind those with an ordering."""
  48. ev1 = _create_event("!abc:test")
  49. ev2 = _create_event("!xyz:test", "xyz")
  50. self.assertEqual([ev2, ev1], _order(ev1, ev2))
  51. def test_order(self):
  52. """The ordering should be used."""
  53. ev1 = _create_event("!abc:test", "xyz")
  54. ev2 = _create_event("!xyz:test", "abc")
  55. self.assertEqual([ev2, ev1], _order(ev1, ev2))
  56. def test_order_origin_server_ts(self):
  57. """Origin server is a tie-breaker for ordering."""
  58. ev1 = _create_event("!abc:test", origin_server_ts=10)
  59. ev2 = _create_event("!xyz:test", origin_server_ts=30)
  60. self.assertEqual([ev1, ev2], _order(ev1, ev2))
  61. def test_order_room_id(self):
  62. """Room ID is a final tie-breaker for ordering."""
  63. ev1 = _create_event("!abc:test")
  64. ev2 = _create_event("!xyz:test")
  65. self.assertEqual([ev1, ev2], _order(ev1, ev2))
  66. def test_invalid_ordering_type(self):
  67. """Invalid orderings are considered the same as missing."""
  68. ev1 = _create_event("!abc:test", 1)
  69. ev2 = _create_event("!xyz:test", "xyz")
  70. self.assertEqual([ev2, ev1], _order(ev1, ev2))
  71. ev1 = _create_event("!abc:test", {})
  72. self.assertEqual([ev2, ev1], _order(ev1, ev2))
  73. ev1 = _create_event("!abc:test", [])
  74. self.assertEqual([ev2, ev1], _order(ev1, ev2))
  75. ev1 = _create_event("!abc:test", True)
  76. self.assertEqual([ev2, ev1], _order(ev1, ev2))
  77. def test_invalid_ordering_value(self):
  78. """Invalid orderings are considered the same as missing."""
  79. ev1 = _create_event("!abc:test", "foo\n")
  80. ev2 = _create_event("!xyz:test", "xyz")
  81. self.assertEqual([ev2, ev1], _order(ev1, ev2))
  82. ev1 = _create_event("!abc:test", "a" * 51)
  83. self.assertEqual([ev2, ev1], _order(ev1, ev2))
  84. class SpaceSummaryTestCase(unittest.HomeserverTestCase):
  85. servlets = [
  86. admin.register_servlets_for_client_rest_resource,
  87. room.register_servlets,
  88. login.register_servlets,
  89. ]
  90. def prepare(self, reactor, clock, hs: HomeServer):
  91. self.hs = hs
  92. self.handler = self.hs.get_room_summary_handler()
  93. # Create a user.
  94. self.user = self.register_user("user", "pass")
  95. self.token = self.login("user", "pass")
  96. # Create a space and a child room.
  97. self.space = self.helper.create_room_as(
  98. self.user,
  99. tok=self.token,
  100. extra_content={
  101. "creation_content": {EventContentFields.ROOM_TYPE: RoomTypes.SPACE}
  102. },
  103. )
  104. self.room = self.helper.create_room_as(self.user, tok=self.token)
  105. self._add_child(self.space, self.room, self.token)
  106. def _add_child(
  107. self, space_id: str, room_id: str, token: str, order: Optional[str] = None
  108. ) -> None:
  109. """Add a child room to a space."""
  110. content: JsonDict = {"via": [self.hs.hostname]}
  111. if order is not None:
  112. content["order"] = order
  113. self.helper.send_state(
  114. space_id,
  115. event_type=EventTypes.SpaceChild,
  116. body=content,
  117. tok=token,
  118. state_key=room_id,
  119. )
  120. def _assert_rooms(
  121. self, result: JsonDict, rooms_and_children: Iterable[Tuple[str, Iterable[str]]]
  122. ) -> None:
  123. """
  124. Assert that the expected room IDs and events are in the response.
  125. Args:
  126. result: The result from the API call.
  127. rooms_and_children: An iterable of tuples where each tuple is:
  128. The expected room ID.
  129. The expected IDs of any children rooms.
  130. """
  131. room_ids = []
  132. children_ids = []
  133. for room_id, children in rooms_and_children:
  134. room_ids.append(room_id)
  135. if children:
  136. children_ids.extend([(room_id, child_id) for child_id in children])
  137. self.assertCountEqual(
  138. [room.get("room_id") for room in result["rooms"]], room_ids
  139. )
  140. self.assertCountEqual(
  141. [
  142. (event.get("room_id"), event.get("state_key"))
  143. for event in result["events"]
  144. ],
  145. children_ids,
  146. )
  147. def _assert_hierarchy(
  148. self, result: JsonDict, rooms_and_children: Iterable[Tuple[str, Iterable[str]]]
  149. ) -> None:
  150. """
  151. Assert that the expected room IDs are in the response.
  152. Args:
  153. result: The result from the API call.
  154. rooms_and_children: An iterable of tuples where each tuple is:
  155. The expected room ID.
  156. The expected IDs of any children rooms.
  157. """
  158. result_room_ids = []
  159. result_children_ids = []
  160. for result_room in result["rooms"]:
  161. result_room_ids.append(result_room["room_id"])
  162. result_children_ids.append(
  163. [
  164. (cs["room_id"], cs["state_key"])
  165. for cs in result_room.get("children_state")
  166. ]
  167. )
  168. room_ids = []
  169. children_ids = []
  170. for room_id, children in rooms_and_children:
  171. room_ids.append(room_id)
  172. children_ids.append([(room_id, child_id) for child_id in children])
  173. # Note that order matters.
  174. self.assertEqual(result_room_ids, room_ids)
  175. self.assertEqual(result_children_ids, children_ids)
  176. def _poke_fed_invite(self, room_id: str, from_user: str) -> None:
  177. """
  178. Creates a invite (as if received over federation) for the room from the
  179. given hostname.
  180. Args:
  181. room_id: The room ID to issue an invite for.
  182. fed_hostname: The user to invite from.
  183. """
  184. # Poke an invite over federation into the database.
  185. fed_handler = self.hs.get_federation_handler()
  186. fed_hostname = UserID.from_string(from_user).domain
  187. event = make_event_from_dict(
  188. {
  189. "room_id": room_id,
  190. "event_id": "!abcd:" + fed_hostname,
  191. "type": EventTypes.Member,
  192. "sender": from_user,
  193. "state_key": self.user,
  194. "content": {"membership": Membership.INVITE},
  195. "prev_events": [],
  196. "auth_events": [],
  197. "depth": 1,
  198. "origin_server_ts": 1234,
  199. }
  200. )
  201. self.get_success(
  202. fed_handler.on_invite_request(fed_hostname, event, RoomVersions.V6)
  203. )
  204. def test_simple_space(self):
  205. """Test a simple space with a single room."""
  206. result = self.get_success(self.handler.get_space_summary(self.user, self.space))
  207. # The result should have the space and the room in it, along with a link
  208. # from space -> room.
  209. expected = [(self.space, [self.room]), (self.room, ())]
  210. self._assert_rooms(result, expected)
  211. result = self.get_success(
  212. self.handler.get_room_hierarchy(self.user, self.space)
  213. )
  214. self._assert_hierarchy(result, expected)
  215. def test_visibility(self):
  216. """A user not in a space cannot inspect it."""
  217. user2 = self.register_user("user2", "pass")
  218. token2 = self.login("user2", "pass")
  219. # The user can see the space since it is publicly joinable.
  220. result = self.get_success(self.handler.get_space_summary(user2, self.space))
  221. expected = [(self.space, [self.room]), (self.room, ())]
  222. self._assert_rooms(result, expected)
  223. result = self.get_success(self.handler.get_room_hierarchy(user2, self.space))
  224. self._assert_hierarchy(result, expected)
  225. # If the space is made invite-only, it should no longer be viewable.
  226. self.helper.send_state(
  227. self.space,
  228. event_type=EventTypes.JoinRules,
  229. body={"join_rule": JoinRules.INVITE},
  230. tok=self.token,
  231. )
  232. self.get_failure(self.handler.get_space_summary(user2, self.space), AuthError)
  233. self.get_failure(self.handler.get_room_hierarchy(user2, self.space), AuthError)
  234. # If the space is made world-readable it should return a result.
  235. self.helper.send_state(
  236. self.space,
  237. event_type=EventTypes.RoomHistoryVisibility,
  238. body={"history_visibility": HistoryVisibility.WORLD_READABLE},
  239. tok=self.token,
  240. )
  241. result = self.get_success(self.handler.get_space_summary(user2, self.space))
  242. self._assert_rooms(result, expected)
  243. result = self.get_success(self.handler.get_room_hierarchy(user2, self.space))
  244. self._assert_hierarchy(result, expected)
  245. # Make it not world-readable again and confirm it results in an error.
  246. self.helper.send_state(
  247. self.space,
  248. event_type=EventTypes.RoomHistoryVisibility,
  249. body={"history_visibility": HistoryVisibility.JOINED},
  250. tok=self.token,
  251. )
  252. self.get_failure(self.handler.get_space_summary(user2, self.space), AuthError)
  253. self.get_failure(self.handler.get_room_hierarchy(user2, self.space), AuthError)
  254. # Join the space and results should be returned.
  255. self.helper.invite(self.space, targ=user2, tok=self.token)
  256. self.helper.join(self.space, user2, tok=token2)
  257. result = self.get_success(self.handler.get_space_summary(user2, self.space))
  258. self._assert_rooms(result, expected)
  259. result = self.get_success(self.handler.get_room_hierarchy(user2, self.space))
  260. self._assert_hierarchy(result, expected)
  261. # Attempting to view an unknown room returns the same error.
  262. self.get_failure(
  263. self.handler.get_space_summary(user2, "#not-a-space:" + self.hs.hostname),
  264. AuthError,
  265. )
  266. self.get_failure(
  267. self.handler.get_room_hierarchy(user2, "#not-a-space:" + self.hs.hostname),
  268. AuthError,
  269. )
  270. def test_room_hierarchy_cache(self) -> None:
  271. """In-flight room hierarchy requests are deduplicated."""
  272. # Run two `get_room_hierarchy` calls up until they block.
  273. deferred1 = ensureDeferred(
  274. self.handler.get_room_hierarchy(self.user, self.space)
  275. )
  276. deferred2 = ensureDeferred(
  277. self.handler.get_room_hierarchy(self.user, self.space)
  278. )
  279. # Complete the two calls.
  280. result1 = self.get_success(deferred1)
  281. result2 = self.get_success(deferred2)
  282. # Both `get_room_hierarchy` calls should return the same result.
  283. expected = [(self.space, [self.room]), (self.room, ())]
  284. self._assert_hierarchy(result1, expected)
  285. self._assert_hierarchy(result2, expected)
  286. self.assertIs(result1, result2)
  287. # A subsequent `get_room_hierarchy` call should not reuse the result.
  288. result3 = self.get_success(
  289. self.handler.get_room_hierarchy(self.user, self.space)
  290. )
  291. self._assert_hierarchy(result3, expected)
  292. self.assertIsNot(result1, result3)
  293. def test_room_hierarchy_cache_sharing(self) -> None:
  294. """Room hierarchy responses for different users are not shared."""
  295. user2 = self.register_user("user2", "pass")
  296. # Make the room within the space invite-only.
  297. self.helper.send_state(
  298. self.room,
  299. event_type=EventTypes.JoinRules,
  300. body={"join_rule": JoinRules.INVITE},
  301. tok=self.token,
  302. )
  303. # Run two `get_room_hierarchy` calls for different users up until they block.
  304. deferred1 = ensureDeferred(
  305. self.handler.get_room_hierarchy(self.user, self.space)
  306. )
  307. deferred2 = ensureDeferred(self.handler.get_room_hierarchy(user2, self.space))
  308. # Complete the two calls.
  309. result1 = self.get_success(deferred1)
  310. result2 = self.get_success(deferred2)
  311. # The `get_room_hierarchy` calls should return different results.
  312. self._assert_hierarchy(result1, [(self.space, [self.room]), (self.room, ())])
  313. self._assert_hierarchy(result2, [(self.space, [self.room])])
  314. def _create_room_with_join_rule(
  315. self, join_rule: str, room_version: Optional[str] = None, **extra_content
  316. ) -> str:
  317. """Create a room with the given join rule and add it to the space."""
  318. room_id = self.helper.create_room_as(
  319. self.user,
  320. room_version=room_version,
  321. tok=self.token,
  322. extra_content={
  323. "initial_state": [
  324. {
  325. "type": EventTypes.JoinRules,
  326. "state_key": "",
  327. "content": {
  328. "join_rule": join_rule,
  329. **extra_content,
  330. },
  331. }
  332. ]
  333. },
  334. )
  335. self._add_child(self.space, room_id, self.token)
  336. return room_id
  337. def test_filtering(self):
  338. """
  339. Rooms should be properly filtered to only include rooms the user has access to.
  340. """
  341. user2 = self.register_user("user2", "pass")
  342. token2 = self.login("user2", "pass")
  343. # Create a few rooms which will have different properties.
  344. public_room = self._create_room_with_join_rule(JoinRules.PUBLIC)
  345. knock_room = self._create_room_with_join_rule(
  346. JoinRules.KNOCK, room_version=RoomVersions.V7.identifier
  347. )
  348. not_invited_room = self._create_room_with_join_rule(JoinRules.INVITE)
  349. invited_room = self._create_room_with_join_rule(JoinRules.INVITE)
  350. self.helper.invite(invited_room, targ=user2, tok=self.token)
  351. restricted_room = self._create_room_with_join_rule(
  352. JoinRules.RESTRICTED,
  353. room_version=RoomVersions.V8.identifier,
  354. allow=[],
  355. )
  356. restricted_accessible_room = self._create_room_with_join_rule(
  357. JoinRules.RESTRICTED,
  358. room_version=RoomVersions.V8.identifier,
  359. allow=[
  360. {
  361. "type": RestrictedJoinRuleTypes.ROOM_MEMBERSHIP,
  362. "room_id": self.space,
  363. "via": [self.hs.hostname],
  364. }
  365. ],
  366. )
  367. world_readable_room = self._create_room_with_join_rule(JoinRules.INVITE)
  368. self.helper.send_state(
  369. world_readable_room,
  370. event_type=EventTypes.RoomHistoryVisibility,
  371. body={"history_visibility": HistoryVisibility.WORLD_READABLE},
  372. tok=self.token,
  373. )
  374. joined_room = self._create_room_with_join_rule(JoinRules.INVITE)
  375. self.helper.invite(joined_room, targ=user2, tok=self.token)
  376. self.helper.join(joined_room, user2, tok=token2)
  377. # Join the space.
  378. self.helper.join(self.space, user2, tok=token2)
  379. result = self.get_success(self.handler.get_space_summary(user2, self.space))
  380. expected = [
  381. (
  382. self.space,
  383. [
  384. self.room,
  385. public_room,
  386. knock_room,
  387. not_invited_room,
  388. invited_room,
  389. restricted_room,
  390. restricted_accessible_room,
  391. world_readable_room,
  392. joined_room,
  393. ],
  394. ),
  395. (self.room, ()),
  396. (public_room, ()),
  397. (knock_room, ()),
  398. (invited_room, ()),
  399. (restricted_accessible_room, ()),
  400. (world_readable_room, ()),
  401. (joined_room, ()),
  402. ]
  403. self._assert_rooms(result, expected)
  404. result = self.get_success(self.handler.get_room_hierarchy(user2, self.space))
  405. self._assert_hierarchy(result, expected)
  406. def test_complex_space(self):
  407. """
  408. Create a "complex" space to see how it handles things like loops and subspaces.
  409. """
  410. # Create an inaccessible room.
  411. user2 = self.register_user("user2", "pass")
  412. token2 = self.login("user2", "pass")
  413. room2 = self.helper.create_room_as(user2, is_public=False, tok=token2)
  414. # This is a bit odd as "user" is adding a room they don't know about, but
  415. # it works for the tests.
  416. self._add_child(self.space, room2, self.token)
  417. # Create a subspace under the space with an additional room in it.
  418. subspace = self.helper.create_room_as(
  419. self.user,
  420. tok=self.token,
  421. extra_content={
  422. "creation_content": {EventContentFields.ROOM_TYPE: RoomTypes.SPACE}
  423. },
  424. )
  425. subroom = self.helper.create_room_as(self.user, tok=self.token)
  426. self._add_child(self.space, subspace, token=self.token)
  427. self._add_child(subspace, subroom, token=self.token)
  428. # Also add the two rooms from the space into this subspace (causing loops).
  429. self._add_child(subspace, self.room, token=self.token)
  430. self._add_child(subspace, room2, self.token)
  431. result = self.get_success(self.handler.get_space_summary(self.user, self.space))
  432. # The result should include each room a single time and each link.
  433. expected = [
  434. (self.space, [self.room, room2, subspace]),
  435. (self.room, ()),
  436. (subspace, [subroom, self.room, room2]),
  437. (subroom, ()),
  438. ]
  439. self._assert_rooms(result, expected)
  440. result = self.get_success(
  441. self.handler.get_room_hierarchy(self.user, self.space)
  442. )
  443. self._assert_hierarchy(result, expected)
  444. def test_pagination(self):
  445. """Test simple pagination works."""
  446. room_ids = []
  447. for i in range(1, 10):
  448. room = self.helper.create_room_as(self.user, tok=self.token)
  449. self._add_child(self.space, room, self.token, order=str(i))
  450. room_ids.append(room)
  451. # The room created initially doesn't have an order, so comes last.
  452. room_ids.append(self.room)
  453. result = self.get_success(
  454. self.handler.get_room_hierarchy(self.user, self.space, limit=7)
  455. )
  456. # The result should have the space and all of the links, plus some of the
  457. # rooms and a pagination token.
  458. expected: List[Tuple[str, Iterable[str]]] = [(self.space, room_ids)]
  459. expected += [(room_id, ()) for room_id in room_ids[:6]]
  460. self._assert_hierarchy(result, expected)
  461. self.assertIn("next_batch", result)
  462. # Check the next page.
  463. result = self.get_success(
  464. self.handler.get_room_hierarchy(
  465. self.user, self.space, limit=5, from_token=result["next_batch"]
  466. )
  467. )
  468. # The result should have the space and the room in it, along with a link
  469. # from space -> room.
  470. expected = [(room_id, ()) for room_id in room_ids[6:]]
  471. self._assert_hierarchy(result, expected)
  472. self.assertNotIn("next_batch", result)
  473. def test_invalid_pagination_token(self):
  474. """An invalid pagination token, or changing other parameters, shoudl be rejected."""
  475. room_ids = []
  476. for i in range(1, 10):
  477. room = self.helper.create_room_as(self.user, tok=self.token)
  478. self._add_child(self.space, room, self.token, order=str(i))
  479. room_ids.append(room)
  480. # The room created initially doesn't have an order, so comes last.
  481. room_ids.append(self.room)
  482. result = self.get_success(
  483. self.handler.get_room_hierarchy(self.user, self.space, limit=7)
  484. )
  485. self.assertIn("next_batch", result)
  486. # Changing the room ID, suggested-only, or max-depth causes an error.
  487. self.get_failure(
  488. self.handler.get_room_hierarchy(
  489. self.user, self.room, from_token=result["next_batch"]
  490. ),
  491. SynapseError,
  492. )
  493. self.get_failure(
  494. self.handler.get_room_hierarchy(
  495. self.user,
  496. self.space,
  497. suggested_only=True,
  498. from_token=result["next_batch"],
  499. ),
  500. SynapseError,
  501. )
  502. self.get_failure(
  503. self.handler.get_room_hierarchy(
  504. self.user, self.space, max_depth=0, from_token=result["next_batch"]
  505. ),
  506. SynapseError,
  507. )
  508. # An invalid token is ignored.
  509. self.get_failure(
  510. self.handler.get_room_hierarchy(self.user, self.space, from_token="foo"),
  511. SynapseError,
  512. )
  513. def test_max_depth(self):
  514. """Create a deep tree to test the max depth against."""
  515. spaces = [self.space]
  516. rooms = [self.room]
  517. for _ in range(5):
  518. spaces.append(
  519. self.helper.create_room_as(
  520. self.user,
  521. tok=self.token,
  522. extra_content={
  523. "creation_content": {
  524. EventContentFields.ROOM_TYPE: RoomTypes.SPACE
  525. }
  526. },
  527. )
  528. )
  529. self._add_child(spaces[-2], spaces[-1], self.token)
  530. rooms.append(self.helper.create_room_as(self.user, tok=self.token))
  531. self._add_child(spaces[-1], rooms[-1], self.token)
  532. # Test just the space itself.
  533. result = self.get_success(
  534. self.handler.get_room_hierarchy(self.user, self.space, max_depth=0)
  535. )
  536. expected: List[Tuple[str, Iterable[str]]] = [(spaces[0], [rooms[0], spaces[1]])]
  537. self._assert_hierarchy(result, expected)
  538. # A single additional layer.
  539. result = self.get_success(
  540. self.handler.get_room_hierarchy(self.user, self.space, max_depth=1)
  541. )
  542. expected += [
  543. (rooms[0], ()),
  544. (spaces[1], [rooms[1], spaces[2]]),
  545. ]
  546. self._assert_hierarchy(result, expected)
  547. # A few layers.
  548. result = self.get_success(
  549. self.handler.get_room_hierarchy(self.user, self.space, max_depth=3)
  550. )
  551. expected += [
  552. (rooms[1], ()),
  553. (spaces[2], [rooms[2], spaces[3]]),
  554. (rooms[2], ()),
  555. (spaces[3], [rooms[3], spaces[4]]),
  556. ]
  557. self._assert_hierarchy(result, expected)
  558. def test_unknown_room_version(self):
  559. """
  560. If an room with an unknown room version is encountered it should not cause
  561. the entire summary to skip.
  562. """
  563. # Poke the database and update the room version to an unknown one.
  564. self.get_success(
  565. self.hs.get_datastores().main.db_pool.simple_update(
  566. "rooms",
  567. keyvalues={"room_id": self.room},
  568. updatevalues={"room_version": "unknown-room-version"},
  569. desc="updated-room-version",
  570. )
  571. )
  572. result = self.get_success(self.handler.get_space_summary(self.user, self.space))
  573. # The result should have only the space, along with a link from space -> room.
  574. expected = [(self.space, [self.room])]
  575. self._assert_rooms(result, expected)
  576. result = self.get_success(
  577. self.handler.get_room_hierarchy(self.user, self.space)
  578. )
  579. self._assert_hierarchy(result, expected)
  580. def test_fed_complex(self):
  581. """
  582. Return data over federation and ensure that it is handled properly.
  583. """
  584. fed_hostname = self.hs.hostname + "2"
  585. subspace = "#subspace:" + fed_hostname
  586. subroom = "#subroom:" + fed_hostname
  587. # Generate some good data, and some bad data:
  588. #
  589. # * Event *back* to the root room.
  590. # * Unrelated events / rooms
  591. # * Multiple levels of events (in a not-useful order, e.g. grandchild
  592. # events before child events).
  593. # Note that these entries are brief, but should contain enough info.
  594. requested_room_entry = _RoomEntry(
  595. subspace,
  596. {
  597. "room_id": subspace,
  598. "world_readable": True,
  599. "room_type": RoomTypes.SPACE,
  600. },
  601. [
  602. {
  603. "type": EventTypes.SpaceChild,
  604. "room_id": subspace,
  605. "state_key": subroom,
  606. "content": {"via": [fed_hostname]},
  607. }
  608. ],
  609. )
  610. child_room = {
  611. "room_id": subroom,
  612. "world_readable": True,
  613. }
  614. async def summarize_remote_room(
  615. _self, room, suggested_only, max_children, exclude_rooms
  616. ):
  617. return [
  618. requested_room_entry,
  619. _RoomEntry(
  620. subroom,
  621. {
  622. "room_id": subroom,
  623. "world_readable": True,
  624. },
  625. ),
  626. ]
  627. async def summarize_remote_room_hierarchy(_self, room, suggested_only):
  628. return requested_room_entry, {subroom: child_room}, set()
  629. # Add a room to the space which is on another server.
  630. self._add_child(self.space, subspace, self.token)
  631. with mock.patch(
  632. "synapse.handlers.room_summary.RoomSummaryHandler._summarize_remote_room",
  633. new=summarize_remote_room,
  634. ):
  635. result = self.get_success(
  636. self.handler.get_space_summary(self.user, self.space)
  637. )
  638. expected = [
  639. (self.space, [self.room, subspace]),
  640. (self.room, ()),
  641. (subspace, [subroom]),
  642. (subroom, ()),
  643. ]
  644. self._assert_rooms(result, expected)
  645. with mock.patch(
  646. "synapse.handlers.room_summary.RoomSummaryHandler._summarize_remote_room_hierarchy",
  647. new=summarize_remote_room_hierarchy,
  648. ):
  649. result = self.get_success(
  650. self.handler.get_room_hierarchy(self.user, self.space)
  651. )
  652. self._assert_hierarchy(result, expected)
  653. def test_fed_filtering(self):
  654. """
  655. Rooms returned over federation should be properly filtered to only include
  656. rooms the user has access to.
  657. """
  658. fed_hostname = self.hs.hostname + "2"
  659. subspace = "#subspace:" + fed_hostname
  660. # Create a few rooms which will have different properties.
  661. public_room = "#public:" + fed_hostname
  662. knock_room = "#knock:" + fed_hostname
  663. not_invited_room = "#not_invited:" + fed_hostname
  664. invited_room = "#invited:" + fed_hostname
  665. restricted_room = "#restricted:" + fed_hostname
  666. restricted_accessible_room = "#restricted_accessible:" + fed_hostname
  667. world_readable_room = "#world_readable:" + fed_hostname
  668. joined_room = self.helper.create_room_as(self.user, tok=self.token)
  669. # Poke an invite over federation into the database.
  670. self._poke_fed_invite(invited_room, "@remote:" + fed_hostname)
  671. # Note that these entries are brief, but should contain enough info.
  672. children_rooms = (
  673. (
  674. public_room,
  675. {
  676. "room_id": public_room,
  677. "world_readable": False,
  678. "join_rules": JoinRules.PUBLIC,
  679. },
  680. ),
  681. (
  682. knock_room,
  683. {
  684. "room_id": knock_room,
  685. "world_readable": False,
  686. "join_rules": JoinRules.KNOCK,
  687. },
  688. ),
  689. (
  690. not_invited_room,
  691. {
  692. "room_id": not_invited_room,
  693. "world_readable": False,
  694. "join_rules": JoinRules.INVITE,
  695. },
  696. ),
  697. (
  698. invited_room,
  699. {
  700. "room_id": invited_room,
  701. "world_readable": False,
  702. "join_rules": JoinRules.INVITE,
  703. },
  704. ),
  705. (
  706. restricted_room,
  707. {
  708. "room_id": restricted_room,
  709. "world_readable": False,
  710. "join_rules": JoinRules.RESTRICTED,
  711. "allowed_spaces": [],
  712. },
  713. ),
  714. (
  715. restricted_accessible_room,
  716. {
  717. "room_id": restricted_accessible_room,
  718. "world_readable": False,
  719. "join_rules": JoinRules.RESTRICTED,
  720. "allowed_spaces": [self.room],
  721. },
  722. ),
  723. (
  724. world_readable_room,
  725. {
  726. "room_id": world_readable_room,
  727. "world_readable": True,
  728. "join_rules": JoinRules.INVITE,
  729. },
  730. ),
  731. (
  732. joined_room,
  733. {
  734. "room_id": joined_room,
  735. "world_readable": False,
  736. "join_rules": JoinRules.INVITE,
  737. },
  738. ),
  739. )
  740. subspace_room_entry = _RoomEntry(
  741. subspace,
  742. {
  743. "room_id": subspace,
  744. "world_readable": True,
  745. },
  746. # Place each room in the sub-space.
  747. [
  748. {
  749. "type": EventTypes.SpaceChild,
  750. "room_id": subspace,
  751. "state_key": room_id,
  752. "content": {"via": [fed_hostname]},
  753. }
  754. for room_id, _ in children_rooms
  755. ],
  756. )
  757. async def summarize_remote_room(
  758. _self, room, suggested_only, max_children, exclude_rooms
  759. ):
  760. return [subspace_room_entry] + [
  761. # A copy is made of the room data since the allowed_spaces key
  762. # is removed.
  763. _RoomEntry(child_room[0], dict(child_room[1]))
  764. for child_room in children_rooms
  765. ]
  766. async def summarize_remote_room_hierarchy(_self, room, suggested_only):
  767. return subspace_room_entry, dict(children_rooms), set()
  768. # Add a room to the space which is on another server.
  769. self._add_child(self.space, subspace, self.token)
  770. with mock.patch(
  771. "synapse.handlers.room_summary.RoomSummaryHandler._summarize_remote_room",
  772. new=summarize_remote_room,
  773. ):
  774. result = self.get_success(
  775. self.handler.get_space_summary(self.user, self.space)
  776. )
  777. expected = [
  778. (self.space, [self.room, subspace]),
  779. (self.room, ()),
  780. (
  781. subspace,
  782. [
  783. public_room,
  784. knock_room,
  785. not_invited_room,
  786. invited_room,
  787. restricted_room,
  788. restricted_accessible_room,
  789. world_readable_room,
  790. joined_room,
  791. ],
  792. ),
  793. (public_room, ()),
  794. (knock_room, ()),
  795. (invited_room, ()),
  796. (restricted_accessible_room, ()),
  797. (world_readable_room, ()),
  798. (joined_room, ()),
  799. ]
  800. self._assert_rooms(result, expected)
  801. with mock.patch(
  802. "synapse.handlers.room_summary.RoomSummaryHandler._summarize_remote_room_hierarchy",
  803. new=summarize_remote_room_hierarchy,
  804. ):
  805. result = self.get_success(
  806. self.handler.get_room_hierarchy(self.user, self.space)
  807. )
  808. self._assert_hierarchy(result, expected)
  809. def test_fed_invited(self):
  810. """
  811. A room which the user was invited to should be included in the response.
  812. This differs from test_fed_filtering in that the room itself is being
  813. queried over federation, instead of it being included as a sub-room of
  814. a space in the response.
  815. """
  816. fed_hostname = self.hs.hostname + "2"
  817. fed_room = "#subroom:" + fed_hostname
  818. # Poke an invite over federation into the database.
  819. self._poke_fed_invite(fed_room, "@remote:" + fed_hostname)
  820. fed_room_entry = _RoomEntry(
  821. fed_room,
  822. {
  823. "room_id": fed_room,
  824. "world_readable": False,
  825. "join_rules": JoinRules.INVITE,
  826. },
  827. )
  828. async def summarize_remote_room(
  829. _self, room, suggested_only, max_children, exclude_rooms
  830. ):
  831. return [fed_room_entry]
  832. async def summarize_remote_room_hierarchy(_self, room, suggested_only):
  833. return fed_room_entry, {}, set()
  834. # Add a room to the space which is on another server.
  835. self._add_child(self.space, fed_room, self.token)
  836. with mock.patch(
  837. "synapse.handlers.room_summary.RoomSummaryHandler._summarize_remote_room",
  838. new=summarize_remote_room,
  839. ):
  840. result = self.get_success(
  841. self.handler.get_space_summary(self.user, self.space)
  842. )
  843. expected = [
  844. (self.space, [self.room, fed_room]),
  845. (self.room, ()),
  846. (fed_room, ()),
  847. ]
  848. self._assert_rooms(result, expected)
  849. with mock.patch(
  850. "synapse.handlers.room_summary.RoomSummaryHandler._summarize_remote_room_hierarchy",
  851. new=summarize_remote_room_hierarchy,
  852. ):
  853. result = self.get_success(
  854. self.handler.get_room_hierarchy(self.user, self.space)
  855. )
  856. self._assert_hierarchy(result, expected)
  857. class RoomSummaryTestCase(unittest.HomeserverTestCase):
  858. servlets = [
  859. admin.register_servlets_for_client_rest_resource,
  860. room.register_servlets,
  861. login.register_servlets,
  862. ]
  863. def prepare(self, reactor, clock, hs: HomeServer):
  864. self.hs = hs
  865. self.handler = self.hs.get_room_summary_handler()
  866. # Create a user.
  867. self.user = self.register_user("user", "pass")
  868. self.token = self.login("user", "pass")
  869. # Create a simple room.
  870. self.room = self.helper.create_room_as(self.user, tok=self.token)
  871. self.helper.send_state(
  872. self.room,
  873. event_type=EventTypes.JoinRules,
  874. body={"join_rule": JoinRules.INVITE},
  875. tok=self.token,
  876. )
  877. def test_own_room(self):
  878. """Test a simple room created by the requester."""
  879. result = self.get_success(self.handler.get_room_summary(self.user, self.room))
  880. self.assertEqual(result.get("room_id"), self.room)
  881. def test_visibility(self):
  882. """A user not in a private room cannot get its summary."""
  883. user2 = self.register_user("user2", "pass")
  884. token2 = self.login("user2", "pass")
  885. # The user cannot see the room.
  886. self.get_failure(self.handler.get_room_summary(user2, self.room), NotFoundError)
  887. # If the room is made world-readable it should return a result.
  888. self.helper.send_state(
  889. self.room,
  890. event_type=EventTypes.RoomHistoryVisibility,
  891. body={"history_visibility": HistoryVisibility.WORLD_READABLE},
  892. tok=self.token,
  893. )
  894. result = self.get_success(self.handler.get_room_summary(user2, self.room))
  895. self.assertEqual(result.get("room_id"), self.room)
  896. # Make it not world-readable again and confirm it results in an error.
  897. self.helper.send_state(
  898. self.room,
  899. event_type=EventTypes.RoomHistoryVisibility,
  900. body={"history_visibility": HistoryVisibility.JOINED},
  901. tok=self.token,
  902. )
  903. self.get_failure(self.handler.get_room_summary(user2, self.room), NotFoundError)
  904. # If the room is made public it should return a result.
  905. self.helper.send_state(
  906. self.room,
  907. event_type=EventTypes.JoinRules,
  908. body={"join_rule": JoinRules.PUBLIC},
  909. tok=self.token,
  910. )
  911. result = self.get_success(self.handler.get_room_summary(user2, self.room))
  912. self.assertEqual(result.get("room_id"), self.room)
  913. # Join the space, make it invite-only again and results should be returned.
  914. self.helper.join(self.room, user2, tok=token2)
  915. self.helper.send_state(
  916. self.room,
  917. event_type=EventTypes.JoinRules,
  918. body={"join_rule": JoinRules.INVITE},
  919. tok=self.token,
  920. )
  921. result = self.get_success(self.handler.get_room_summary(user2, self.room))
  922. self.assertEqual(result.get("room_id"), self.room)