You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

582 lines
23 KiB

  1. # Copyright 2015 OpenMarket Ltd
  2. # Copyright 2017 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import (
  17. TYPE_CHECKING,
  18. Any,
  19. Collection,
  20. Dict,
  21. List,
  22. Mapping,
  23. Optional,
  24. Sequence,
  25. Set,
  26. Tuple,
  27. Union,
  28. )
  29. from prometheus_client import Counter
  30. from synapse.api.constants import (
  31. MAIN_TIMELINE,
  32. EventContentFields,
  33. EventTypes,
  34. Membership,
  35. RelationTypes,
  36. )
  37. from synapse.api.room_versions import PushRuleRoomFlag
  38. from synapse.event_auth import auth_types_for_event, get_user_power_level
  39. from synapse.events import EventBase, relation_from_event
  40. from synapse.events.snapshot import EventContext
  41. from synapse.state import POWER_KEY
  42. from synapse.storage.databases.main.roommember import EventIdMembership
  43. from synapse.synapse_rust.push import FilteredPushRules, PushRuleEvaluator
  44. from synapse.types import JsonValue
  45. from synapse.types.state import StateFilter
  46. from synapse.util.caches import register_cache
  47. from synapse.util.metrics import measure_func
  48. from synapse.visibility import filter_event_for_clients_with_state
  49. if TYPE_CHECKING:
  50. from synapse.server import HomeServer
  51. logger = logging.getLogger(__name__)
  52. push_rules_invalidation_counter = Counter(
  53. "synapse_push_bulk_push_rule_evaluator_push_rules_invalidation_counter", ""
  54. )
  55. push_rules_state_size_counter = Counter(
  56. "synapse_push_bulk_push_rule_evaluator_push_rules_state_size_counter", ""
  57. )
  58. STATE_EVENT_TYPES_TO_MARK_UNREAD = {
  59. EventTypes.Topic,
  60. EventTypes.Name,
  61. EventTypes.RoomAvatar,
  62. EventTypes.Tombstone,
  63. }
  64. SENTINEL = object()
  65. def _should_count_as_unread(event: EventBase, context: EventContext) -> bool:
  66. # Exclude rejected and soft-failed events.
  67. if context.rejected or event.internal_metadata.is_soft_failed():
  68. return False
  69. # Exclude notices.
  70. if (
  71. not event.is_state()
  72. and event.type == EventTypes.Message
  73. and event.content.get("msgtype") == "m.notice"
  74. ):
  75. return False
  76. # Exclude edits.
  77. relates_to = relation_from_event(event)
  78. if relates_to and relates_to.rel_type == RelationTypes.REPLACE:
  79. return False
  80. # Mark events that have a non-empty string body as unread.
  81. body = event.content.get("body")
  82. if isinstance(body, str) and body:
  83. return True
  84. # Mark some state events as unread.
  85. if event.is_state() and event.type in STATE_EVENT_TYPES_TO_MARK_UNREAD:
  86. return True
  87. # Mark encrypted events as unread.
  88. if not event.is_state() and event.type == EventTypes.Encrypted:
  89. return True
  90. return False
  91. class BulkPushRuleEvaluator:
  92. """Calculates the outcome of push rules for an event for all users in the
  93. room at once.
  94. """
  95. def __init__(self, hs: "HomeServer"):
  96. self.hs = hs
  97. self.store = hs.get_datastores().main
  98. self.clock = hs.get_clock()
  99. self._event_auth_handler = hs.get_event_auth_handler()
  100. self.should_calculate_push_rules = self.hs.config.push.enable_push
  101. self._related_event_match_enabled = self.hs.config.experimental.msc3664_enabled
  102. self._intentional_mentions_enabled = (
  103. self.hs.config.experimental.msc3952_intentional_mentions
  104. )
  105. self.room_push_rule_cache_metrics = register_cache(
  106. "cache",
  107. "room_push_rule_cache",
  108. cache=[], # Meaningless size, as this isn't a cache that stores values,
  109. resizable=False,
  110. )
  111. async def _get_rules_for_event(
  112. self,
  113. event: EventBase,
  114. ) -> Dict[str, FilteredPushRules]:
  115. """Get the push rules for all users who may need to be notified about
  116. the event.
  117. Note: this does not check if the user is allowed to see the event.
  118. Returns:
  119. Mapping of user ID to their push rules.
  120. """
  121. # If this is a membership event, only calculate push rules for the target.
  122. # While it's possible for users to configure push rules to respond to such an
  123. # event, in practise nobody does this. At the cost of violating the spec a
  124. # little, we can skip fetching a huge number of push rules in large rooms.
  125. # This helps make joins and leaves faster.
  126. if event.type == EventTypes.Member:
  127. local_users: Sequence[str] = []
  128. # We never notify a user about their own actions. This is enforced in
  129. # `_action_for_event_by_user` in the loop over `rules_by_user`, but we
  130. # do the same check here to avoid unnecessary DB queries.
  131. if event.sender != event.state_key and self.hs.is_mine_id(event.state_key):
  132. # Check the target is in the room, to avoid notifying them of
  133. # e.g. a pre-emptive ban.
  134. target_already_in_room = await self.store.check_local_user_in_room(
  135. event.state_key, event.room_id
  136. )
  137. if target_already_in_room:
  138. local_users = [event.state_key]
  139. else:
  140. # We get the users who may need to be notified by first fetching the
  141. # local users currently in the room, finding those that have push rules,
  142. # and *then* checking which users are actually allowed to see the event.
  143. #
  144. # The alternative is to first fetch all users that were joined at the
  145. # event, but that requires fetching the full state at the event, which
  146. # may be expensive for large rooms with few local users.
  147. local_users = await self.store.get_local_users_in_room(event.room_id)
  148. # Filter out appservice users.
  149. local_users = [
  150. u
  151. for u in local_users
  152. if not self.store.get_if_app_services_interested_in_user(u)
  153. ]
  154. # if this event is an invite event, we may need to run rules for the user
  155. # who's been invited, otherwise they won't get told they've been invited
  156. if event.type == EventTypes.Member and event.membership == Membership.INVITE:
  157. invited = event.state_key
  158. if invited and self.hs.is_mine_id(invited) and invited not in local_users:
  159. local_users.append(invited)
  160. if not local_users:
  161. return {}
  162. rules_by_user = await self.store.bulk_get_push_rules(local_users)
  163. logger.debug("Users in room: %s", local_users)
  164. if logger.isEnabledFor(logging.DEBUG):
  165. logger.debug(
  166. "Returning push rules for %r %r",
  167. event.room_id,
  168. list(rules_by_user.keys()),
  169. )
  170. return rules_by_user
  171. async def _get_power_levels_and_sender_level(
  172. self,
  173. event: EventBase,
  174. context: EventContext,
  175. event_id_to_event: Mapping[str, EventBase],
  176. ) -> Tuple[dict, Optional[int]]:
  177. """
  178. Given an event and an event context, get the power level event relevant to the event
  179. and the power level of the sender of the event.
  180. Args:
  181. event: event to check
  182. context: context of event to check
  183. event_id_to_event: a mapping of event_id to event for a set of events being
  184. batch persisted. This is needed as the sought-after power level event may
  185. be in this batch rather than the DB
  186. """
  187. # There are no power levels and sender levels possible to get from outlier
  188. if event.internal_metadata.is_outlier():
  189. return {}, None
  190. event_types = auth_types_for_event(event.room_version, event)
  191. prev_state_ids = await context.get_prev_state_ids(
  192. StateFilter.from_types(event_types)
  193. )
  194. pl_event_id = prev_state_ids.get(POWER_KEY)
  195. # fastpath: if there's a power level event, that's all we need, and
  196. # not having a power level event is an extreme edge case
  197. if pl_event_id:
  198. # Get the power level event from the batch, or fall back to the database.
  199. pl_event = event_id_to_event.get(pl_event_id)
  200. if pl_event:
  201. auth_events = {POWER_KEY: pl_event}
  202. else:
  203. auth_events = {POWER_KEY: await self.store.get_event(pl_event_id)}
  204. else:
  205. auth_events_ids = self._event_auth_handler.compute_auth_events(
  206. event, prev_state_ids, for_verification=False
  207. )
  208. auth_events_dict = await self.store.get_events(auth_events_ids)
  209. # Some needed auth events might be in the batch, combine them with those
  210. # fetched from the database.
  211. for auth_event_id in auth_events_ids:
  212. auth_event = event_id_to_event.get(auth_event_id)
  213. if auth_event:
  214. auth_events_dict[auth_event_id] = auth_event
  215. auth_events = {(e.type, e.state_key): e for e in auth_events_dict.values()}
  216. sender_level = get_user_power_level(event.sender, auth_events)
  217. pl_event = auth_events.get(POWER_KEY)
  218. return pl_event.content if pl_event else {}, sender_level
  219. async def _related_events(
  220. self, event: EventBase
  221. ) -> Dict[str, Dict[str, JsonValue]]:
  222. """Fetches the related events for 'event'. Sets the im.vector.is_falling_back key if the event is from a fallback relation
  223. Returns:
  224. Mapping of relation type to flattened events.
  225. """
  226. related_events: Dict[str, Dict[str, JsonValue]] = {}
  227. if self._related_event_match_enabled:
  228. related_event_id = event.content.get("m.relates_to", {}).get("event_id")
  229. relation_type = event.content.get("m.relates_to", {}).get("rel_type")
  230. if related_event_id is not None and relation_type is not None:
  231. related_event = await self.store.get_event(
  232. related_event_id, allow_none=True
  233. )
  234. if related_event is not None:
  235. related_events[relation_type] = _flatten_dict(
  236. related_event,
  237. msc3783_escape_event_match_key=self.hs.config.experimental.msc3783_escape_event_match_key,
  238. )
  239. reply_event_id = (
  240. event.content.get("m.relates_to", {})
  241. .get("m.in_reply_to", {})
  242. .get("event_id")
  243. )
  244. # convert replies to pseudo relations
  245. if reply_event_id is not None:
  246. related_event = await self.store.get_event(
  247. reply_event_id, allow_none=True
  248. )
  249. if related_event is not None:
  250. related_events["m.in_reply_to"] = _flatten_dict(
  251. related_event,
  252. msc3783_escape_event_match_key=self.hs.config.experimental.msc3783_escape_event_match_key,
  253. )
  254. # indicate that this is from a fallback relation.
  255. if relation_type == "m.thread" and event.content.get(
  256. "m.relates_to", {}
  257. ).get("is_falling_back", False):
  258. related_events["m.in_reply_to"][
  259. "im.vector.is_falling_back"
  260. ] = ""
  261. return related_events
  262. async def action_for_events_by_user(
  263. self, events_and_context: List[Tuple[EventBase, EventContext]]
  264. ) -> None:
  265. """Given a list of events and their associated contexts, evaluate the push rules
  266. for each event, check if the message should increment the unread count, and
  267. insert the results into the event_push_actions_staging table.
  268. """
  269. if not self.should_calculate_push_rules:
  270. return
  271. # For batched events the power level events may not have been persisted yet,
  272. # so we pass in the batched events. Thus if the event cannot be found in the
  273. # database we can check in the batch.
  274. event_id_to_event = {e.event_id: e for e, _ in events_and_context}
  275. for event, context in events_and_context:
  276. await self._action_for_event_by_user(event, context, event_id_to_event)
  277. @measure_func("action_for_event_by_user")
  278. async def _action_for_event_by_user(
  279. self,
  280. event: EventBase,
  281. context: EventContext,
  282. event_id_to_event: Mapping[str, EventBase],
  283. ) -> None:
  284. if (
  285. not event.internal_metadata.is_notifiable()
  286. or event.internal_metadata.is_historical()
  287. ):
  288. # Push rules for events that aren't notifiable can't be processed by this and
  289. # we want to skip push notification actions for historical messages
  290. # because we don't want to notify people about old history back in time.
  291. # The historical messages also do not have the proper `context.current_state_ids`
  292. # and `state_groups` because they have `prev_events` that aren't persisted yet
  293. # (historical messages persisted in reverse-chronological order).
  294. return
  295. # Disable counting as unread unless the experimental configuration is
  296. # enabled, as it can cause additional (unwanted) rows to be added to the
  297. # event_push_actions table.
  298. count_as_unread = False
  299. if self.hs.config.experimental.msc2654_enabled:
  300. count_as_unread = _should_count_as_unread(event, context)
  301. rules_by_user = await self._get_rules_for_event(event)
  302. actions_by_user: Dict[str, Collection[Union[Mapping, str]]] = {}
  303. room_member_count = await self.store.get_number_joined_users_in_room(
  304. event.room_id
  305. )
  306. (
  307. power_levels,
  308. sender_power_level,
  309. ) = await self._get_power_levels_and_sender_level(
  310. event, context, event_id_to_event
  311. )
  312. # Find the event's thread ID.
  313. relation = relation_from_event(event)
  314. # If the event does not have a relation, then it cannot have a thread ID.
  315. thread_id = MAIN_TIMELINE
  316. if relation:
  317. # Recursively attempt to find the thread this event relates to.
  318. if relation.rel_type == RelationTypes.THREAD:
  319. thread_id = relation.parent_id
  320. else:
  321. # Since the event has not yet been persisted we check whether
  322. # the parent is part of a thread.
  323. thread_id = await self.store.get_thread_id(relation.parent_id)
  324. related_events = await self._related_events(event)
  325. # It's possible that old room versions have non-integer power levels (floats or
  326. # strings; even the occasional `null`). For old rooms, we interpret these as if
  327. # they were integers. Do this here for the `@room` power level threshold.
  328. # Note that this is done automatically for the sender's power level by
  329. # _get_power_levels_and_sender_level in its call to get_user_power_level
  330. # (even for room V10.)
  331. notification_levels = power_levels.get("notifications", {})
  332. if not event.room_version.msc3667_int_only_power_levels:
  333. keys = list(notification_levels.keys())
  334. for key in keys:
  335. level = notification_levels.get(key, SENTINEL)
  336. if level is not SENTINEL and type(level) is not int:
  337. try:
  338. notification_levels[key] = int(level)
  339. except (TypeError, ValueError):
  340. del notification_levels[key]
  341. # Pull out any user and room mentions.
  342. mentions = event.content.get(EventContentFields.MSC3952_MENTIONS)
  343. has_mentions = self._intentional_mentions_enabled and isinstance(mentions, dict)
  344. user_mentions: Set[str] = set()
  345. if has_mentions:
  346. # mypy seems to have lost the type even though it must be a dict here.
  347. assert isinstance(mentions, dict)
  348. # Remove out any non-string items and convert to a set.
  349. user_mentions_raw = mentions.get("user_ids")
  350. if isinstance(user_mentions_raw, list):
  351. user_mentions = set(
  352. filter(lambda item: isinstance(item, str), user_mentions_raw)
  353. )
  354. evaluator = PushRuleEvaluator(
  355. _flatten_dict(
  356. event,
  357. msc3783_escape_event_match_key=self.hs.config.experimental.msc3783_escape_event_match_key,
  358. ),
  359. has_mentions,
  360. user_mentions,
  361. room_member_count,
  362. sender_power_level,
  363. notification_levels,
  364. related_events,
  365. self._related_event_match_enabled,
  366. event.room_version.msc3931_push_features,
  367. self.hs.config.experimental.msc1767_enabled, # MSC3931 flag
  368. self.hs.config.experimental.msc3758_exact_event_match,
  369. self.hs.config.experimental.msc3966_exact_event_property_contains,
  370. )
  371. users = rules_by_user.keys()
  372. profiles = await self.store.get_subset_users_in_room_with_profiles(
  373. event.room_id, users
  374. )
  375. for uid, rules in rules_by_user.items():
  376. if event.sender == uid:
  377. continue
  378. display_name = None
  379. profile = profiles.get(uid)
  380. if profile:
  381. display_name = profile.display_name
  382. if not display_name:
  383. # Handle the case where we are pushing a membership event to
  384. # that user, as they might not be already joined.
  385. if event.type == EventTypes.Member and event.state_key == uid:
  386. display_name = event.content.get("displayname", None)
  387. if not isinstance(display_name, str):
  388. display_name = None
  389. if count_as_unread:
  390. # Add an element for the current user if the event needs to be marked as
  391. # unread, so that add_push_actions_to_staging iterates over it.
  392. # If the event shouldn't be marked as unread but should notify the
  393. # current user, it'll be added to the dict later.
  394. actions_by_user[uid] = []
  395. actions = evaluator.run(rules, uid, display_name)
  396. if "notify" in actions:
  397. # Push rules say we should notify the user of this event
  398. actions_by_user[uid] = actions
  399. # If there aren't any actions then we can skip the rest of the
  400. # processing.
  401. if not actions_by_user:
  402. return
  403. # This is a check for the case where user joins a room without being
  404. # allowed to see history, and then the server receives a delayed event
  405. # from before the user joined, which they should not be pushed for
  406. #
  407. # We do this *after* calculating the push actions as a) its unlikely
  408. # that we'll filter anyone out and b) for large rooms its likely that
  409. # most users will have push disabled and so the set of users to check is
  410. # much smaller.
  411. uids_with_visibility = await filter_event_for_clients_with_state(
  412. self.store, actions_by_user.keys(), event, context
  413. )
  414. for user_id in set(actions_by_user).difference(uids_with_visibility):
  415. actions_by_user.pop(user_id, None)
  416. # Mark in the DB staging area the push actions for users who should be
  417. # notified for this event. (This will then get handled when we persist
  418. # the event)
  419. await self.store.add_push_actions_to_staging(
  420. event.event_id,
  421. actions_by_user,
  422. count_as_unread,
  423. thread_id,
  424. )
  425. MemberMap = Dict[str, Optional[EventIdMembership]]
  426. Rule = Dict[str, dict]
  427. RulesByUser = Dict[str, List[Rule]]
  428. StateGroup = Union[object, int]
  429. def _is_simple_value(value: Any) -> bool:
  430. return isinstance(value, (bool, str)) or type(value) is int or value is None
  431. def _flatten_dict(
  432. d: Union[EventBase, Mapping[str, Any]],
  433. prefix: Optional[List[str]] = None,
  434. result: Optional[Dict[str, JsonValue]] = None,
  435. *,
  436. msc3783_escape_event_match_key: bool = False,
  437. ) -> Dict[str, JsonValue]:
  438. """
  439. Given a JSON dictionary (or event) which might contain sub dictionaries,
  440. flatten it into a single layer dictionary by combining the keys & sub-keys.
  441. String, integer, boolean, null or lists of those values are kept. All others are dropped.
  442. Transforms:
  443. {"foo": {"bar": "test"}}
  444. To:
  445. {"foo.bar": "test"}
  446. Args:
  447. d: The event or content to continue flattening.
  448. prefix: The key prefix (from outer dictionaries).
  449. result: The result to mutate.
  450. Returns:
  451. The resulting dictionary.
  452. """
  453. if prefix is None:
  454. prefix = []
  455. if result is None:
  456. result = {}
  457. for key, value in d.items():
  458. if msc3783_escape_event_match_key:
  459. # Escape periods in the key with a backslash (and backslashes with an
  460. # extra backslash). This is since a period is used as a separator between
  461. # nested fields.
  462. key = key.replace("\\", "\\\\").replace(".", "\\.")
  463. if _is_simple_value(value):
  464. result[".".join(prefix + [key])] = value
  465. elif isinstance(value, (list, tuple)):
  466. result[".".join(prefix + [key])] = [v for v in value if _is_simple_value(v)]
  467. elif isinstance(value, Mapping):
  468. # do not set `room_version` due to recursion considerations below
  469. _flatten_dict(
  470. value,
  471. prefix=(prefix + [key]),
  472. result=result,
  473. msc3783_escape_event_match_key=msc3783_escape_event_match_key,
  474. )
  475. # `room_version` should only ever be set when looking at the top level of an event
  476. if (
  477. isinstance(d, EventBase)
  478. and PushRuleRoomFlag.EXTENSIBLE_EVENTS in d.room_version.msc3931_push_features
  479. ):
  480. # Room supports extensible events: replace `content.body` with the plain text
  481. # representation from `m.markup`, as per MSC1767.
  482. markup = d.get("content").get("m.markup")
  483. if d.room_version.identifier.startswith("org.matrix.msc1767."):
  484. markup = d.get("content").get("org.matrix.msc1767.markup")
  485. if markup is not None and isinstance(markup, list):
  486. text = ""
  487. for rep in markup:
  488. if not isinstance(rep, dict):
  489. # invalid markup - skip all processing
  490. break
  491. if rep.get("mimetype", "text/plain") == "text/plain":
  492. rep_text = rep.get("body")
  493. if rep_text is not None and isinstance(rep_text, str):
  494. text = rep_text.lower()
  495. break
  496. result["content.body"] = text
  497. return result