__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2019 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import os
  17. from distutils.util import strtobool
  18. import six
  19. from unpaddedbase64 import encode_base64
  20. from synapse.api.errors import UnsupportedRoomVersionError
  21. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, EventFormatVersions
  22. from synapse.util.caches import intern_dict
  23. from synapse.util.frozenutils import freeze
  24. # Whether we should use frozen_dict in FrozenEvent. Using frozen_dicts prevents
  25. # bugs where we accidentally share e.g. signature dicts. However, converting a
  26. # dict to frozen_dicts is expensive.
  27. #
  28. # NOTE: This is overridden by the configuration by the Synapse worker apps, but
  29. # for the sake of tests, it is set here while it cannot be configured on the
  30. # homeserver object itself.
  31. USE_FROZEN_DICTS = strtobool(os.environ.get("SYNAPSE_USE_FROZEN_DICTS", "0"))
  32. class _EventInternalMetadata(object):
  33. def __init__(self, internal_metadata_dict):
  34. self.__dict__ = dict(internal_metadata_dict)
  35. def get_dict(self):
  36. return dict(self.__dict__)
  37. def is_outlier(self):
  38. return getattr(self, "outlier", False)
  39. def is_out_of_band_membership(self):
  40. """Whether this is an out of band membership, like an invite or an invite
  41. rejection. This is needed as those events are marked as outliers, but
  42. they still need to be processed as if they're new events (e.g. updating
  43. invite state in the database, relaying to clients, etc).
  44. """
  45. return getattr(self, "out_of_band_membership", False)
  46. def get_send_on_behalf_of(self):
  47. """Whether this server should send the event on behalf of another server.
  48. This is used by the federation "send_join" API to forward the initial join
  49. event for a server in the room.
  50. returns a str with the name of the server this event is sent on behalf of.
  51. """
  52. return getattr(self, "send_on_behalf_of", None)
  53. def need_to_check_redaction(self):
  54. """Whether the redaction event needs to be rechecked when fetching
  55. from the database.
  56. Starting in room v3 redaction events are accepted up front, and later
  57. checked to see if the redacter and redactee's domains match.
  58. If the sender of the redaction event is allowed to redact any event
  59. due to auth rules, then this will always return false.
  60. Returns:
  61. bool
  62. """
  63. return getattr(self, "recheck_redaction", False)
  64. def is_soft_failed(self):
  65. """Whether the event has been soft failed.
  66. Soft failed events should be handled as usual, except:
  67. 1. They should not go down sync or event streams, or generally
  68. sent to clients.
  69. 2. They should not be added to the forward extremities (and
  70. therefore not to current state).
  71. Returns:
  72. bool
  73. """
  74. return getattr(self, "soft_failed", False)
  75. def _event_dict_property(key):
  76. # We want to be able to use hasattr with the event dict properties.
  77. # However, (on python3) hasattr expects AttributeError to be raised. Hence,
  78. # we need to transform the KeyError into an AttributeError
  79. def getter(self):
  80. try:
  81. return self._event_dict[key]
  82. except KeyError:
  83. raise AttributeError(key)
  84. def setter(self, v):
  85. try:
  86. self._event_dict[key] = v
  87. except KeyError:
  88. raise AttributeError(key)
  89. def delete(self):
  90. try:
  91. del self._event_dict[key]
  92. except KeyError:
  93. raise AttributeError(key)
  94. return property(
  95. getter,
  96. setter,
  97. delete,
  98. )
  99. class EventBase(object):
  100. def __init__(self, event_dict, signatures={}, unsigned={},
  101. internal_metadata_dict={}, rejected_reason=None):
  102. self.signatures = signatures
  103. self.unsigned = unsigned
  104. self.rejected_reason = rejected_reason
  105. self._event_dict = event_dict
  106. self.internal_metadata = _EventInternalMetadata(
  107. internal_metadata_dict
  108. )
  109. auth_events = _event_dict_property("auth_events")
  110. depth = _event_dict_property("depth")
  111. content = _event_dict_property("content")
  112. hashes = _event_dict_property("hashes")
  113. origin = _event_dict_property("origin")
  114. origin_server_ts = _event_dict_property("origin_server_ts")
  115. prev_events = _event_dict_property("prev_events")
  116. redacts = _event_dict_property("redacts")
  117. room_id = _event_dict_property("room_id")
  118. sender = _event_dict_property("sender")
  119. user_id = _event_dict_property("sender")
  120. @property
  121. def membership(self):
  122. return self.content["membership"]
  123. def is_state(self):
  124. return hasattr(self, "state_key") and self.state_key is not None
  125. def get_dict(self):
  126. d = dict(self._event_dict)
  127. d.update({
  128. "signatures": self.signatures,
  129. "unsigned": dict(self.unsigned),
  130. })
  131. return d
  132. def get(self, key, default=None):
  133. return self._event_dict.get(key, default)
  134. def get_internal_metadata_dict(self):
  135. return self.internal_metadata.get_dict()
  136. def get_pdu_json(self, time_now=None):
  137. pdu_json = self.get_dict()
  138. if time_now is not None and "age_ts" in pdu_json["unsigned"]:
  139. age = time_now - pdu_json["unsigned"]["age_ts"]
  140. pdu_json.setdefault("unsigned", {})["age"] = int(age)
  141. del pdu_json["unsigned"]["age_ts"]
  142. # This may be a frozen event
  143. pdu_json["unsigned"].pop("redacted_because", None)
  144. return pdu_json
  145. def __set__(self, instance, value):
  146. raise AttributeError("Unrecognized attribute %s" % (instance,))
  147. def __getitem__(self, field):
  148. return self._event_dict[field]
  149. def __contains__(self, field):
  150. return field in self._event_dict
  151. def items(self):
  152. return list(self._event_dict.items())
  153. def keys(self):
  154. return six.iterkeys(self._event_dict)
  155. def prev_event_ids(self):
  156. """Returns the list of prev event IDs. The order matches the order
  157. specified in the event, though there is no meaning to it.
  158. Returns:
  159. list[str]: The list of event IDs of this event's prev_events
  160. """
  161. return [e for e, _ in self.prev_events]
  162. def auth_event_ids(self):
  163. """Returns the list of auth event IDs. The order matches the order
  164. specified in the event, though there is no meaning to it.
  165. Returns:
  166. list[str]: The list of event IDs of this event's auth_events
  167. """
  168. return [e for e, _ in self.auth_events]
  169. class FrozenEvent(EventBase):
  170. format_version = EventFormatVersions.V1 # All events of this type are V1
  171. def __init__(self, event_dict, internal_metadata_dict={}, rejected_reason=None):
  172. event_dict = dict(event_dict)
  173. # Signatures is a dict of dicts, and this is faster than doing a
  174. # copy.deepcopy
  175. signatures = {
  176. name: {sig_id: sig for sig_id, sig in sigs.items()}
  177. for name, sigs in event_dict.pop("signatures", {}).items()
  178. }
  179. unsigned = dict(event_dict.pop("unsigned", {}))
  180. # We intern these strings because they turn up a lot (especially when
  181. # caching).
  182. event_dict = intern_dict(event_dict)
  183. if USE_FROZEN_DICTS:
  184. frozen_dict = freeze(event_dict)
  185. else:
  186. frozen_dict = event_dict
  187. self.event_id = event_dict["event_id"]
  188. self.type = event_dict["type"]
  189. if "state_key" in event_dict:
  190. self.state_key = event_dict["state_key"]
  191. super(FrozenEvent, self).__init__(
  192. frozen_dict,
  193. signatures=signatures,
  194. unsigned=unsigned,
  195. internal_metadata_dict=internal_metadata_dict,
  196. rejected_reason=rejected_reason,
  197. )
  198. def __str__(self):
  199. return self.__repr__()
  200. def __repr__(self):
  201. return "<FrozenEvent event_id='%s', type='%s', state_key='%s'>" % (
  202. self.get("event_id", None),
  203. self.get("type", None),
  204. self.get("state_key", None),
  205. )
  206. class FrozenEventV2(EventBase):
  207. format_version = EventFormatVersions.V2 # All events of this type are V2
  208. def __init__(self, event_dict, internal_metadata_dict={}, rejected_reason=None):
  209. event_dict = dict(event_dict)
  210. # Signatures is a dict of dicts, and this is faster than doing a
  211. # copy.deepcopy
  212. signatures = {
  213. name: {sig_id: sig for sig_id, sig in sigs.items()}
  214. for name, sigs in event_dict.pop("signatures", {}).items()
  215. }
  216. assert "event_id" not in event_dict
  217. unsigned = dict(event_dict.pop("unsigned", {}))
  218. # We intern these strings because they turn up a lot (especially when
  219. # caching).
  220. event_dict = intern_dict(event_dict)
  221. if USE_FROZEN_DICTS:
  222. frozen_dict = freeze(event_dict)
  223. else:
  224. frozen_dict = event_dict
  225. self._event_id = None
  226. self.type = event_dict["type"]
  227. if "state_key" in event_dict:
  228. self.state_key = event_dict["state_key"]
  229. super(FrozenEventV2, self).__init__(
  230. frozen_dict,
  231. signatures=signatures,
  232. unsigned=unsigned,
  233. internal_metadata_dict=internal_metadata_dict,
  234. rejected_reason=rejected_reason,
  235. )
  236. @property
  237. def event_id(self):
  238. # We have to import this here as otherwise we get an import loop which
  239. # is hard to break.
  240. from synapse.crypto.event_signing import compute_event_reference_hash
  241. if self._event_id:
  242. return self._event_id
  243. self._event_id = "$" + encode_base64(compute_event_reference_hash(self)[1])
  244. return self._event_id
  245. def prev_event_ids(self):
  246. """Returns the list of prev event IDs. The order matches the order
  247. specified in the event, though there is no meaning to it.
  248. Returns:
  249. list[str]: The list of event IDs of this event's prev_events
  250. """
  251. return self.prev_events
  252. def auth_event_ids(self):
  253. """Returns the list of auth event IDs. The order matches the order
  254. specified in the event, though there is no meaning to it.
  255. Returns:
  256. list[str]: The list of event IDs of this event's auth_events
  257. """
  258. return self.auth_events
  259. def __str__(self):
  260. return self.__repr__()
  261. def __repr__(self):
  262. return "<%s event_id='%s', type='%s', state_key='%s'>" % (
  263. self.__class__.__name__,
  264. self.event_id,
  265. self.get("type", None),
  266. self.get("state_key", None),
  267. )
  268. class FrozenEventV3(FrozenEventV2):
  269. """FrozenEventV3, which differs from FrozenEventV2 only in the event_id format"""
  270. format_version = EventFormatVersions.V3 # All events of this type are V3
  271. @property
  272. def event_id(self):
  273. # We have to import this here as otherwise we get an import loop which
  274. # is hard to break.
  275. from synapse.crypto.event_signing import compute_event_reference_hash
  276. if self._event_id:
  277. return self._event_id
  278. self._event_id = "$" + encode_base64(
  279. compute_event_reference_hash(self)[1], urlsafe=True
  280. )
  281. return self._event_id
  282. def room_version_to_event_format(room_version):
  283. """Converts a room version string to the event format
  284. Args:
  285. room_version (str)
  286. Returns:
  287. int
  288. Raises:
  289. UnsupportedRoomVersionError if the room version is unknown
  290. """
  291. v = KNOWN_ROOM_VERSIONS.get(room_version)
  292. if not v:
  293. # this can happen if support is withdrawn for a room version
  294. raise UnsupportedRoomVersionError()
  295. return v.event_format
  296. def event_type_from_format_version(format_version):
  297. """Returns the python type to use to construct an Event object for the
  298. given event format version.
  299. Args:
  300. format_version (int): The event format version
  301. Returns:
  302. type: A type that can be initialized as per the initializer of
  303. `FrozenEvent`
  304. """
  305. if format_version == EventFormatVersions.V1:
  306. return FrozenEvent
  307. elif format_version == EventFormatVersions.V2:
  308. return FrozenEventV2
  309. elif format_version == EventFormatVersions.V3:
  310. return FrozenEventV3
  311. else:
  312. raise Exception(
  313. "No event format %r" % (format_version,)
  314. )