1
0

test_push_rule_evaluator.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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 twisted.test.proto_helpers import MemoryReactor
  17. import synapse.rest.admin
  18. from synapse.api.constants import EventTypes, Membership
  19. from synapse.api.room_versions import RoomVersions
  20. from synapse.appservice import ApplicationService
  21. from synapse.events import FrozenEvent
  22. from synapse.push import push_rule_evaluator
  23. from synapse.push.push_rule_evaluator import PushRuleEvaluatorForEvent
  24. from synapse.rest.client import login, register, room
  25. from synapse.server import HomeServer
  26. from synapse.storage.databases.main.appservice import _make_exclusive_regex
  27. from synapse.types import JsonDict
  28. from synapse.util import Clock
  29. from tests import unittest
  30. from tests.test_utils.event_injection import create_event, inject_member_event
  31. class PushRuleEvaluatorTestCase(unittest.TestCase):
  32. def _get_evaluator(
  33. self,
  34. content: JsonDict,
  35. relations: Optional[Dict[str, Set[Tuple[str, str]]]] = None,
  36. relations_match_enabled: bool = False,
  37. ) -> PushRuleEvaluatorForEvent:
  38. event = FrozenEvent(
  39. {
  40. "event_id": "$event_id",
  41. "type": "m.room.history_visibility",
  42. "sender": "@user:test",
  43. "state_key": "",
  44. "room_id": "#room:test",
  45. "content": content,
  46. },
  47. RoomVersions.V1,
  48. )
  49. room_member_count = 0
  50. sender_power_level = 0
  51. power_levels: Dict[str, Union[int, Dict[str, int]]] = {}
  52. return PushRuleEvaluatorForEvent(
  53. event,
  54. room_member_count,
  55. sender_power_level,
  56. power_levels,
  57. relations or set(),
  58. relations_match_enabled,
  59. )
  60. def test_display_name(self) -> None:
  61. """Check for a matching display name in the body of the event."""
  62. evaluator = self._get_evaluator({"body": "foo bar baz"})
  63. condition = {
  64. "kind": "contains_display_name",
  65. }
  66. # Blank names are skipped.
  67. self.assertFalse(evaluator.matches(condition, "@user:test", ""))
  68. # Check a display name that doesn't match.
  69. self.assertFalse(evaluator.matches(condition, "@user:test", "not found"))
  70. # Check a display name which matches.
  71. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))
  72. # A display name that matches, but not a full word does not result in a match.
  73. self.assertFalse(evaluator.matches(condition, "@user:test", "ba"))
  74. # A display name should not be interpreted as a regular expression.
  75. self.assertFalse(evaluator.matches(condition, "@user:test", "ba[rz]"))
  76. # A display name with spaces should work fine.
  77. self.assertTrue(evaluator.matches(condition, "@user:test", "foo bar"))
  78. def _assert_matches(
  79. self, condition: JsonDict, content: JsonDict, msg: Optional[str] = None
  80. ) -> None:
  81. evaluator = self._get_evaluator(content)
  82. self.assertTrue(evaluator.matches(condition, "@user:test", "display_name"), msg)
  83. def _assert_not_matches(
  84. self, condition: JsonDict, content: JsonDict, msg: Optional[str] = None
  85. ) -> None:
  86. evaluator = self._get_evaluator(content)
  87. self.assertFalse(
  88. evaluator.matches(condition, "@user:test", "display_name"), msg
  89. )
  90. def test_event_match_body(self) -> None:
  91. """Check that event_match conditions on content.body work as expected"""
  92. # if the key is `content.body`, the pattern matches substrings.
  93. # non-wildcards should match
  94. condition = {
  95. "kind": "event_match",
  96. "key": "content.body",
  97. "pattern": "foobaz",
  98. }
  99. self._assert_matches(
  100. condition,
  101. {"body": "aaa FoobaZ zzz"},
  102. "patterns should match and be case-insensitive",
  103. )
  104. self._assert_not_matches(
  105. condition,
  106. {"body": "aa xFoobaZ yy"},
  107. "pattern should only match at word boundaries",
  108. )
  109. self._assert_not_matches(
  110. condition,
  111. {"body": "aa foobazx yy"},
  112. "pattern should only match at word boundaries",
  113. )
  114. # wildcards should match
  115. condition = {
  116. "kind": "event_match",
  117. "key": "content.body",
  118. "pattern": "f?o*baz",
  119. }
  120. self._assert_matches(
  121. condition,
  122. {"body": "aaa FoobarbaZ zzz"},
  123. "* should match string and pattern should be case-insensitive",
  124. )
  125. self._assert_matches(
  126. condition, {"body": "aa foobaz yy"}, "* should match 0 characters"
  127. )
  128. self._assert_not_matches(
  129. condition, {"body": "aa fobbaz yy"}, "? should not match 0 characters"
  130. )
  131. self._assert_not_matches(
  132. condition, {"body": "aa fiiobaz yy"}, "? should not match 2 characters"
  133. )
  134. self._assert_not_matches(
  135. condition,
  136. {"body": "aa xfooxbaz yy"},
  137. "pattern should only match at word boundaries",
  138. )
  139. self._assert_not_matches(
  140. condition,
  141. {"body": "aa fooxbazx yy"},
  142. "pattern should only match at word boundaries",
  143. )
  144. # test backslashes
  145. condition = {
  146. "kind": "event_match",
  147. "key": "content.body",
  148. "pattern": r"f\oobaz",
  149. }
  150. self._assert_matches(
  151. condition,
  152. {"body": r"F\oobaz"},
  153. "backslash should match itself",
  154. )
  155. condition = {
  156. "kind": "event_match",
  157. "key": "content.body",
  158. "pattern": r"f\?obaz",
  159. }
  160. self._assert_matches(
  161. condition,
  162. {"body": r"F\oobaz"},
  163. r"? after \ should match any character",
  164. )
  165. def test_event_match_non_body(self) -> None:
  166. """Check that event_match conditions on other keys work as expected"""
  167. # if the key is anything other than 'content.body', the pattern must match the
  168. # whole value.
  169. # non-wildcards should match
  170. condition = {
  171. "kind": "event_match",
  172. "key": "content.value",
  173. "pattern": "foobaz",
  174. }
  175. self._assert_matches(
  176. condition,
  177. {"value": "FoobaZ"},
  178. "patterns should match and be case-insensitive",
  179. )
  180. self._assert_not_matches(
  181. condition,
  182. {"value": "xFoobaZ"},
  183. "pattern should only match at the start/end of the value",
  184. )
  185. self._assert_not_matches(
  186. condition,
  187. {"value": "FoobaZz"},
  188. "pattern should only match at the start/end of the value",
  189. )
  190. # it should work on frozendicts too
  191. self._assert_matches(
  192. condition,
  193. frozendict.frozendict({"value": "FoobaZ"}),
  194. "patterns should match on frozendicts",
  195. )
  196. # wildcards should match
  197. condition = {
  198. "kind": "event_match",
  199. "key": "content.value",
  200. "pattern": "f?o*baz",
  201. }
  202. self._assert_matches(
  203. condition,
  204. {"value": "FoobarbaZ"},
  205. "* should match string and pattern should be case-insensitive",
  206. )
  207. self._assert_matches(
  208. condition, {"value": "foobaz"}, "* should match 0 characters"
  209. )
  210. self._assert_not_matches(
  211. condition, {"value": "fobbaz"}, "? should not match 0 characters"
  212. )
  213. self._assert_not_matches(
  214. condition, {"value": "fiiobaz"}, "? should not match 2 characters"
  215. )
  216. self._assert_not_matches(
  217. condition,
  218. {"value": "xfooxbaz"},
  219. "pattern should only match at the start/end of the value",
  220. )
  221. self._assert_not_matches(
  222. condition,
  223. {"value": "fooxbazx"},
  224. "pattern should only match at the start/end of the value",
  225. )
  226. self._assert_not_matches(
  227. condition,
  228. {"value": "x\nfooxbaz"},
  229. "pattern should not match after a newline",
  230. )
  231. self._assert_not_matches(
  232. condition,
  233. {"value": "fooxbaz\nx"},
  234. "pattern should not match before a newline",
  235. )
  236. def test_no_body(self) -> None:
  237. """Not having a body shouldn't break the evaluator."""
  238. evaluator = self._get_evaluator({})
  239. condition = {
  240. "kind": "contains_display_name",
  241. }
  242. self.assertFalse(evaluator.matches(condition, "@user:test", "foo"))
  243. def test_invalid_body(self) -> None:
  244. """A non-string body should not break the evaluator."""
  245. condition = {
  246. "kind": "contains_display_name",
  247. }
  248. for body in (1, True, {"foo": "bar"}):
  249. evaluator = self._get_evaluator({"body": body})
  250. self.assertFalse(evaluator.matches(condition, "@user:test", "foo"))
  251. def test_tweaks_for_actions(self) -> None:
  252. """
  253. This tests the behaviour of tweaks_for_actions.
  254. """
  255. actions = [
  256. {"set_tweak": "sound", "value": "default"},
  257. {"set_tweak": "highlight"},
  258. "notify",
  259. ]
  260. self.assertEqual(
  261. push_rule_evaluator.tweaks_for_actions(actions),
  262. {"sound": "default", "highlight": True},
  263. )
  264. def test_relation_match(self) -> None:
  265. """Test the relation_match push rule kind."""
  266. # Check if the experimental feature is disabled.
  267. evaluator = self._get_evaluator(
  268. {}, {"m.annotation": {("@user:test", "m.reaction")}}
  269. )
  270. condition = {"kind": "relation_match"}
  271. # Oddly, an unknown condition always matches.
  272. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))
  273. # A push rule evaluator with the experimental rule enabled.
  274. evaluator = self._get_evaluator(
  275. {}, {"m.annotation": {("@user:test", "m.reaction")}}, True
  276. )
  277. # Check just relation type.
  278. condition = {
  279. "kind": "org.matrix.msc3772.relation_match",
  280. "rel_type": "m.annotation",
  281. }
  282. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))
  283. # Check relation type and sender.
  284. condition = {
  285. "kind": "org.matrix.msc3772.relation_match",
  286. "rel_type": "m.annotation",
  287. "sender": "@user:test",
  288. }
  289. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))
  290. condition = {
  291. "kind": "org.matrix.msc3772.relation_match",
  292. "rel_type": "m.annotation",
  293. "sender": "@other:test",
  294. }
  295. self.assertFalse(evaluator.matches(condition, "@user:test", "foo"))
  296. # Check relation type and event type.
  297. condition = {
  298. "kind": "org.matrix.msc3772.relation_match",
  299. "rel_type": "m.annotation",
  300. "type": "m.reaction",
  301. }
  302. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))
  303. # Check just sender, this fails since rel_type is required.
  304. condition = {
  305. "kind": "org.matrix.msc3772.relation_match",
  306. "sender": "@user:test",
  307. }
  308. self.assertFalse(evaluator.matches(condition, "@user:test", "foo"))
  309. # Check sender glob.
  310. condition = {
  311. "kind": "org.matrix.msc3772.relation_match",
  312. "rel_type": "m.annotation",
  313. "sender": "@*:test",
  314. }
  315. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))
  316. # Check event type glob.
  317. condition = {
  318. "kind": "org.matrix.msc3772.relation_match",
  319. "rel_type": "m.annotation",
  320. "event_type": "*.reaction",
  321. }
  322. self.assertTrue(evaluator.matches(condition, "@user:test", "foo"))
  323. class TestBulkPushRuleEvaluator(unittest.HomeserverTestCase):
  324. """Tests for the bulk push rule evaluator"""
  325. servlets = [
  326. synapse.rest.admin.register_servlets_for_client_rest_resource,
  327. login.register_servlets,
  328. register.register_servlets,
  329. room.register_servlets,
  330. ]
  331. def prepare(self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer):
  332. # Define an application service so that we can register appservice users
  333. self._service_token = "some_token"
  334. self._service = ApplicationService(
  335. self._service_token,
  336. "as1",
  337. "@as.sender:test",
  338. namespaces={
  339. "users": [
  340. {"regex": "@_as_.*:test", "exclusive": True},
  341. {"regex": "@as.sender:test", "exclusive": True},
  342. ]
  343. },
  344. msc3202_transaction_extensions=True,
  345. )
  346. self.hs.get_datastores().main.services_cache = [self._service]
  347. self.hs.get_datastores().main.exclusive_user_regex = _make_exclusive_regex(
  348. [self._service]
  349. )
  350. self._as_user, _ = self.register_appservice_user(
  351. "_as_user", self._service_token
  352. )
  353. self.evaluator = self.hs.get_bulk_push_rule_evaluator()
  354. def test_ignore_appservice_users(self) -> None:
  355. "Test that we don't generate push for appservice users"
  356. user_id = self.register_user("user", "pass")
  357. token = self.login("user", "pass")
  358. room_id = self.helper.create_room_as(user_id, tok=token)
  359. self.get_success(
  360. inject_member_event(self.hs, room_id, self._as_user, Membership.JOIN)
  361. )
  362. event, context = self.get_success(
  363. create_event(
  364. self.hs,
  365. type=EventTypes.Message,
  366. room_id=room_id,
  367. sender=user_id,
  368. content={"body": "test", "msgtype": "m.text"},
  369. )
  370. )
  371. # Assert the returned push rules do not contain the app service user
  372. rules = self.get_success(self.evaluator._get_rules_for_event(event))
  373. self.assertTrue(self._as_user not in rules)
  374. # Assert that no push actions have been added to the staging table (the
  375. # sender should not be pushed for the event)
  376. users_with_push_actions = self.get_success(
  377. self.hs.get_datastores().main.db_pool.simple_select_onecol(
  378. table="event_push_actions_staging",
  379. keyvalues={"event_id": event.event_id},
  380. retcol="user_id",
  381. desc="test_ignore_appservice_users",
  382. )
  383. )
  384. self.assertEqual(len(users_with_push_actions), 0)