__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket 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 TYPE_CHECKING, Iterable, List, Match, Optional
  18. from synapse.api.constants import EventTypes
  19. from synapse.events import EventBase
  20. from synapse.types import GroupID, JsonDict, UserID, get_domain_from_id
  21. from synapse.util.caches.descriptors import _CacheContext, cached
  22. if TYPE_CHECKING:
  23. from synapse.appservice.api import ApplicationServiceApi
  24. from synapse.storage.databases.main import DataStore
  25. logger = logging.getLogger(__name__)
  26. class ApplicationServiceState:
  27. DOWN = "down"
  28. UP = "up"
  29. class ApplicationService:
  30. """Defines an application service. This definition is mostly what is
  31. provided to the /register AS API.
  32. Provides methods to check if this service is "interested" in events.
  33. """
  34. NS_USERS = "users"
  35. NS_ALIASES = "aliases"
  36. NS_ROOMS = "rooms"
  37. # The ordering here is important as it is used to map database values (which
  38. # are stored as ints representing the position in this list) to namespace
  39. # values.
  40. NS_LIST = [NS_USERS, NS_ALIASES, NS_ROOMS]
  41. def __init__(
  42. self,
  43. token,
  44. hostname,
  45. id,
  46. sender,
  47. url=None,
  48. namespaces=None,
  49. hs_token=None,
  50. protocols=None,
  51. rate_limited=True,
  52. ip_range_whitelist=None,
  53. supports_ephemeral=False,
  54. ):
  55. self.token = token
  56. self.url = (
  57. url.rstrip("/") if isinstance(url, str) else None
  58. ) # url must not end with a slash
  59. self.hs_token = hs_token
  60. self.sender = sender
  61. self.server_name = hostname
  62. self.namespaces = self._check_namespaces(namespaces)
  63. self.id = id
  64. self.ip_range_whitelist = ip_range_whitelist
  65. self.supports_ephemeral = supports_ephemeral
  66. if "|" in self.id:
  67. raise Exception("application service ID cannot contain '|' character")
  68. # .protocols is a publicly visible field
  69. if protocols:
  70. self.protocols = set(protocols)
  71. else:
  72. self.protocols = set()
  73. self.rate_limited = rate_limited
  74. def _check_namespaces(self, namespaces):
  75. # Sanity check that it is of the form:
  76. # {
  77. # users: [ {regex: "[A-z]+.*", exclusive: true}, ...],
  78. # aliases: [ {regex: "[A-z]+.*", exclusive: true}, ...],
  79. # rooms: [ {regex: "[A-z]+.*", exclusive: true}, ...],
  80. # }
  81. if not namespaces:
  82. namespaces = {}
  83. for ns in ApplicationService.NS_LIST:
  84. if ns not in namespaces:
  85. namespaces[ns] = []
  86. continue
  87. if type(namespaces[ns]) != list:
  88. raise ValueError("Bad namespace value for '%s'" % ns)
  89. for regex_obj in namespaces[ns]:
  90. if not isinstance(regex_obj, dict):
  91. raise ValueError("Expected dict regex for ns '%s'" % ns)
  92. if not isinstance(regex_obj.get("exclusive"), bool):
  93. raise ValueError("Expected bool for 'exclusive' in ns '%s'" % ns)
  94. group_id = regex_obj.get("group_id")
  95. if group_id:
  96. if not isinstance(group_id, str):
  97. raise ValueError(
  98. "Expected string for 'group_id' in ns '%s'" % ns
  99. )
  100. try:
  101. GroupID.from_string(group_id)
  102. except Exception:
  103. raise ValueError(
  104. "Expected valid group ID for 'group_id' in ns '%s'" % ns
  105. )
  106. if get_domain_from_id(group_id) != self.server_name:
  107. raise ValueError(
  108. "Expected 'group_id' to be this host in ns '%s'" % ns
  109. )
  110. regex = regex_obj.get("regex")
  111. if isinstance(regex, str):
  112. regex_obj["regex"] = re.compile(regex) # Pre-compile regex
  113. else:
  114. raise ValueError("Expected string for 'regex' in ns '%s'" % ns)
  115. return namespaces
  116. def _matches_regex(self, test_string: str, namespace_key: str) -> Optional[Match]:
  117. for regex_obj in self.namespaces[namespace_key]:
  118. if regex_obj["regex"].match(test_string):
  119. return regex_obj
  120. return None
  121. def _is_exclusive(self, ns_key: str, test_string: str) -> bool:
  122. regex_obj = self._matches_regex(test_string, ns_key)
  123. if regex_obj:
  124. return regex_obj["exclusive"]
  125. return False
  126. async def _matches_user(
  127. self, event: Optional[EventBase], store: Optional["DataStore"] = None
  128. ) -> bool:
  129. if not event:
  130. return False
  131. if self.is_interested_in_user(event.sender):
  132. return True
  133. # also check m.room.member state key
  134. if event.type == EventTypes.Member and self.is_interested_in_user(
  135. event.state_key
  136. ):
  137. return True
  138. if not store:
  139. return False
  140. does_match = await self.matches_user_in_member_list(event.room_id, store)
  141. return does_match
  142. @cached(num_args=1, cache_context=True)
  143. async def matches_user_in_member_list(
  144. self, room_id: str, store: "DataStore", cache_context: _CacheContext,
  145. ) -> bool:
  146. """Check if this service is interested a room based upon it's membership
  147. Args:
  148. room_id: The room to check.
  149. store: The datastore to query.
  150. Returns:
  151. True if this service would like to know about this room.
  152. """
  153. member_list = await store.get_users_in_room(
  154. room_id, on_invalidate=cache_context.invalidate
  155. )
  156. # check joined member events
  157. for user_id in member_list:
  158. if self.is_interested_in_user(user_id):
  159. return True
  160. return False
  161. def _matches_room_id(self, event: EventBase) -> bool:
  162. if hasattr(event, "room_id"):
  163. return self.is_interested_in_room(event.room_id)
  164. return False
  165. async def _matches_aliases(
  166. self, event: EventBase, store: Optional["DataStore"] = None
  167. ) -> bool:
  168. if not store or not event:
  169. return False
  170. alias_list = await store.get_aliases_for_room(event.room_id)
  171. for alias in alias_list:
  172. if self.is_interested_in_alias(alias):
  173. return True
  174. return False
  175. async def is_interested(
  176. self, event: EventBase, store: Optional["DataStore"] = None
  177. ) -> bool:
  178. """Check if this service is interested in this event.
  179. Args:
  180. event: The event to check.
  181. store: The datastore to query.
  182. Returns:
  183. True if this service would like to know about this event.
  184. """
  185. # Do cheap checks first
  186. if self._matches_room_id(event):
  187. return True
  188. # This will check the namespaces first before
  189. # checking the store, so should be run before _matches_aliases
  190. if await self._matches_user(event, store):
  191. return True
  192. # This will check the store, so should be run last
  193. if await self._matches_aliases(event, store):
  194. return True
  195. return False
  196. @cached(num_args=1)
  197. async def is_interested_in_presence(
  198. self, user_id: UserID, store: "DataStore"
  199. ) -> bool:
  200. """Check if this service is interested a user's presence
  201. Args:
  202. user_id: The user to check.
  203. store: The datastore to query.
  204. Returns:
  205. True if this service would like to know about presence for this user.
  206. """
  207. # Find all the rooms the sender is in
  208. if self.is_interested_in_user(user_id.to_string()):
  209. return True
  210. room_ids = await store.get_rooms_for_user(user_id.to_string())
  211. # Then find out if the appservice is interested in any of those rooms
  212. for room_id in room_ids:
  213. if await self.matches_user_in_member_list(room_id, store):
  214. return True
  215. return False
  216. def is_interested_in_user(self, user_id: str) -> bool:
  217. return (
  218. bool(self._matches_regex(user_id, ApplicationService.NS_USERS))
  219. or user_id == self.sender
  220. )
  221. def is_interested_in_alias(self, alias: str) -> bool:
  222. return bool(self._matches_regex(alias, ApplicationService.NS_ALIASES))
  223. def is_interested_in_room(self, room_id: str) -> bool:
  224. return bool(self._matches_regex(room_id, ApplicationService.NS_ROOMS))
  225. def is_exclusive_user(self, user_id: str) -> bool:
  226. return (
  227. self._is_exclusive(ApplicationService.NS_USERS, user_id)
  228. or user_id == self.sender
  229. )
  230. def is_interested_in_protocol(self, protocol: str) -> bool:
  231. return protocol in self.protocols
  232. def is_exclusive_alias(self, alias: str) -> bool:
  233. return self._is_exclusive(ApplicationService.NS_ALIASES, alias)
  234. def is_exclusive_room(self, room_id: str) -> bool:
  235. return self._is_exclusive(ApplicationService.NS_ROOMS, room_id)
  236. def get_exclusive_user_regexes(self):
  237. """Get the list of regexes used to determine if a user is exclusively
  238. registered by the AS
  239. """
  240. return [
  241. regex_obj["regex"]
  242. for regex_obj in self.namespaces[ApplicationService.NS_USERS]
  243. if regex_obj["exclusive"]
  244. ]
  245. def get_groups_for_user(self, user_id: str) -> Iterable[str]:
  246. """Get the groups that this user is associated with by this AS
  247. Args:
  248. user_id: The ID of the user.
  249. Returns:
  250. An iterable that yields group_id strings.
  251. """
  252. return (
  253. regex_obj["group_id"]
  254. for regex_obj in self.namespaces[ApplicationService.NS_USERS]
  255. if "group_id" in regex_obj and regex_obj["regex"].match(user_id)
  256. )
  257. def is_rate_limited(self) -> bool:
  258. return self.rate_limited
  259. def __str__(self):
  260. # copy dictionary and redact token fields so they don't get logged
  261. dict_copy = self.__dict__.copy()
  262. dict_copy["token"] = "<redacted>"
  263. dict_copy["hs_token"] = "<redacted>"
  264. return "ApplicationService: %s" % (dict_copy,)
  265. class AppServiceTransaction:
  266. """Represents an application service transaction."""
  267. def __init__(
  268. self,
  269. service: ApplicationService,
  270. id: int,
  271. events: List[EventBase],
  272. ephemeral: List[JsonDict],
  273. ):
  274. self.service = service
  275. self.id = id
  276. self.events = events
  277. self.ephemeral = ephemeral
  278. async def send(self, as_api: "ApplicationServiceApi") -> bool:
  279. """Sends this transaction using the provided AS API interface.
  280. Args:
  281. as_api: The API to use to send.
  282. Returns:
  283. True if the transaction was sent.
  284. """
  285. return await as_api.push_bulk(
  286. service=self.service,
  287. events=self.events,
  288. ephemeral=self.ephemeral,
  289. txn_id=self.id,
  290. )
  291. async def complete(self, store: "DataStore") -> None:
  292. """Completes this transaction as successful.
  293. Marks this transaction ID on the application service and removes the
  294. transaction contents from the database.
  295. Args:
  296. store: The database store to operate on.
  297. """
  298. await store.complete_appservice_txn(service=self.service, txn_id=self.id)