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.
 
 
 
 
 
 

363 lines
12 KiB

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