__init__.py 16 KB

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