__init__.py 16 KB

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