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.
 
 
 
 
 
 

362 lines
12 KiB

  1. # Copyright 2015, 2016 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. import re
  17. from typing import (
  18. Any,
  19. Dict,
  20. List,
  21. Mapping,
  22. Optional,
  23. Pattern,
  24. Sequence,
  25. Set,
  26. Tuple,
  27. Union,
  28. )
  29. from matrix_common.regex import glob_to_regex, to_word_pattern
  30. from synapse.events import EventBase
  31. from synapse.types import UserID
  32. from synapse.util.caches.lrucache import LruCache
  33. logger = logging.getLogger(__name__)
  34. GLOB_REGEX = re.compile(r"\\\[(\\\!|)(.*)\\\]")
  35. IS_GLOB = re.compile(r"[\?\*\[\]]")
  36. INEQUALITY_EXPR = re.compile("^([=<>]*)([0-9]*)$")
  37. def _room_member_count(condition: Mapping[str, Any], room_member_count: int) -> bool:
  38. return _test_ineq_condition(condition, room_member_count)
  39. def _sender_notification_permission(
  40. condition: Mapping[str, Any],
  41. sender_power_level: Optional[int],
  42. power_levels: Dict[str, Union[int, Dict[str, int]]],
  43. ) -> bool:
  44. if sender_power_level is None:
  45. return False
  46. notif_level_key = condition.get("key")
  47. if notif_level_key is None:
  48. return False
  49. notif_levels = power_levels.get("notifications", {})
  50. assert isinstance(notif_levels, dict)
  51. room_notif_level = notif_levels.get(notif_level_key, 50)
  52. return sender_power_level >= room_notif_level
  53. def _test_ineq_condition(condition: Mapping[str, Any], number: int) -> bool:
  54. if "is" not in condition:
  55. return False
  56. m = INEQUALITY_EXPR.match(condition["is"])
  57. if not m:
  58. return False
  59. ineq = m.group(1)
  60. rhs = m.group(2)
  61. if not rhs.isdigit():
  62. return False
  63. rhs_int = int(rhs)
  64. if ineq == "" or ineq == "==":
  65. return number == rhs_int
  66. elif ineq == "<":
  67. return number < rhs_int
  68. elif ineq == ">":
  69. return number > rhs_int
  70. elif ineq == ">=":
  71. return number >= rhs_int
  72. elif ineq == "<=":
  73. return number <= rhs_int
  74. else:
  75. return False
  76. def tweaks_for_actions(actions: List[Union[str, Dict]]) -> Dict[str, Any]:
  77. """
  78. Converts a list of actions into a `tweaks` dict (which can then be passed to
  79. the push gateway).
  80. This function ignores all actions other than `set_tweak` actions, and treats
  81. absent `value`s as `True`, which agrees with the only spec-defined treatment
  82. of absent `value`s (namely, for `highlight` tweaks).
  83. Args:
  84. actions: list of actions
  85. e.g. [
  86. {"set_tweak": "a", "value": "AAA"},
  87. {"set_tweak": "b", "value": "BBB"},
  88. {"set_tweak": "highlight"},
  89. "notify"
  90. ]
  91. Returns:
  92. dictionary of tweaks for those actions
  93. e.g. {"a": "AAA", "b": "BBB", "highlight": True}
  94. """
  95. tweaks = {}
  96. for a in actions:
  97. if not isinstance(a, dict):
  98. continue
  99. if "set_tweak" in a:
  100. # value is allowed to be absent in which case the value assumed
  101. # should be True.
  102. tweaks[a["set_tweak"]] = a.get("value", True)
  103. return tweaks
  104. class PushRuleEvaluatorForEvent:
  105. def __init__(
  106. self,
  107. event: EventBase,
  108. room_member_count: int,
  109. sender_power_level: Optional[int],
  110. power_levels: Dict[str, Union[int, Dict[str, int]]],
  111. relations: Dict[str, Set[Tuple[str, str]]],
  112. relations_match_enabled: bool,
  113. ):
  114. self._event = event
  115. self._room_member_count = room_member_count
  116. self._sender_power_level = sender_power_level
  117. self._power_levels = power_levels
  118. self._relations = relations
  119. self._relations_match_enabled = relations_match_enabled
  120. # Maps strings of e.g. 'content.body' -> event["content"]["body"]
  121. self._value_cache = _flatten_dict(event)
  122. # Maps cache keys to final values.
  123. self._condition_cache: Dict[str, bool] = {}
  124. def check_conditions(
  125. self, conditions: Sequence[Mapping], uid: str, display_name: Optional[str]
  126. ) -> bool:
  127. """
  128. Returns true if a user's conditions/user ID/display name match the event.
  129. Args:
  130. conditions: The user's conditions to match.
  131. uid: The user's MXID.
  132. display_name: The display name.
  133. Returns:
  134. True if all conditions match the event, False otherwise.
  135. """
  136. for cond in conditions:
  137. _cache_key = cond.get("_cache_key", None)
  138. if _cache_key:
  139. res = self._condition_cache.get(_cache_key, None)
  140. if res is False:
  141. return False
  142. elif res is True:
  143. continue
  144. res = self.matches(cond, uid, display_name)
  145. if _cache_key:
  146. self._condition_cache[_cache_key] = bool(res)
  147. if not res:
  148. return False
  149. return True
  150. def matches(
  151. self, condition: Mapping[str, Any], user_id: str, display_name: Optional[str]
  152. ) -> bool:
  153. """
  154. Returns true if a user's condition/user ID/display name match the event.
  155. Args:
  156. condition: The user's condition to match.
  157. uid: The user's MXID.
  158. display_name: The display name, or None if there is not one.
  159. Returns:
  160. True if the condition matches the event, False otherwise.
  161. """
  162. if condition["kind"] == "event_match":
  163. return self._event_match(condition, user_id)
  164. elif condition["kind"] == "contains_display_name":
  165. return self._contains_display_name(display_name)
  166. elif condition["kind"] == "room_member_count":
  167. return _room_member_count(condition, self._room_member_count)
  168. elif condition["kind"] == "sender_notification_permission":
  169. return _sender_notification_permission(
  170. condition, self._sender_power_level, self._power_levels
  171. )
  172. elif (
  173. condition["kind"] == "org.matrix.msc3772.relation_match"
  174. and self._relations_match_enabled
  175. ):
  176. return self._relation_match(condition, user_id)
  177. else:
  178. # XXX This looks incorrect -- we have reached an unknown condition
  179. # kind and are unconditionally returning that it matches. Note
  180. # that it seems possible to provide a condition to the /pushrules
  181. # endpoint with an unknown kind, see _rule_tuple_from_request_object.
  182. return True
  183. def _event_match(self, condition: Mapping, user_id: str) -> bool:
  184. """
  185. Check an "event_match" push rule condition.
  186. Args:
  187. condition: The "event_match" push rule condition to match.
  188. user_id: The user's MXID.
  189. Returns:
  190. True if the condition matches the event, False otherwise.
  191. """
  192. pattern = condition.get("pattern", None)
  193. if not pattern:
  194. pattern_type = condition.get("pattern_type", None)
  195. if pattern_type == "user_id":
  196. pattern = user_id
  197. elif pattern_type == "user_localpart":
  198. pattern = UserID.from_string(user_id).localpart
  199. if not pattern:
  200. logger.warning("event_match condition with no pattern")
  201. return False
  202. # XXX: optimisation: cache our pattern regexps
  203. if condition["key"] == "content.body":
  204. body = self._event.content.get("body", None)
  205. if not body or not isinstance(body, str):
  206. return False
  207. return _glob_matches(pattern, body, word_boundary=True)
  208. else:
  209. haystack = self._value_cache.get(condition["key"], None)
  210. if haystack is None:
  211. return False
  212. return _glob_matches(pattern, haystack)
  213. def _contains_display_name(self, display_name: Optional[str]) -> bool:
  214. """
  215. Check an "event_match" push rule condition.
  216. Args:
  217. display_name: The display name, or None if there is not one.
  218. Returns:
  219. True if the display name is found in the event body, False otherwise.
  220. """
  221. if not display_name:
  222. return False
  223. body = self._event.content.get("body", None)
  224. if not body or not isinstance(body, str):
  225. return False
  226. # Similar to _glob_matches, but do not treat display_name as a glob.
  227. r = regex_cache.get((display_name, False, True), None)
  228. if not r:
  229. r1 = re.escape(display_name)
  230. r1 = to_word_pattern(r1)
  231. r = re.compile(r1, flags=re.IGNORECASE)
  232. regex_cache[(display_name, False, True)] = r
  233. return bool(r.search(body))
  234. def _relation_match(self, condition: Mapping, user_id: str) -> bool:
  235. """
  236. Check an "relation_match" push rule condition.
  237. Args:
  238. condition: The "event_match" push rule condition to match.
  239. user_id: The user's MXID.
  240. Returns:
  241. True if the condition matches the event, False otherwise.
  242. """
  243. rel_type = condition.get("rel_type")
  244. if not rel_type:
  245. logger.warning("relation_match condition missing rel_type")
  246. return False
  247. sender_pattern = condition.get("sender")
  248. if sender_pattern is None:
  249. sender_type = condition.get("sender_type")
  250. if sender_type == "user_id":
  251. sender_pattern = user_id
  252. type_pattern = condition.get("type")
  253. # If any other relations matches, return True.
  254. for sender, event_type in self._relations.get(rel_type, ()):
  255. if sender_pattern and not _glob_matches(sender_pattern, sender):
  256. continue
  257. if type_pattern and not _glob_matches(type_pattern, event_type):
  258. continue
  259. # All values must have matched.
  260. return True
  261. # No relations matched.
  262. return False
  263. # Caches (string, is_glob, word_boundary) -> regex for push. See _glob_matches
  264. regex_cache: LruCache[Tuple[str, bool, bool], Pattern] = LruCache(
  265. 50000, "regex_push_cache"
  266. )
  267. def _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool:
  268. """Tests if value matches glob.
  269. Args:
  270. glob
  271. value: String to test against glob.
  272. word_boundary: Whether to match against word boundaries or entire
  273. string. Defaults to False.
  274. """
  275. try:
  276. r = regex_cache.get((glob, True, word_boundary), None)
  277. if not r:
  278. r = glob_to_regex(glob, word_boundary=word_boundary)
  279. regex_cache[(glob, True, word_boundary)] = r
  280. return bool(r.search(value))
  281. except re.error:
  282. logger.warning("Failed to parse glob to regex: %r", glob)
  283. return False
  284. def _flatten_dict(
  285. d: Union[EventBase, Mapping[str, Any]],
  286. prefix: Optional[List[str]] = None,
  287. result: Optional[Dict[str, str]] = None,
  288. ) -> Dict[str, str]:
  289. if prefix is None:
  290. prefix = []
  291. if result is None:
  292. result = {}
  293. for key, value in d.items():
  294. if isinstance(value, str):
  295. result[".".join(prefix + [key])] = value.lower()
  296. elif isinstance(value, Mapping):
  297. _flatten_dict(value, prefix=(prefix + [key]), result=result)
  298. return result