__init__.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 twisted.internet import defer
  18. from synapse.api.constants import EventTypes
  19. from synapse.types import GroupID, get_domain_from_id
  20. from synapse.util.caches.descriptors import cachedInlineCallbacks
  21. logger = logging.getLogger(__name__)
  22. class ApplicationServiceState(object):
  23. DOWN = "down"
  24. UP = "up"
  25. class AppServiceTransaction(object):
  26. """Represents an application service transaction."""
  27. def __init__(self, service, id, events):
  28. self.service = service
  29. self.id = id
  30. self.events = events
  31. def send(self, as_api):
  32. """Sends this transaction using the provided AS API interface.
  33. Args:
  34. as_api(ApplicationServiceApi): The API to use to send.
  35. Returns:
  36. A Deferred which resolves to True if the transaction was sent.
  37. """
  38. return as_api.push_bulk(
  39. service=self.service, events=self.events, txn_id=self.id
  40. )
  41. def complete(self, store):
  42. """Completes this transaction as successful.
  43. Marks this transaction ID on the application service and removes the
  44. transaction contents from the database.
  45. Args:
  46. store: The database store to operate on.
  47. Returns:
  48. A Deferred which resolves to True if the transaction was completed.
  49. """
  50. return store.complete_appservice_txn(service=self.service, txn_id=self.id)
  51. class ApplicationService(object):
  52. """Defines an application service. This definition is mostly what is
  53. provided to the /register AS API.
  54. Provides methods to check if this service is "interested" in events.
  55. """
  56. NS_USERS = "users"
  57. NS_ALIASES = "aliases"
  58. NS_ROOMS = "rooms"
  59. # The ordering here is important as it is used to map database values (which
  60. # are stored as ints representing the position in this list) to namespace
  61. # values.
  62. NS_LIST = [NS_USERS, NS_ALIASES, NS_ROOMS]
  63. def __init__(
  64. self,
  65. token,
  66. hostname,
  67. url=None,
  68. namespaces=None,
  69. hs_token=None,
  70. sender=None,
  71. id=None,
  72. protocols=None,
  73. rate_limited=True,
  74. ip_range_whitelist=None,
  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. if "|" in self.id:
  87. raise Exception("application service ID cannot contain '|' character")
  88. # .protocols is a publicly visible field
  89. if protocols:
  90. self.protocols = set(protocols)
  91. else:
  92. self.protocols = set()
  93. self.rate_limited = rate_limited
  94. def _check_namespaces(self, namespaces):
  95. # Sanity check that it is of the form:
  96. # {
  97. # users: [ {regex: "[A-z]+.*", exclusive: true}, ...],
  98. # aliases: [ {regex: "[A-z]+.*", exclusive: true}, ...],
  99. # rooms: [ {regex: "[A-z]+.*", exclusive: true}, ...],
  100. # }
  101. if not namespaces:
  102. namespaces = {}
  103. for ns in ApplicationService.NS_LIST:
  104. if ns not in namespaces:
  105. namespaces[ns] = []
  106. continue
  107. if type(namespaces[ns]) != list:
  108. raise ValueError("Bad namespace value for '%s'" % ns)
  109. for regex_obj in namespaces[ns]:
  110. if not isinstance(regex_obj, dict):
  111. raise ValueError("Expected dict regex for ns '%s'" % ns)
  112. if not isinstance(regex_obj.get("exclusive"), bool):
  113. raise ValueError("Expected bool for 'exclusive' in ns '%s'" % ns)
  114. group_id = regex_obj.get("group_id")
  115. if group_id:
  116. if not isinstance(group_id, str):
  117. raise ValueError(
  118. "Expected string for 'group_id' in ns '%s'" % ns
  119. )
  120. try:
  121. GroupID.from_string(group_id)
  122. except Exception:
  123. raise ValueError(
  124. "Expected valid group ID for 'group_id' in ns '%s'" % ns
  125. )
  126. if get_domain_from_id(group_id) != self.server_name:
  127. raise ValueError(
  128. "Expected 'group_id' to be this host in ns '%s'" % ns
  129. )
  130. regex = regex_obj.get("regex")
  131. if isinstance(regex, str):
  132. regex_obj["regex"] = re.compile(regex) # Pre-compile regex
  133. else:
  134. raise ValueError("Expected string for 'regex' in ns '%s'" % ns)
  135. return namespaces
  136. def _matches_regex(self, test_string, namespace_key):
  137. for regex_obj in self.namespaces[namespace_key]:
  138. if regex_obj["regex"].match(test_string):
  139. return regex_obj
  140. return None
  141. def _is_exclusive(self, ns_key, test_string):
  142. regex_obj = self._matches_regex(test_string, ns_key)
  143. if regex_obj:
  144. return regex_obj["exclusive"]
  145. return False
  146. @defer.inlineCallbacks
  147. def _matches_user(self, event, store):
  148. if not event:
  149. return False
  150. if self.is_interested_in_user(event.sender):
  151. return True
  152. # also check m.room.member state key
  153. if event.type == EventTypes.Member and self.is_interested_in_user(
  154. event.state_key
  155. ):
  156. return True
  157. if not store:
  158. return False
  159. does_match = yield self._matches_user_in_member_list(event.room_id, store)
  160. return does_match
  161. @cachedInlineCallbacks(num_args=1, cache_context=True)
  162. def _matches_user_in_member_list(self, room_id, store, cache_context):
  163. member_list = yield store.get_users_in_room(
  164. room_id, on_invalidate=cache_context.invalidate
  165. )
  166. # check joined member events
  167. for user_id in member_list:
  168. if self.is_interested_in_user(user_id):
  169. return True
  170. return False
  171. def _matches_room_id(self, event):
  172. if hasattr(event, "room_id"):
  173. return self.is_interested_in_room(event.room_id)
  174. return False
  175. @defer.inlineCallbacks
  176. def _matches_aliases(self, event, store):
  177. if not store or not event:
  178. return False
  179. alias_list = yield store.get_aliases_for_room(event.room_id)
  180. for alias in alias_list:
  181. if self.is_interested_in_alias(alias):
  182. return True
  183. return False
  184. @defer.inlineCallbacks
  185. def is_interested(self, event, store=None):
  186. """Check if this service is interested in this event.
  187. Args:
  188. event(Event): The event to check.
  189. store(DataStore)
  190. Returns:
  191. bool: True if this service would like to know about this event.
  192. """
  193. # Do cheap checks first
  194. if self._matches_room_id(event):
  195. return True
  196. if (yield self._matches_aliases(event, store)):
  197. return True
  198. if (yield self._matches_user(event, store)):
  199. return True
  200. return False
  201. def is_interested_in_user(self, user_id):
  202. return (
  203. self._matches_regex(user_id, ApplicationService.NS_USERS)
  204. or user_id == self.sender
  205. )
  206. def is_interested_in_alias(self, alias):
  207. return bool(self._matches_regex(alias, ApplicationService.NS_ALIASES))
  208. def is_interested_in_room(self, room_id):
  209. return bool(self._matches_regex(room_id, ApplicationService.NS_ROOMS))
  210. def is_exclusive_user(self, user_id):
  211. return (
  212. self._is_exclusive(ApplicationService.NS_USERS, user_id)
  213. or user_id == self.sender
  214. )
  215. def is_interested_in_protocol(self, protocol):
  216. return protocol in self.protocols
  217. def is_exclusive_alias(self, alias):
  218. return self._is_exclusive(ApplicationService.NS_ALIASES, alias)
  219. def is_exclusive_room(self, room_id):
  220. return self._is_exclusive(ApplicationService.NS_ROOMS, room_id)
  221. def get_exclusive_user_regexes(self):
  222. """Get the list of regexes used to determine if a user is exclusively
  223. registered by the AS
  224. """
  225. return [
  226. regex_obj["regex"]
  227. for regex_obj in self.namespaces[ApplicationService.NS_USERS]
  228. if regex_obj["exclusive"]
  229. ]
  230. def get_groups_for_user(self, user_id):
  231. """Get the groups that this user is associated with by this AS
  232. Args:
  233. user_id (str): The ID of the user.
  234. Returns:
  235. iterable[str]: an iterable that yields group_id strings.
  236. """
  237. return (
  238. regex_obj["group_id"]
  239. for regex_obj in self.namespaces[ApplicationService.NS_USERS]
  240. if "group_id" in regex_obj and regex_obj["regex"].match(user_id)
  241. )
  242. def is_rate_limited(self):
  243. return self.rate_limited
  244. def __str__(self):
  245. # copy dictionary and redact token fields so they don't get logged
  246. dict_copy = self.__dict__.copy()
  247. dict_copy["token"] = "<redacted>"
  248. dict_copy["hs_token"] = "<redacted>"
  249. return "ApplicationService: %s" % (dict_copy,)