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