__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. # Copyright 2022 The Matrix.org Foundation C.I.C.
  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 enum import Enum
  18. from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Pattern
  19. import attr
  20. from netaddr import IPSet
  21. from synapse.api.constants import EventTypes
  22. from synapse.events import EventBase
  23. from synapse.types import (
  24. DeviceListUpdates,
  25. GroupID,
  26. JsonDict,
  27. UserID,
  28. get_domain_from_id,
  29. )
  30. from synapse.util.caches.descriptors import _CacheContext, cached
  31. if TYPE_CHECKING:
  32. from synapse.appservice.api import ApplicationServiceApi
  33. from synapse.storage.databases.main import DataStore
  34. logger = logging.getLogger(__name__)
  35. # Type for the `device_one_time_key_counts` field in an appservice transaction
  36. # user ID -> {device ID -> {algorithm -> count}}
  37. TransactionOneTimeKeyCounts = Dict[str, Dict[str, Dict[str, int]]]
  38. # Type for the `device_unused_fallback_key_types` field in an appservice transaction
  39. # user ID -> {device ID -> [algorithm]}
  40. TransactionUnusedFallbackKeys = Dict[str, Dict[str, List[str]]]
  41. class ApplicationServiceState(Enum):
  42. DOWN = "down"
  43. UP = "up"
  44. @attr.s(slots=True, frozen=True, auto_attribs=True)
  45. class Namespace:
  46. exclusive: bool
  47. group_id: Optional[str]
  48. regex: Pattern[str]
  49. class ApplicationService:
  50. """Defines an application service. This definition is mostly what is
  51. provided to the /register AS API.
  52. Provides methods to check if this service is "interested" in events.
  53. """
  54. NS_USERS = "users"
  55. NS_ALIASES = "aliases"
  56. NS_ROOMS = "rooms"
  57. # The ordering here is important as it is used to map database values (which
  58. # are stored as ints representing the position in this list) to namespace
  59. # values.
  60. NS_LIST = [NS_USERS, NS_ALIASES, NS_ROOMS]
  61. def __init__(
  62. self,
  63. token: str,
  64. hostname: str,
  65. id: str,
  66. sender: str,
  67. url: Optional[str] = None,
  68. namespaces: Optional[JsonDict] = None,
  69. hs_token: Optional[str] = None,
  70. protocols: Optional[Iterable[str]] = None,
  71. rate_limited: bool = True,
  72. ip_range_whitelist: Optional[IPSet] = None,
  73. supports_ephemeral: bool = False,
  74. msc3202_transaction_extensions: bool = False,
  75. ):
  76. self.token = token
  77. self.url = (
  78. url.rstrip("/") if isinstance(url, str) else None
  79. ) # url must not end with a slash
  80. self.hs_token = hs_token
  81. self.sender = sender
  82. self.server_name = hostname
  83. self.namespaces = self._check_namespaces(namespaces)
  84. self.id = id
  85. self.ip_range_whitelist = ip_range_whitelist
  86. self.supports_ephemeral = supports_ephemeral
  87. self.msc3202_transaction_extensions = msc3202_transaction_extensions
  88. if "|" in self.id:
  89. raise Exception("application service ID cannot contain '|' character")
  90. # .protocols is a publicly visible field
  91. if protocols:
  92. self.protocols = set(protocols)
  93. else:
  94. self.protocols = set()
  95. self.rate_limited = rate_limited
  96. def _check_namespaces(
  97. self, namespaces: Optional[JsonDict]
  98. ) -> Dict[str, List[Namespace]]:
  99. # Sanity check that it is of the form:
  100. # {
  101. # users: [ {regex: "[A-z]+.*", exclusive: true}, ...],
  102. # aliases: [ {regex: "[A-z]+.*", exclusive: true}, ...],
  103. # rooms: [ {regex: "[A-z]+.*", exclusive: true}, ...],
  104. # }
  105. if namespaces is None:
  106. namespaces = {}
  107. result: Dict[str, List[Namespace]] = {}
  108. for ns in ApplicationService.NS_LIST:
  109. result[ns] = []
  110. if ns not in namespaces:
  111. continue
  112. if not isinstance(namespaces[ns], list):
  113. raise ValueError("Bad namespace value for '%s'" % ns)
  114. for regex_obj in namespaces[ns]:
  115. if not isinstance(regex_obj, dict):
  116. raise ValueError("Expected dict regex for ns '%s'" % ns)
  117. exclusive = regex_obj.get("exclusive")
  118. if not isinstance(exclusive, bool):
  119. raise ValueError("Expected bool for 'exclusive' in ns '%s'" % ns)
  120. group_id = regex_obj.get("group_id")
  121. if group_id:
  122. if not isinstance(group_id, str):
  123. raise ValueError(
  124. "Expected string for 'group_id' in ns '%s'" % ns
  125. )
  126. try:
  127. GroupID.from_string(group_id)
  128. except Exception:
  129. raise ValueError(
  130. "Expected valid group ID for 'group_id' in ns '%s'" % ns
  131. )
  132. if get_domain_from_id(group_id) != self.server_name:
  133. raise ValueError(
  134. "Expected 'group_id' to be this host in ns '%s'" % ns
  135. )
  136. regex = regex_obj.get("regex")
  137. if not isinstance(regex, str):
  138. raise ValueError("Expected string for 'regex' in ns '%s'" % ns)
  139. # Pre-compile regex.
  140. result[ns].append(Namespace(exclusive, group_id, re.compile(regex)))
  141. return result
  142. def _matches_regex(
  143. self, namespace_key: str, test_string: str
  144. ) -> Optional[Namespace]:
  145. for namespace in self.namespaces[namespace_key]:
  146. if namespace.regex.match(test_string):
  147. return namespace
  148. return None
  149. def _is_exclusive(self, namespace_key: str, test_string: str) -> bool:
  150. namespace = self._matches_regex(namespace_key, test_string)
  151. if namespace:
  152. return namespace.exclusive
  153. return False
  154. @cached(num_args=1, cache_context=True)
  155. async def _matches_user_in_member_list(
  156. self,
  157. room_id: str,
  158. store: "DataStore",
  159. cache_context: _CacheContext,
  160. ) -> bool:
  161. """Check if this service is interested a room based upon its membership
  162. Args:
  163. room_id: The room to check.
  164. store: The datastore to query.
  165. Returns:
  166. True if this service would like to know about this room.
  167. """
  168. member_list = await store.get_users_in_room(
  169. room_id, on_invalidate=cache_context.invalidate
  170. )
  171. # check joined member events
  172. for user_id in member_list:
  173. if self.is_interested_in_user(user_id):
  174. return True
  175. return False
  176. def is_interested_in_user(
  177. self,
  178. user_id: str,
  179. ) -> bool:
  180. """
  181. Returns whether the application is interested in a given user ID.
  182. The appservice is considered to be interested in a user if either: the
  183. user ID is in the appservice's user namespace, or if the user is the
  184. appservice's configured sender_localpart.
  185. Args:
  186. user_id: The ID of the user to check.
  187. Returns:
  188. True if the application service is interested in the user, False if not.
  189. """
  190. return (
  191. # User is the appservice's sender_localpart user
  192. user_id == self.sender
  193. # User is in the appservice's user namespace
  194. or self.is_user_in_namespace(user_id)
  195. )
  196. @cached(num_args=1, cache_context=True)
  197. async def is_interested_in_room(
  198. self,
  199. room_id: str,
  200. store: "DataStore",
  201. cache_context: _CacheContext,
  202. ) -> bool:
  203. """
  204. Returns whether the application service is interested in a given room ID.
  205. The appservice is considered to be interested in the room if either: the ID or one
  206. of the aliases of the room is in the appservice's room ID or alias namespace
  207. respectively, or if one of the members of the room fall into the appservice's user
  208. namespace.
  209. Args:
  210. room_id: The ID of the room to check.
  211. store: The homeserver's datastore class.
  212. Returns:
  213. True if the application service is interested in the room, False if not.
  214. """
  215. # Check if we have interest in this room ID
  216. if self.is_room_id_in_namespace(room_id):
  217. return True
  218. # likewise with the room's aliases (if it has any)
  219. alias_list = await store.get_aliases_for_room(room_id)
  220. for alias in alias_list:
  221. if self.is_room_alias_in_namespace(alias):
  222. return True
  223. # And finally, perform an expensive check on whether any of the
  224. # users in the room match the appservice's user namespace
  225. return await self._matches_user_in_member_list(
  226. room_id, store, on_invalidate=cache_context.invalidate
  227. )
  228. @cached(num_args=1, cache_context=True)
  229. async def is_interested_in_event(
  230. self,
  231. event_id: str,
  232. event: EventBase,
  233. store: "DataStore",
  234. cache_context: _CacheContext,
  235. ) -> bool:
  236. """Check if this service is interested in this event.
  237. Args:
  238. event_id: The ID of the event to check. This is purely used for simplifying the
  239. caching of calls to this method.
  240. event: The event to check.
  241. store: The datastore to query.
  242. Returns:
  243. True if this service would like to know about this event, otherwise False.
  244. """
  245. # Check if we're interested in this event's sender by namespace (or if they're the
  246. # sender_localpart user)
  247. if self.is_interested_in_user(event.sender):
  248. return True
  249. # additionally, if this is a membership event, perform the same checks on
  250. # the user it references
  251. if event.type == EventTypes.Member and self.is_interested_in_user(
  252. event.state_key
  253. ):
  254. return True
  255. # This will check the datastore, so should be run last
  256. if await self.is_interested_in_room(
  257. event.room_id, store, on_invalidate=cache_context.invalidate
  258. ):
  259. return True
  260. return False
  261. @cached(num_args=1, cache_context=True)
  262. async def is_interested_in_presence(
  263. self, user_id: UserID, store: "DataStore", cache_context: _CacheContext
  264. ) -> bool:
  265. """Check if this service is interested a user's presence
  266. Args:
  267. user_id: The user to check.
  268. store: The datastore to query.
  269. Returns:
  270. True if this service would like to know about presence for this user.
  271. """
  272. # Find all the rooms the sender is in
  273. if self.is_interested_in_user(user_id.to_string()):
  274. return True
  275. room_ids = await store.get_rooms_for_user(user_id.to_string())
  276. # Then find out if the appservice is interested in any of those rooms
  277. for room_id in room_ids:
  278. if await self.is_interested_in_room(
  279. room_id, store, on_invalidate=cache_context.invalidate
  280. ):
  281. return True
  282. return False
  283. def is_user_in_namespace(self, user_id: str) -> bool:
  284. return bool(self._matches_regex(ApplicationService.NS_USERS, user_id))
  285. def is_room_alias_in_namespace(self, alias: str) -> bool:
  286. return bool(self._matches_regex(ApplicationService.NS_ALIASES, alias))
  287. def is_room_id_in_namespace(self, room_id: str) -> bool:
  288. return bool(self._matches_regex(ApplicationService.NS_ROOMS, room_id))
  289. def is_exclusive_user(self, user_id: str) -> bool:
  290. return (
  291. self._is_exclusive(ApplicationService.NS_USERS, user_id)
  292. or user_id == self.sender
  293. )
  294. def is_interested_in_protocol(self, protocol: str) -> bool:
  295. return protocol in self.protocols
  296. def is_exclusive_alias(self, alias: str) -> bool:
  297. return self._is_exclusive(ApplicationService.NS_ALIASES, alias)
  298. def is_exclusive_room(self, room_id: str) -> bool:
  299. return self._is_exclusive(ApplicationService.NS_ROOMS, room_id)
  300. def get_exclusive_user_regexes(self) -> List[Pattern[str]]:
  301. """Get the list of regexes used to determine if a user is exclusively
  302. registered by the AS
  303. """
  304. return [
  305. namespace.regex
  306. for namespace in self.namespaces[ApplicationService.NS_USERS]
  307. if namespace.exclusive
  308. ]
  309. def get_groups_for_user(self, user_id: str) -> Iterable[str]:
  310. """Get the groups that this user is associated with by this AS
  311. Args:
  312. user_id: The ID of the user.
  313. Returns:
  314. An iterable that yields group_id strings.
  315. """
  316. return (
  317. namespace.group_id
  318. for namespace in self.namespaces[ApplicationService.NS_USERS]
  319. if namespace.group_id and namespace.regex.match(user_id)
  320. )
  321. def is_rate_limited(self) -> bool:
  322. return self.rate_limited
  323. def __str__(self) -> str:
  324. # copy dictionary and redact token fields so they don't get logged
  325. dict_copy = self.__dict__.copy()
  326. dict_copy["token"] = "<redacted>"
  327. dict_copy["hs_token"] = "<redacted>"
  328. return "ApplicationService: %s" % (dict_copy,)
  329. class AppServiceTransaction:
  330. """Represents an application service transaction."""
  331. def __init__(
  332. self,
  333. service: ApplicationService,
  334. id: int,
  335. events: List[EventBase],
  336. ephemeral: List[JsonDict],
  337. to_device_messages: List[JsonDict],
  338. one_time_key_counts: TransactionOneTimeKeyCounts,
  339. unused_fallback_keys: TransactionUnusedFallbackKeys,
  340. device_list_summary: DeviceListUpdates,
  341. ):
  342. self.service = service
  343. self.id = id
  344. self.events = events
  345. self.ephemeral = ephemeral
  346. self.to_device_messages = to_device_messages
  347. self.one_time_key_counts = one_time_key_counts
  348. self.unused_fallback_keys = unused_fallback_keys
  349. self.device_list_summary = device_list_summary
  350. async def send(self, as_api: "ApplicationServiceApi") -> bool:
  351. """Sends this transaction using the provided AS API interface.
  352. Args:
  353. as_api: The API to use to send.
  354. Returns:
  355. True if the transaction was sent.
  356. """
  357. return await as_api.push_bulk(
  358. service=self.service,
  359. events=self.events,
  360. ephemeral=self.ephemeral,
  361. to_device_messages=self.to_device_messages,
  362. one_time_key_counts=self.one_time_key_counts,
  363. unused_fallback_keys=self.unused_fallback_keys,
  364. device_list_summary=self.device_list_summary,
  365. txn_id=self.id,
  366. )
  367. async def complete(self, store: "DataStore") -> None:
  368. """Completes this transaction as successful.
  369. Marks this transaction ID on the application service and removes the
  370. transaction contents from the database.
  371. Args:
  372. store: The database store to operate on.
  373. """
  374. await store.complete_appservice_txn(service=self.service, txn_id=self.id)