__init__.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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 collections.abc
  18. import os
  19. from typing import (
  20. TYPE_CHECKING,
  21. Any,
  22. Dict,
  23. Generic,
  24. Iterable,
  25. List,
  26. Optional,
  27. Sequence,
  28. Tuple,
  29. Type,
  30. TypeVar,
  31. Union,
  32. overload,
  33. )
  34. import attr
  35. from typing_extensions import Literal
  36. from unpaddedbase64 import encode_base64
  37. from synapse.api.constants import RelationTypes
  38. from synapse.api.room_versions import EventFormatVersions, RoomVersion, RoomVersions
  39. from synapse.types import JsonDict, RoomStreamToken, StrCollection
  40. from synapse.util.caches import intern_dict
  41. from synapse.util.frozenutils import freeze
  42. from synapse.util.stringutils import strtobool
  43. if TYPE_CHECKING:
  44. from synapse.events.builder import EventBuilder
  45. # Whether we should use frozen_dict in FrozenEvent. Using frozen_dicts prevents
  46. # bugs where we accidentally share e.g. signature dicts. However, converting a
  47. # dict to frozen_dicts is expensive.
  48. #
  49. # NOTE: This is overridden by the configuration by the Synapse worker apps, but
  50. # for the sake of tests, it is set here while it cannot be configured on the
  51. # homeserver object itself.
  52. USE_FROZEN_DICTS = strtobool(os.environ.get("SYNAPSE_USE_FROZEN_DICTS", "0"))
  53. T = TypeVar("T")
  54. # DictProperty (and DefaultDictProperty) require the classes they're used with to
  55. # have a _dict property to pull properties from.
  56. #
  57. # TODO _DictPropertyInstance should not include EventBuilder but due to
  58. # https://github.com/python/mypy/issues/5570 it thinks the DictProperty and
  59. # DefaultDictProperty get applied to EventBuilder when it is in a Union with
  60. # EventBase. This is the least invasive hack to get mypy to comply.
  61. #
  62. # Note that DictProperty/DefaultDictProperty cannot actually be used with
  63. # EventBuilder as it lacks a _dict property.
  64. _DictPropertyInstance = Union["_EventInternalMetadata", "EventBase", "EventBuilder"]
  65. class DictProperty(Generic[T]):
  66. """An object property which delegates to the `_dict` within its parent object."""
  67. __slots__ = ["key"]
  68. def __init__(self, key: str):
  69. self.key = key
  70. @overload
  71. def __get__(
  72. self,
  73. instance: Literal[None],
  74. owner: Optional[Type[_DictPropertyInstance]] = None,
  75. ) -> "DictProperty":
  76. ...
  77. @overload
  78. def __get__(
  79. self,
  80. instance: _DictPropertyInstance,
  81. owner: Optional[Type[_DictPropertyInstance]] = None,
  82. ) -> T:
  83. ...
  84. def __get__(
  85. self,
  86. instance: Optional[_DictPropertyInstance],
  87. owner: Optional[Type[_DictPropertyInstance]] = None,
  88. ) -> Union[T, "DictProperty"]:
  89. # if the property is accessed as a class property rather than an instance
  90. # property, return the property itself rather than the value
  91. if instance is None:
  92. return self
  93. try:
  94. assert isinstance(instance, (EventBase, _EventInternalMetadata))
  95. return instance._dict[self.key]
  96. except KeyError as e1:
  97. # We want this to look like a regular attribute error (mostly so that
  98. # hasattr() works correctly), so we convert the KeyError into an
  99. # AttributeError.
  100. #
  101. # To exclude the KeyError from the traceback, we explicitly
  102. # 'raise from e1.__context__' (which is better than 'raise from None',
  103. # because that would omit any *earlier* exceptions).
  104. #
  105. raise AttributeError(
  106. "'%s' has no '%s' property" % (type(instance), self.key)
  107. ) from e1.__context__
  108. def __set__(self, instance: _DictPropertyInstance, v: T) -> None:
  109. assert isinstance(instance, (EventBase, _EventInternalMetadata))
  110. instance._dict[self.key] = v
  111. def __delete__(self, instance: _DictPropertyInstance) -> None:
  112. assert isinstance(instance, (EventBase, _EventInternalMetadata))
  113. try:
  114. del instance._dict[self.key]
  115. except KeyError as e1:
  116. raise AttributeError(
  117. "'%s' has no '%s' property" % (type(instance), self.key)
  118. ) from e1.__context__
  119. class DefaultDictProperty(DictProperty, Generic[T]):
  120. """An extension of DictProperty which provides a default if the property is
  121. not present in the parent's _dict.
  122. Note that this means that hasattr() on the property always returns True.
  123. """
  124. __slots__ = ["default"]
  125. def __init__(self, key: str, default: T):
  126. super().__init__(key)
  127. self.default = default
  128. @overload
  129. def __get__(
  130. self,
  131. instance: Literal[None],
  132. owner: Optional[Type[_DictPropertyInstance]] = None,
  133. ) -> "DefaultDictProperty":
  134. ...
  135. @overload
  136. def __get__(
  137. self,
  138. instance: _DictPropertyInstance,
  139. owner: Optional[Type[_DictPropertyInstance]] = None,
  140. ) -> T:
  141. ...
  142. def __get__(
  143. self,
  144. instance: Optional[_DictPropertyInstance],
  145. owner: Optional[Type[_DictPropertyInstance]] = None,
  146. ) -> Union[T, "DefaultDictProperty"]:
  147. if instance is None:
  148. return self
  149. assert isinstance(instance, (EventBase, _EventInternalMetadata))
  150. return instance._dict.get(self.key, self.default)
  151. class _EventInternalMetadata:
  152. __slots__ = ["_dict", "stream_ordering", "outlier"]
  153. def __init__(self, internal_metadata_dict: JsonDict):
  154. # we have to copy the dict, because it turns out that the same dict is
  155. # reused. TODO: fix that
  156. self._dict = dict(internal_metadata_dict)
  157. # the stream ordering of this event. None, until it has been persisted.
  158. self.stream_ordering: Optional[int] = None
  159. # whether this event is an outlier (ie, whether we have the state at that point
  160. # in the DAG)
  161. self.outlier = False
  162. out_of_band_membership: DictProperty[bool] = DictProperty("out_of_band_membership")
  163. send_on_behalf_of: DictProperty[str] = DictProperty("send_on_behalf_of")
  164. recheck_redaction: DictProperty[bool] = DictProperty("recheck_redaction")
  165. soft_failed: DictProperty[bool] = DictProperty("soft_failed")
  166. proactively_send: DictProperty[bool] = DictProperty("proactively_send")
  167. redacted: DictProperty[bool] = DictProperty("redacted")
  168. txn_id: DictProperty[str] = DictProperty("txn_id")
  169. """The transaction ID, if it was set when the event was created."""
  170. token_id: DictProperty[int] = DictProperty("token_id")
  171. """The access token ID of the user who sent this event, if any."""
  172. device_id: DictProperty[str] = DictProperty("device_id")
  173. """The device ID of the user who sent this event, if any."""
  174. # XXX: These are set by StreamWorkerStore._set_before_and_after.
  175. # I'm pretty sure that these are never persisted to the database, so shouldn't
  176. # be here
  177. before: DictProperty[RoomStreamToken] = DictProperty("before")
  178. after: DictProperty[RoomStreamToken] = DictProperty("after")
  179. order: DictProperty[Tuple[int, int]] = DictProperty("order")
  180. def get_dict(self) -> JsonDict:
  181. return dict(self._dict)
  182. def is_outlier(self) -> bool:
  183. return self.outlier
  184. def is_out_of_band_membership(self) -> bool:
  185. """Whether this event is an out-of-band membership.
  186. OOB memberships are a special case of outlier events: they are membership events
  187. for federated rooms that we aren't full members of. Examples include invites
  188. received over federation, and rejections for such invites.
  189. The concept of an OOB membership is needed because these events need to be
  190. processed as if they're new regular events (e.g. updating membership state in
  191. the database, relaying to clients via /sync, etc) despite being outliers.
  192. See also https://matrix-org.github.io/synapse/develop/development/room-dag-concepts.html#out-of-band-membership-events.
  193. (Added in synapse 0.99.0, so may be unreliable for events received before that)
  194. """
  195. return self._dict.get("out_of_band_membership", False)
  196. def get_send_on_behalf_of(self) -> Optional[str]:
  197. """Whether this server should send the event on behalf of another server.
  198. This is used by the federation "send_join" API to forward the initial join
  199. event for a server in the room.
  200. returns a str with the name of the server this event is sent on behalf of.
  201. """
  202. return self._dict.get("send_on_behalf_of")
  203. def need_to_check_redaction(self) -> bool:
  204. """Whether the redaction event needs to be rechecked when fetching
  205. from the database.
  206. Starting in room v3 redaction events are accepted up front, and later
  207. checked to see if the redacter and redactee's domains match.
  208. If the sender of the redaction event is allowed to redact any event
  209. due to auth rules, then this will always return false.
  210. """
  211. return self._dict.get("recheck_redaction", False)
  212. def is_soft_failed(self) -> bool:
  213. """Whether the event has been soft failed.
  214. Soft failed events should be handled as usual, except:
  215. 1. They should not go down sync or event streams, or generally
  216. sent to clients.
  217. 2. They should not be added to the forward extremities (and
  218. therefore not to current state).
  219. """
  220. return self._dict.get("soft_failed", False)
  221. def should_proactively_send(self) -> bool:
  222. """Whether the event, if ours, should be sent to other clients and
  223. servers.
  224. This is used for sending dummy events internally. Servers and clients
  225. can still explicitly fetch the event.
  226. """
  227. return self._dict.get("proactively_send", True)
  228. def is_redacted(self) -> bool:
  229. """Whether the event has been redacted.
  230. This is used for efficiently checking whether an event has been
  231. marked as redacted without needing to make another database call.
  232. """
  233. return self._dict.get("redacted", False)
  234. def is_notifiable(self) -> bool:
  235. """Whether this event can trigger a push notification"""
  236. return not self.is_outlier() or self.is_out_of_band_membership()
  237. class EventBase(metaclass=abc.ABCMeta):
  238. @property
  239. @abc.abstractmethod
  240. def format_version(self) -> int:
  241. """The EventFormatVersion implemented by this event"""
  242. ...
  243. def __init__(
  244. self,
  245. event_dict: JsonDict,
  246. room_version: RoomVersion,
  247. signatures: Dict[str, Dict[str, str]],
  248. unsigned: JsonDict,
  249. internal_metadata_dict: JsonDict,
  250. rejected_reason: Optional[str],
  251. ):
  252. assert room_version.event_format == self.format_version
  253. self.room_version = room_version
  254. self.signatures = signatures
  255. self.unsigned = unsigned
  256. self.rejected_reason = rejected_reason
  257. self._dict = event_dict
  258. self.internal_metadata = _EventInternalMetadata(internal_metadata_dict)
  259. depth: DictProperty[int] = DictProperty("depth")
  260. content: DictProperty[JsonDict] = DictProperty("content")
  261. hashes: DictProperty[Dict[str, str]] = DictProperty("hashes")
  262. origin: DictProperty[str] = DictProperty("origin")
  263. origin_server_ts: DictProperty[int] = DictProperty("origin_server_ts")
  264. room_id: DictProperty[str] = DictProperty("room_id")
  265. sender: DictProperty[str] = DictProperty("sender")
  266. # TODO state_key should be Optional[str]. This is generally asserted in Synapse
  267. # by calling is_state() first (which ensures it is not None), but it is hard (not possible?)
  268. # to properly annotate that calling is_state() asserts that state_key exists
  269. # and is non-None. It would be better to replace such direct references with
  270. # get_state_key() (and a check for None).
  271. state_key: DictProperty[str] = DictProperty("state_key")
  272. type: DictProperty[str] = DictProperty("type")
  273. user_id: DictProperty[str] = DictProperty("sender")
  274. @property
  275. def event_id(self) -> str:
  276. raise NotImplementedError()
  277. @property
  278. def membership(self) -> str:
  279. return self.content["membership"]
  280. @property
  281. def redacts(self) -> Optional[str]:
  282. """MSC2176 moved the redacts field into the content."""
  283. if self.room_version.updated_redaction_rules:
  284. return self.content.get("redacts")
  285. return self.get("redacts")
  286. def is_state(self) -> bool:
  287. return self.get_state_key() is not None
  288. def get_state_key(self) -> Optional[str]:
  289. """Get the state key of this event, or None if it's not a state event"""
  290. return self._dict.get("state_key")
  291. def get_dict(self) -> JsonDict:
  292. d = dict(self._dict)
  293. d.update({"signatures": self.signatures, "unsigned": dict(self.unsigned)})
  294. return d
  295. def get(self, key: str, default: Optional[Any] = None) -> Any:
  296. return self._dict.get(key, default)
  297. def get_internal_metadata_dict(self) -> JsonDict:
  298. return self.internal_metadata.get_dict()
  299. def get_pdu_json(self, time_now: Optional[int] = None) -> JsonDict:
  300. pdu_json = self.get_dict()
  301. if time_now is not None and "age_ts" in pdu_json["unsigned"]:
  302. age = time_now - pdu_json["unsigned"]["age_ts"]
  303. pdu_json.setdefault("unsigned", {})["age"] = int(age)
  304. del pdu_json["unsigned"]["age_ts"]
  305. # This may be a frozen event
  306. pdu_json["unsigned"].pop("redacted_because", None)
  307. return pdu_json
  308. def get_templated_pdu_json(self) -> JsonDict:
  309. """
  310. Return a JSON object suitable for a templated event, as used in the
  311. make_{join,leave,knock} workflow.
  312. """
  313. # By using _dict directly we don't pull in signatures/unsigned.
  314. template_json = dict(self._dict)
  315. # The hashes (similar to the signature) need to be recalculated by the
  316. # joining/leaving/knocking server after (potentially) modifying the
  317. # event.
  318. template_json.pop("hashes")
  319. return template_json
  320. def __getitem__(self, field: str) -> Optional[Any]:
  321. return self._dict[field]
  322. def __contains__(self, field: str) -> bool:
  323. return field in self._dict
  324. def items(self) -> List[Tuple[str, Optional[Any]]]:
  325. return list(self._dict.items())
  326. def keys(self) -> Iterable[str]:
  327. return self._dict.keys()
  328. def prev_event_ids(self) -> Sequence[str]:
  329. """Returns the list of prev event IDs. The order matches the order
  330. specified in the event, though there is no meaning to it.
  331. Returns:
  332. The list of event IDs of this event's prev_events
  333. """
  334. return [e for e, _ in self._dict["prev_events"]]
  335. def auth_event_ids(self) -> StrCollection:
  336. """Returns the list of auth event IDs. The order matches the order
  337. specified in the event, though there is no meaning to it.
  338. Returns:
  339. The list of event IDs of this event's auth_events
  340. """
  341. return [e for e, _ in self._dict["auth_events"]]
  342. def freeze(self) -> None:
  343. """'Freeze' the event dict, so it cannot be modified by accident"""
  344. # this will be a no-op if the event dict is already frozen.
  345. self._dict = freeze(self._dict)
  346. def __str__(self) -> str:
  347. return self.__repr__()
  348. def __repr__(self) -> str:
  349. rejection = f"REJECTED={self.rejected_reason}, " if self.rejected_reason else ""
  350. return (
  351. f"<{self.__class__.__name__} "
  352. f"{rejection}"
  353. f"event_id={self.event_id}, "
  354. f"type={self.get('type')}, "
  355. f"state_key={self.get('state_key')}, "
  356. f"outlier={self.internal_metadata.is_outlier()}"
  357. ">"
  358. )
  359. class FrozenEvent(EventBase):
  360. format_version = EventFormatVersions.ROOM_V1_V2 # All events of this type are V1
  361. def __init__(
  362. self,
  363. event_dict: JsonDict,
  364. room_version: RoomVersion,
  365. internal_metadata_dict: Optional[JsonDict] = None,
  366. rejected_reason: Optional[str] = None,
  367. ):
  368. internal_metadata_dict = internal_metadata_dict or {}
  369. event_dict = dict(event_dict)
  370. # Signatures is a dict of dicts, and this is faster than doing a
  371. # copy.deepcopy
  372. signatures = {
  373. name: dict(sigs.items())
  374. for name, sigs in event_dict.pop("signatures", {}).items()
  375. }
  376. unsigned = dict(event_dict.pop("unsigned", {}))
  377. # We intern these strings because they turn up a lot (especially when
  378. # caching).
  379. event_dict = intern_dict(event_dict)
  380. if USE_FROZEN_DICTS:
  381. frozen_dict = freeze(event_dict)
  382. else:
  383. frozen_dict = event_dict
  384. self._event_id = event_dict["event_id"]
  385. super().__init__(
  386. frozen_dict,
  387. room_version=room_version,
  388. signatures=signatures,
  389. unsigned=unsigned,
  390. internal_metadata_dict=internal_metadata_dict,
  391. rejected_reason=rejected_reason,
  392. )
  393. @property
  394. def event_id(self) -> str:
  395. return self._event_id
  396. class FrozenEventV2(EventBase):
  397. format_version = EventFormatVersions.ROOM_V3 # All events of this type are V2
  398. def __init__(
  399. self,
  400. event_dict: JsonDict,
  401. room_version: RoomVersion,
  402. internal_metadata_dict: Optional[JsonDict] = None,
  403. rejected_reason: Optional[str] = None,
  404. ):
  405. internal_metadata_dict = internal_metadata_dict or {}
  406. event_dict = dict(event_dict)
  407. # Signatures is a dict of dicts, and this is faster than doing a
  408. # copy.deepcopy
  409. signatures = {
  410. name: dict(sigs.items())
  411. for name, sigs in event_dict.pop("signatures", {}).items()
  412. }
  413. assert "event_id" not in event_dict
  414. unsigned = dict(event_dict.pop("unsigned", {}))
  415. # We intern these strings because they turn up a lot (especially when
  416. # caching).
  417. event_dict = intern_dict(event_dict)
  418. if USE_FROZEN_DICTS:
  419. frozen_dict = freeze(event_dict)
  420. else:
  421. frozen_dict = event_dict
  422. self._event_id: Optional[str] = None
  423. super().__init__(
  424. frozen_dict,
  425. room_version=room_version,
  426. signatures=signatures,
  427. unsigned=unsigned,
  428. internal_metadata_dict=internal_metadata_dict,
  429. rejected_reason=rejected_reason,
  430. )
  431. @property
  432. def event_id(self) -> str:
  433. # We have to import this here as otherwise we get an import loop which
  434. # is hard to break.
  435. from synapse.crypto.event_signing import compute_event_reference_hash
  436. if self._event_id:
  437. return self._event_id
  438. self._event_id = "$" + encode_base64(compute_event_reference_hash(self)[1])
  439. return self._event_id
  440. def prev_event_ids(self) -> Sequence[str]:
  441. """Returns the list of prev event IDs. The order matches the order
  442. specified in the event, though there is no meaning to it.
  443. Returns:
  444. The list of event IDs of this event's prev_events
  445. """
  446. return self._dict["prev_events"]
  447. def auth_event_ids(self) -> StrCollection:
  448. """Returns the list of auth event IDs. The order matches the order
  449. specified in the event, though there is no meaning to it.
  450. Returns:
  451. The list of event IDs of this event's auth_events
  452. """
  453. return self._dict["auth_events"]
  454. class FrozenEventV3(FrozenEventV2):
  455. """FrozenEventV3, which differs from FrozenEventV2 only in the event_id format"""
  456. format_version = EventFormatVersions.ROOM_V4_PLUS # All events of this type are V3
  457. @property
  458. def event_id(self) -> str:
  459. # We have to import this here as otherwise we get an import loop which
  460. # is hard to break.
  461. from synapse.crypto.event_signing import compute_event_reference_hash
  462. if self._event_id:
  463. return self._event_id
  464. self._event_id = "$" + encode_base64(
  465. compute_event_reference_hash(self)[1], urlsafe=True
  466. )
  467. return self._event_id
  468. def _event_type_from_format_version(
  469. format_version: int,
  470. ) -> Type[Union[FrozenEvent, FrozenEventV2, FrozenEventV3]]:
  471. """Returns the python type to use to construct an Event object for the
  472. given event format version.
  473. Args:
  474. format_version: The event format version
  475. Returns:
  476. A type that can be initialized as per the initializer of `FrozenEvent`
  477. """
  478. if format_version == EventFormatVersions.ROOM_V1_V2:
  479. return FrozenEvent
  480. elif format_version == EventFormatVersions.ROOM_V3:
  481. return FrozenEventV2
  482. elif format_version == EventFormatVersions.ROOM_V4_PLUS:
  483. return FrozenEventV3
  484. else:
  485. raise Exception("No event format %r" % (format_version,))
  486. def make_event_from_dict(
  487. event_dict: JsonDict,
  488. room_version: RoomVersion = RoomVersions.V1,
  489. internal_metadata_dict: Optional[JsonDict] = None,
  490. rejected_reason: Optional[str] = None,
  491. ) -> EventBase:
  492. """Construct an EventBase from the given event dict"""
  493. event_type = _event_type_from_format_version(room_version.event_format)
  494. return event_type(
  495. event_dict, room_version, internal_metadata_dict or {}, rejected_reason
  496. )
  497. @attr.s(slots=True, frozen=True, auto_attribs=True)
  498. class _EventRelation:
  499. # The target event of the relation.
  500. parent_id: str
  501. # The relation type.
  502. rel_type: str
  503. # The aggregation key. Will be None if the rel_type is not m.annotation or is
  504. # not a string.
  505. aggregation_key: Optional[str]
  506. def relation_from_event(event: EventBase) -> Optional[_EventRelation]:
  507. """
  508. Attempt to parse relation information an event.
  509. Returns:
  510. The event relation information, if it is valid. None, otherwise.
  511. """
  512. relation = event.content.get("m.relates_to")
  513. if not relation or not isinstance(relation, collections.abc.Mapping):
  514. # No relation information.
  515. return None
  516. # Relations must have a type and parent event ID.
  517. rel_type = relation.get("rel_type")
  518. if not isinstance(rel_type, str):
  519. return None
  520. parent_id = relation.get("event_id")
  521. if not isinstance(parent_id, str):
  522. return None
  523. # Annotations have a key field.
  524. aggregation_key = None
  525. if rel_type == RelationTypes.ANNOTATION:
  526. aggregation_key = relation.get("key")
  527. if not isinstance(aggregation_key, str):
  528. aggregation_key = None
  529. return _EventRelation(parent_id, rel_type, aggregation_key)