test_push_rule_evaluator.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. # Copyright 2020 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 Dict, Optional, Set, Tuple, Union
  15. import frozendict
  16. from synapse.api.room_versions import RoomVersions
  17. from synapse.events import FrozenEvent
  18. from synapse.push import push_rule_evaluator
  19. from synapse.push.push_rule_evaluator import PushRuleEvaluatorForEvent
  20. from synapse.types import JsonDict
  21. from tests import unittest
  22. class PushRuleEvaluatorTestCase(unittest.TestCase):
  23. def _get_evaluator(
  24. self,
  25. content: JsonDict,
  26. relations: Optional[Dict[str, Set[Tuple[str, str]]]] = None,
  27. relations_match_enabled: bool = False,
  28. ) -> PushRuleEvaluatorForEvent:
  29. event = FrozenEvent(
  30. {
  31. "event_id": "$event_id",
  32. "type": "m.room.history_visibility",
  33. "sender": "@user:test",
  34. "state_key": "",
  35. "room_id": "#room:test",
  36. "content": content,
  37. },
  38. RoomVersions.V1,
  39. )
  40. room_member_count = 0
  41. sender_power_level = 0
  42. power_levels: Dict[str, Union[int, Dict[str, int]]] = {}
  43. return PushRuleEvaluatorForEvent(
  44. event,
  45. room_member_count,
  46. sender_power_level,
  47. power_levels,
  48. relations or set(),
  49. relations_match_enabled,
  50. )
  51. def test_display_name(self) -> None:
  52. """Check for a matching display name in the body of the event."""
  53. evaluator = self._get_evaluator({"body": "foo bar baz"})
  54. condition = {
  55. "kind": "contains_display_name",
  56. }
  57. # Blank names are skipped.
  58. self.assertFalse(evaluator.matches(condition, "@user:test", ""))
  59. # Check a display name that doesn't match.
  60. self.assertFalse(evaluator.matches(condition, "@user:test", "not found"))
  61. # Check a display name which matches.
  62. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))
  63. # A display name that matches, but not a full word does not result in a match.
  64. self.assertFalse(evaluator.matches(condition, "@user:test", "ba"))
  65. # A display name should not be interpreted as a regular expression.
  66. self.assertFalse(evaluator.matches(condition, "@user:test", "ba[rz]"))
  67. # A display name with spaces should work fine.
  68. self.assertTrue(evaluator.matches(condition, "@user:test", "foo bar"))
  69. def _assert_matches(
  70. self, condition: JsonDict, content: JsonDict, msg: Optional[str] = None
  71. ) -> None:
  72. evaluator = self._get_evaluator(content)
  73. self.assertTrue(evaluator.matches(condition, "@user:test", "display_name"), msg)
  74. def _assert_not_matches(
  75. self, condition: JsonDict, content: JsonDict, msg: Optional[str] = None
  76. ) -> None:
  77. evaluator = self._get_evaluator(content)
  78. self.assertFalse(
  79. evaluator.matches(condition, "@user:test", "display_name"), msg
  80. )
  81. def test_event_match_body(self) -> None:
  82. """Check that event_match conditions on content.body work as expected"""
  83. # if the key is `content.body`, the pattern matches substrings.
  84. # non-wildcards should match
  85. condition = {
  86. "kind": "event_match",
  87. "key": "content.body",
  88. "pattern": "foobaz",
  89. }
  90. self._assert_matches(
  91. condition,
  92. {"body": "aaa FoobaZ zzz"},
  93. "patterns should match and be case-insensitive",
  94. )
  95. self._assert_not_matches(
  96. condition,
  97. {"body": "aa xFoobaZ yy"},
  98. "pattern should only match at word boundaries",
  99. )
  100. self._assert_not_matches(
  101. condition,
  102. {"body": "aa foobazx yy"},
  103. "pattern should only match at word boundaries",
  104. )
  105. # wildcards should match
  106. condition = {
  107. "kind": "event_match",
  108. "key": "content.body",
  109. "pattern": "f?o*baz",
  110. }
  111. self._assert_matches(
  112. condition,
  113. {"body": "aaa FoobarbaZ zzz"},
  114. "* should match string and pattern should be case-insensitive",
  115. )
  116. self._assert_matches(
  117. condition, {"body": "aa foobaz yy"}, "* should match 0 characters"
  118. )
  119. self._assert_not_matches(
  120. condition, {"body": "aa fobbaz yy"}, "? should not match 0 characters"
  121. )
  122. self._assert_not_matches(
  123. condition, {"body": "aa fiiobaz yy"}, "? should not match 2 characters"
  124. )
  125. self._assert_not_matches(
  126. condition,
  127. {"body": "aa xfooxbaz yy"},
  128. "pattern should only match at word boundaries",
  129. )
  130. self._assert_not_matches(
  131. condition,
  132. {"body": "aa fooxbazx yy"},
  133. "pattern should only match at word boundaries",
  134. )
  135. # test backslashes
  136. condition = {
  137. "kind": "event_match",
  138. "key": "content.body",
  139. "pattern": r"f\oobaz",
  140. }
  141. self._assert_matches(
  142. condition,
  143. {"body": r"F\oobaz"},
  144. "backslash should match itself",
  145. )
  146. condition = {
  147. "kind": "event_match",
  148. "key": "content.body",
  149. "pattern": r"f\?obaz",
  150. }
  151. self._assert_matches(
  152. condition,
  153. {"body": r"F\oobaz"},
  154. r"? after \ should match any character",
  155. )
  156. def test_event_match_non_body(self) -> None:
  157. """Check that event_match conditions on other keys work as expected"""
  158. # if the key is anything other than 'content.body', the pattern must match the
  159. # whole value.
  160. # non-wildcards should match
  161. condition = {
  162. "kind": "event_match",
  163. "key": "content.value",
  164. "pattern": "foobaz",
  165. }
  166. self._assert_matches(
  167. condition,
  168. {"value": "FoobaZ"},
  169. "patterns should match and be case-insensitive",
  170. )
  171. self._assert_not_matches(
  172. condition,
  173. {"value": "xFoobaZ"},
  174. "pattern should only match at the start/end of the value",
  175. )
  176. self._assert_not_matches(
  177. condition,
  178. {"value": "FoobaZz"},
  179. "pattern should only match at the start/end of the value",
  180. )
  181. # it should work on frozendicts too
  182. self._assert_matches(
  183. condition,
  184. frozendict.frozendict({"value": "FoobaZ"}),
  185. "patterns should match on frozendicts",
  186. )
  187. # wildcards should match
  188. condition = {
  189. "kind": "event_match",
  190. "key": "content.value",
  191. "pattern": "f?o*baz",
  192. }
  193. self._assert_matches(
  194. condition,
  195. {"value": "FoobarbaZ"},
  196. "* should match string and pattern should be case-insensitive",
  197. )
  198. self._assert_matches(
  199. condition, {"value": "foobaz"}, "* should match 0 characters"
  200. )
  201. self._assert_not_matches(
  202. condition, {"value": "fobbaz"}, "? should not match 0 characters"
  203. )
  204. self._assert_not_matches(
  205. condition, {"value": "fiiobaz"}, "? should not match 2 characters"
  206. )
  207. self._assert_not_matches(
  208. condition,
  209. {"value": "xfooxbaz"},
  210. "pattern should only match at the start/end of the value",
  211. )
  212. self._assert_not_matches(
  213. condition,
  214. {"value": "fooxbazx"},
  215. "pattern should only match at the start/end of the value",
  216. )
  217. self._assert_not_matches(
  218. condition,
  219. {"value": "x\nfooxbaz"},
  220. "pattern should not match after a newline",
  221. )
  222. self._assert_not_matches(
  223. condition,
  224. {"value": "fooxbaz\nx"},
  225. "pattern should not match before a newline",
  226. )
  227. def test_no_body(self) -> None:
  228. """Not having a body shouldn't break the evaluator."""
  229. evaluator = self._get_evaluator({})
  230. condition = {
  231. "kind": "contains_display_name",
  232. }
  233. self.assertFalse(evaluator.matches(condition, "@user:test", "foo"))
  234. def test_invalid_body(self) -> None:
  235. """A non-string body should not break the evaluator."""
  236. condition = {
  237. "kind": "contains_display_name",
  238. }
  239. for body in (1, True, {"foo": "bar"}):
  240. evaluator = self._get_evaluator({"body": body})
  241. self.assertFalse(evaluator.matches(condition, "@user:test", "foo"))
  242. def test_tweaks_for_actions(self) -> None:
  243. """
  244. This tests the behaviour of tweaks_for_actions.
  245. """
  246. actions = [
  247. {"set_tweak": "sound", "value": "default"},
  248. {"set_tweak": "highlight"},
  249. "notify",
  250. ]
  251. self.assertEqual(
  252. push_rule_evaluator.tweaks_for_actions(actions),
  253. {"sound": "default", "highlight": True},
  254. )
  255. def test_relation_match(self) -> None:
  256. """Test the relation_match push rule kind."""
  257. # Check if the experimental feature is disabled.
  258. evaluator = self._get_evaluator(
  259. {}, {"m.annotation": {("@user:test", "m.reaction")}}
  260. )
  261. condition = {"kind": "relation_match"}
  262. # Oddly, an unknown condition always matches.
  263. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))
  264. # A push rule evaluator with the experimental rule enabled.
  265. evaluator = self._get_evaluator(
  266. {}, {"m.annotation": {("@user:test", "m.reaction")}}, True
  267. )
  268. # Check just relation type.
  269. condition = {
  270. "kind": "org.matrix.msc3772.relation_match",
  271. "rel_type": "m.annotation",
  272. }
  273. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))
  274. # Check relation type and sender.
  275. condition = {
  276. "kind": "org.matrix.msc3772.relation_match",
  277. "rel_type": "m.annotation",
  278. "sender": "@user:test",
  279. }
  280. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))
  281. condition = {
  282. "kind": "org.matrix.msc3772.relation_match",
  283. "rel_type": "m.annotation",
  284. "sender": "@other:test",
  285. }
  286. self.assertFalse(evaluator.matches(condition, "@user:test", "foo"))
  287. # Check relation type and event type.
  288. condition = {
  289. "kind": "org.matrix.msc3772.relation_match",
  290. "rel_type": "m.annotation",
  291. "type": "m.reaction",
  292. }
  293. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))
  294. # Check just sender, this fails since rel_type is required.
  295. condition = {
  296. "kind": "org.matrix.msc3772.relation_match",
  297. "sender": "@user:test",
  298. }
  299. self.assertFalse(evaluator.matches(condition, "@user:test", "foo"))
  300. # Check sender glob.
  301. condition = {
  302. "kind": "org.matrix.msc3772.relation_match",
  303. "rel_type": "m.annotation",
  304. "sender": "@*:test",
  305. }
  306. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))
  307. # Check event type glob.
  308. condition = {
  309. "kind": "org.matrix.msc3772.relation_match",
  310. "rel_type": "m.annotation",
  311. "event_type": "*.reaction",
  312. }
  313. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))