__init__.py 10 KB

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