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.
 
 
 
 
 
 

573 lines
20 KiB

  1. // Copyright 2022 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. use std::borrow::Cow;
  15. use std::collections::BTreeMap;
  16. use anyhow::{Context, Error};
  17. use lazy_static::lazy_static;
  18. use log::warn;
  19. use pyo3::prelude::*;
  20. use regex::Regex;
  21. use super::{
  22. utils::{get_glob_matcher, get_localpart_from_id, GlobMatchType},
  23. Action, Condition, EventPropertyIsCondition, FilteredPushRules, KnownCondition,
  24. SimpleJsonValue,
  25. };
  26. use crate::push::{EventMatchPatternType, JsonValue};
  27. lazy_static! {
  28. /// Used to parse the `is` clause in the room member count condition.
  29. static ref INEQUALITY_EXPR: Regex = Regex::new(r"^([=<>]*)([0-9]+)$").expect("valid regex");
  30. /// Used to determine which MSC3931 room version feature flags are actually known to
  31. /// the push evaluator.
  32. static ref KNOWN_RVER_FLAGS: Vec<String> = vec![
  33. RoomVersionFeatures::ExtensibleEvents.as_str().to_string(),
  34. ];
  35. /// The "safe" rule IDs which are not affected by MSC3932's behaviour (room versions which
  36. /// declare Extensible Events support ultimately *disable* push rules which do not declare
  37. /// *any* MSC3931 room_version_supports condition).
  38. static ref SAFE_EXTENSIBLE_EVENTS_RULE_IDS: Vec<String> = vec![
  39. "global/override/.m.rule.master".to_string(),
  40. "global/override/.m.rule.roomnotif".to_string(),
  41. "global/content/.m.rule.contains_user_name".to_string(),
  42. ];
  43. }
  44. enum RoomVersionFeatures {
  45. ExtensibleEvents,
  46. }
  47. impl RoomVersionFeatures {
  48. fn as_str(&self) -> &'static str {
  49. match self {
  50. RoomVersionFeatures::ExtensibleEvents => "org.matrix.msc3932.extensible_events",
  51. }
  52. }
  53. }
  54. /// Allows running a set of push rules against a particular event.
  55. #[pyclass]
  56. pub struct PushRuleEvaluator {
  57. /// A mapping of "flattened" keys to simple JSON values in the event, e.g.
  58. /// includes things like "type" and "content.msgtype".
  59. flattened_keys: BTreeMap<String, JsonValue>,
  60. /// The "content.body", if any.
  61. body: String,
  62. /// True if the event has a m.mentions property. (Note that this is a separate
  63. /// flag instead of checking flattened_keys since the m.mentions property
  64. /// might be an empty map and not appear in flattened_keys.
  65. has_mentions: bool,
  66. /// The number of users in the room.
  67. room_member_count: u64,
  68. /// The `notifications` section of the current power levels in the room.
  69. notification_power_levels: BTreeMap<String, i64>,
  70. /// The power level of the sender of the event, or None if event is an
  71. /// outlier.
  72. sender_power_level: Option<i64>,
  73. /// The related events, indexed by relation type. Flattened in the same manner as
  74. /// `flattened_keys`.
  75. related_events_flattened: BTreeMap<String, BTreeMap<String, JsonValue>>,
  76. /// If msc3664, push rules for related events, is enabled.
  77. related_event_match_enabled: bool,
  78. /// If MSC3931 is applicable, the feature flags for the room version.
  79. room_version_feature_flags: Vec<String>,
  80. /// If MSC3931 (room version feature flags) is enabled. Usually controlled by the same
  81. /// flag as MSC1767 (extensible events core).
  82. msc3931_enabled: bool,
  83. }
  84. #[pymethods]
  85. impl PushRuleEvaluator {
  86. /// Create a new `PushRuleEvaluator`. See struct docstring for details.
  87. #[allow(clippy::too_many_arguments)]
  88. #[new]
  89. pub fn py_new(
  90. flattened_keys: BTreeMap<String, JsonValue>,
  91. has_mentions: bool,
  92. room_member_count: u64,
  93. sender_power_level: Option<i64>,
  94. notification_power_levels: BTreeMap<String, i64>,
  95. related_events_flattened: BTreeMap<String, BTreeMap<String, JsonValue>>,
  96. related_event_match_enabled: bool,
  97. room_version_feature_flags: Vec<String>,
  98. msc3931_enabled: bool,
  99. ) -> Result<Self, Error> {
  100. let body = match flattened_keys.get("content.body") {
  101. Some(JsonValue::Value(SimpleJsonValue::Str(s))) => s.clone().into_owned(),
  102. _ => String::new(),
  103. };
  104. Ok(PushRuleEvaluator {
  105. flattened_keys,
  106. body,
  107. has_mentions,
  108. room_member_count,
  109. notification_power_levels,
  110. sender_power_level,
  111. related_events_flattened,
  112. related_event_match_enabled,
  113. room_version_feature_flags,
  114. msc3931_enabled,
  115. })
  116. }
  117. /// Run the evaluator with the given push rules, for the given user ID and
  118. /// display name of the user.
  119. ///
  120. /// Passing in None will skip evaluating rules matching user ID and display
  121. /// name.
  122. ///
  123. /// Returns the set of actions, if any, that match (filtering out any
  124. /// `dont_notify` and `coalesce` actions).
  125. pub fn run(
  126. &self,
  127. push_rules: &FilteredPushRules,
  128. user_id: Option<&str>,
  129. display_name: Option<&str>,
  130. ) -> Vec<Action> {
  131. 'outer: for (push_rule, enabled) in push_rules.iter() {
  132. if !enabled {
  133. continue;
  134. }
  135. let rule_id = &push_rule.rule_id().to_string();
  136. // For backwards-compatibility the legacy mention rules are disabled
  137. // if the event contains the 'm.mentions' property.
  138. if self.has_mentions
  139. && (rule_id == "global/override/.m.rule.contains_display_name"
  140. || rule_id == "global/content/.m.rule.contains_user_name"
  141. || rule_id == "global/override/.m.rule.roomnotif")
  142. {
  143. continue;
  144. }
  145. let extev_flag = &RoomVersionFeatures::ExtensibleEvents.as_str().to_string();
  146. let supports_extensible_events = self.room_version_feature_flags.contains(extev_flag);
  147. let safe_from_rver_condition = SAFE_EXTENSIBLE_EVENTS_RULE_IDS.contains(rule_id);
  148. let mut has_rver_condition = false;
  149. for condition in push_rule.conditions.iter() {
  150. has_rver_condition |= matches!(
  151. condition,
  152. // per MSC3932, we just need *any* room version condition to match
  153. Condition::Known(KnownCondition::RoomVersionSupports { feature: _ }),
  154. );
  155. match self.match_condition(condition, user_id, display_name) {
  156. Ok(true) => {}
  157. Ok(false) => continue 'outer,
  158. Err(err) => {
  159. warn!("Condition match failed {err}");
  160. continue 'outer;
  161. }
  162. }
  163. }
  164. // MSC3932: Disable push rules in extensible event-supporting room versions if they
  165. // don't describe *any* MSC3931 room version condition, unless the rule is on the
  166. // safe list.
  167. if !has_rver_condition && !safe_from_rver_condition && supports_extensible_events {
  168. continue;
  169. }
  170. let actions = push_rule
  171. .actions
  172. .iter()
  173. // Filter out "dont_notify" and "coalesce" actions, as we don't store them
  174. // (since they result in no action by the pushers).
  175. .filter(|a| **a != Action::DontNotify && **a != Action::Coalesce)
  176. .cloned()
  177. .collect();
  178. return actions;
  179. }
  180. Vec::new()
  181. }
  182. /// Check if the given condition matches.
  183. fn matches(
  184. &self,
  185. condition: Condition,
  186. user_id: Option<&str>,
  187. display_name: Option<&str>,
  188. ) -> bool {
  189. match self.match_condition(&condition, user_id, display_name) {
  190. Ok(true) => true,
  191. Ok(false) => false,
  192. Err(err) => {
  193. warn!("Condition match failed {err}");
  194. false
  195. }
  196. }
  197. }
  198. }
  199. impl PushRuleEvaluator {
  200. /// Match a given `Condition` for a push rule.
  201. pub fn match_condition(
  202. &self,
  203. condition: &Condition,
  204. user_id: Option<&str>,
  205. display_name: Option<&str>,
  206. ) -> Result<bool, Error> {
  207. let known_condition = match condition {
  208. Condition::Known(known) => known,
  209. Condition::Unknown(_) => {
  210. return Ok(false);
  211. }
  212. };
  213. let result = match known_condition {
  214. KnownCondition::EventMatch(event_match) => self.match_event_match(
  215. &self.flattened_keys,
  216. &event_match.key,
  217. &event_match.pattern,
  218. )?,
  219. KnownCondition::EventMatchType(event_match) => {
  220. // The `pattern_type` can either be "user_id" or "user_localpart",
  221. // either way if we don't have a `user_id` then the condition can't
  222. // match.
  223. let user_id = if let Some(user_id) = user_id {
  224. user_id
  225. } else {
  226. return Ok(false);
  227. };
  228. let pattern = match &*event_match.pattern_type {
  229. EventMatchPatternType::UserId => user_id,
  230. EventMatchPatternType::UserLocalpart => get_localpart_from_id(user_id)?,
  231. };
  232. self.match_event_match(&self.flattened_keys, &event_match.key, pattern)?
  233. }
  234. KnownCondition::EventPropertyIs(event_property_is) => {
  235. self.match_event_property_is(event_property_is)?
  236. }
  237. KnownCondition::RelatedEventMatch(event_match) => self.match_related_event_match(
  238. &event_match.rel_type.clone(),
  239. event_match.include_fallbacks,
  240. event_match.key.clone(),
  241. event_match.pattern.clone(),
  242. )?,
  243. KnownCondition::RelatedEventMatchType(event_match) => {
  244. // The `pattern_type` can either be "user_id" or "user_localpart",
  245. // either way if we don't have a `user_id` then the condition can't
  246. // match.
  247. let user_id = if let Some(user_id) = user_id {
  248. user_id
  249. } else {
  250. return Ok(false);
  251. };
  252. let pattern = match &*event_match.pattern_type {
  253. EventMatchPatternType::UserId => user_id,
  254. EventMatchPatternType::UserLocalpart => get_localpart_from_id(user_id)?,
  255. };
  256. self.match_related_event_match(
  257. &event_match.rel_type.clone(),
  258. event_match.include_fallbacks,
  259. Some(event_match.key.clone()),
  260. Some(Cow::Borrowed(pattern)),
  261. )?
  262. }
  263. KnownCondition::EventPropertyContains(event_property_is) => self
  264. .match_event_property_contains(
  265. event_property_is.key.clone(),
  266. event_property_is.value.clone(),
  267. )?,
  268. KnownCondition::ExactEventPropertyContainsType(exact_event_match) => {
  269. // The `pattern_type` can either be "user_id" or "user_localpart",
  270. // either way if we don't have a `user_id` then the condition can't
  271. // match.
  272. let user_id = if let Some(user_id) = user_id {
  273. user_id
  274. } else {
  275. return Ok(false);
  276. };
  277. let pattern = match &*exact_event_match.value_type {
  278. EventMatchPatternType::UserId => user_id.to_owned(),
  279. EventMatchPatternType::UserLocalpart => {
  280. get_localpart_from_id(user_id)?.to_owned()
  281. }
  282. };
  283. self.match_event_property_contains(
  284. exact_event_match.key.clone(),
  285. Cow::Borrowed(&SimpleJsonValue::Str(Cow::Owned(pattern))),
  286. )?
  287. }
  288. KnownCondition::ContainsDisplayName => {
  289. if let Some(dn) = display_name {
  290. if !dn.is_empty() {
  291. get_glob_matcher(dn, GlobMatchType::Word)?.is_match(&self.body)?
  292. } else {
  293. // We specifically ignore empty display names, as otherwise
  294. // they would always match.
  295. false
  296. }
  297. } else {
  298. false
  299. }
  300. }
  301. KnownCondition::RoomMemberCount { is } => {
  302. if let Some(is) = is {
  303. self.match_member_count(is)?
  304. } else {
  305. false
  306. }
  307. }
  308. KnownCondition::SenderNotificationPermission { key } => {
  309. if let Some(sender_power_level) = &self.sender_power_level {
  310. let required_level = self
  311. .notification_power_levels
  312. .get(key.as_ref())
  313. .copied()
  314. .unwrap_or(50);
  315. *sender_power_level >= required_level
  316. } else {
  317. false
  318. }
  319. }
  320. KnownCondition::RoomVersionSupports { feature } => {
  321. if !self.msc3931_enabled {
  322. false
  323. } else {
  324. let flag = feature.to_string();
  325. KNOWN_RVER_FLAGS.contains(&flag)
  326. && self.room_version_feature_flags.contains(&flag)
  327. }
  328. }
  329. };
  330. Ok(result)
  331. }
  332. /// Evaluates a `event_match` condition.
  333. fn match_event_match(
  334. &self,
  335. flattened_event: &BTreeMap<String, JsonValue>,
  336. key: &str,
  337. pattern: &str,
  338. ) -> Result<bool, Error> {
  339. let haystack = if let Some(JsonValue::Value(SimpleJsonValue::Str(haystack))) =
  340. flattened_event.get(key)
  341. {
  342. haystack
  343. } else {
  344. return Ok(false);
  345. };
  346. // For the content.body we match against "words", but for everything
  347. // else we match against the entire value.
  348. let match_type = if key == "content.body" {
  349. GlobMatchType::Word
  350. } else {
  351. GlobMatchType::Whole
  352. };
  353. let mut compiled_pattern = get_glob_matcher(pattern, match_type)?;
  354. compiled_pattern.is_match(haystack)
  355. }
  356. /// Evaluates a `event_property_is` condition.
  357. fn match_event_property_is(
  358. &self,
  359. event_property_is: &EventPropertyIsCondition,
  360. ) -> Result<bool, Error> {
  361. let value = &event_property_is.value;
  362. let haystack = if let Some(JsonValue::Value(haystack)) =
  363. self.flattened_keys.get(&*event_property_is.key)
  364. {
  365. haystack
  366. } else {
  367. return Ok(false);
  368. };
  369. Ok(haystack == &**value)
  370. }
  371. /// Evaluates a `related_event_match` condition. (MSC3664)
  372. fn match_related_event_match(
  373. &self,
  374. rel_type: &str,
  375. include_fallbacks: Option<bool>,
  376. key: Option<Cow<str>>,
  377. pattern: Option<Cow<str>>,
  378. ) -> Result<bool, Error> {
  379. // First check if related event matching is enabled...
  380. if !self.related_event_match_enabled {
  381. return Ok(false);
  382. }
  383. // get the related event, fail if there is none.
  384. let event = if let Some(event) = self.related_events_flattened.get(rel_type) {
  385. event
  386. } else {
  387. return Ok(false);
  388. };
  389. // If we are not matching fallbacks, don't match if our special key indicating this is a
  390. // fallback relation is not present.
  391. if !include_fallbacks.unwrap_or(false) && event.contains_key("im.vector.is_falling_back") {
  392. return Ok(false);
  393. }
  394. match (key, pattern) {
  395. // if we have no key, accept the event as matching.
  396. (None, _) => Ok(true),
  397. // There was a key, so we *must* have a pattern to go with it.
  398. (Some(_), None) => Ok(false),
  399. // If there is a key & pattern, check if they're in the flattened event (given by rel_type).
  400. (Some(key), Some(pattern)) => self.match_event_match(event, &key, &pattern),
  401. }
  402. }
  403. /// Evaluates a `event_property_contains` condition.
  404. fn match_event_property_contains(
  405. &self,
  406. key: Cow<str>,
  407. value: Cow<SimpleJsonValue>,
  408. ) -> Result<bool, Error> {
  409. let haystack = if let Some(JsonValue::Array(haystack)) = self.flattened_keys.get(&*key) {
  410. haystack
  411. } else {
  412. return Ok(false);
  413. };
  414. Ok(haystack.contains(&value))
  415. }
  416. /// Match the member count against an 'is' condition
  417. /// The `is` condition can be things like '>2', '==3' or even just '4'.
  418. fn match_member_count(&self, is: &str) -> Result<bool, Error> {
  419. let captures = INEQUALITY_EXPR.captures(is).context("bad 'is' clause")?;
  420. let ineq = captures.get(1).map_or("==", |m| m.as_str());
  421. let rhs: u64 = captures
  422. .get(2)
  423. .context("missing number")?
  424. .as_str()
  425. .parse()?;
  426. let matches = match ineq {
  427. "" | "==" => self.room_member_count == rhs,
  428. "<" => self.room_member_count < rhs,
  429. ">" => self.room_member_count > rhs,
  430. ">=" => self.room_member_count >= rhs,
  431. "<=" => self.room_member_count <= rhs,
  432. _ => false,
  433. };
  434. Ok(matches)
  435. }
  436. }
  437. #[test]
  438. fn push_rule_evaluator() {
  439. let mut flattened_keys = BTreeMap::new();
  440. flattened_keys.insert(
  441. "content.body".to_string(),
  442. JsonValue::Value(SimpleJsonValue::Str(Cow::Borrowed("foo bar bob hello"))),
  443. );
  444. let evaluator = PushRuleEvaluator::py_new(
  445. flattened_keys,
  446. false,
  447. 10,
  448. Some(0),
  449. BTreeMap::new(),
  450. BTreeMap::new(),
  451. true,
  452. vec![],
  453. true,
  454. )
  455. .unwrap();
  456. let result = evaluator.run(&FilteredPushRules::default(), None, Some("bob"));
  457. assert_eq!(result.len(), 3);
  458. }
  459. #[test]
  460. fn test_requires_room_version_supports_condition() {
  461. use std::borrow::Cow;
  462. use crate::push::{PushRule, PushRules};
  463. let mut flattened_keys = BTreeMap::new();
  464. flattened_keys.insert(
  465. "content.body".to_string(),
  466. JsonValue::Value(SimpleJsonValue::Str(Cow::Borrowed("foo bar bob hello"))),
  467. );
  468. let flags = vec![RoomVersionFeatures::ExtensibleEvents.as_str().to_string()];
  469. let evaluator = PushRuleEvaluator::py_new(
  470. flattened_keys,
  471. false,
  472. 10,
  473. Some(0),
  474. BTreeMap::new(),
  475. BTreeMap::new(),
  476. false,
  477. flags,
  478. true,
  479. )
  480. .unwrap();
  481. // first test: are the master and contains_user_name rules excluded from the "requires room
  482. // version condition" check?
  483. let mut result = evaluator.run(
  484. &FilteredPushRules::default(),
  485. Some("@bob:example.org"),
  486. None,
  487. );
  488. assert_eq!(result.len(), 3);
  489. // second test: if an appropriate push rule is in play, does it get handled?
  490. let custom_rule = PushRule {
  491. rule_id: Cow::from("global/underride/.org.example.extensible"),
  492. priority_class: 1, // underride
  493. conditions: Cow::from(vec![Condition::Known(
  494. KnownCondition::RoomVersionSupports {
  495. feature: Cow::from(RoomVersionFeatures::ExtensibleEvents.as_str().to_string()),
  496. },
  497. )]),
  498. actions: Cow::from(vec![Action::Notify]),
  499. default: false,
  500. default_enabled: true,
  501. };
  502. let rules = PushRules::new(vec![custom_rule]);
  503. result = evaluator.run(
  504. &FilteredPushRules::py_new(rules, BTreeMap::new(), true, false, true, false),
  505. None,
  506. None,
  507. );
  508. assert_eq!(result.len(), 1);
  509. }