You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

521 lines
17 KiB

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