__init__.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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
  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. token_id: DictProperty[int] = DictProperty("token_id")
  170. historical: DictProperty[bool] = DictProperty("historical")
  171. # XXX: These are set by StreamWorkerStore._set_before_and_after.
  172. # I'm pretty sure that these are never persisted to the database, so shouldn't
  173. # be here
  174. before: DictProperty[RoomStreamToken] = DictProperty("before")
  175. after: DictProperty[RoomStreamToken] = DictProperty("after")
  176. order: DictProperty[Tuple[int, int]] = DictProperty("order")
  177. def get_dict(self) -> JsonDict:
  178. return dict(self._dict)
  179. def is_outlier(self) -> bool:
  180. return self.outlier
  181. def is_out_of_band_membership(self) -> bool:
  182. """Whether this event is an out-of-band membership.
  183. OOB memberships are a special case of outlier events: they are membership events
  184. for federated rooms that we aren't full members of. Examples include invites
  185. received over federation, and rejections for such invites.
  186. The concept of an OOB membership is needed because these events need to be
  187. processed as if they're new regular events (e.g. updating membership state in
  188. the database, relaying to clients via /sync, etc) despite being outliers.
  189. See also https://matrix-org.github.io/synapse/develop/development/room-dag-concepts.html#out-of-band-membership-events.
  190. (Added in synapse 0.99.0, so may be unreliable for events received before that)
  191. """
  192. return self._dict.get("out_of_band_membership", False)
  193. def get_send_on_behalf_of(self) -> Optional[str]:
  194. """Whether this server should send the event on behalf of another server.
  195. This is used by the federation "send_join" API to forward the initial join
  196. event for a server in the room.
  197. returns a str with the name of the server this event is sent on behalf of.
  198. """
  199. return self._dict.get("send_on_behalf_of")
  200. def need_to_check_redaction(self) -> bool:
  201. """Whether the redaction event needs to be rechecked when fetching
  202. from the database.
  203. Starting in room v3 redaction events are accepted up front, and later
  204. checked to see if the redacter and redactee's domains match.
  205. If the sender of the redaction event is allowed to redact any event
  206. due to auth rules, then this will always return false.
  207. """
  208. return self._dict.get("recheck_redaction", False)
  209. def is_soft_failed(self) -> bool:
  210. """Whether the event has been soft failed.
  211. Soft failed events should be handled as usual, except:
  212. 1. They should not go down sync or event streams, or generally
  213. sent to clients.
  214. 2. They should not be added to the forward extremities (and
  215. therefore not to current state).
  216. """
  217. return self._dict.get("soft_failed", False)
  218. def should_proactively_send(self) -> bool:
  219. """Whether the event, if ours, should be sent to other clients and
  220. servers.
  221. This is used for sending dummy events internally. Servers and clients
  222. can still explicitly fetch the event.
  223. """
  224. return self._dict.get("proactively_send", True)
  225. def is_redacted(self) -> bool:
  226. """Whether the event has been redacted.
  227. This is used for efficiently checking whether an event has been
  228. marked as redacted without needing to make another database call.
  229. """
  230. return self._dict.get("redacted", False)
  231. def is_historical(self) -> bool:
  232. """Whether this is a historical message.
  233. This is used by the batchsend historical message endpoint and
  234. is needed to and mark the event as backfilled and skip some checks
  235. like push notifications.
  236. """
  237. return self._dict.get("historical", False)
  238. def is_notifiable(self) -> bool:
  239. """Whether this event can trigger a push notification"""
  240. return not self.is_outlier() or self.is_out_of_band_membership()
  241. class EventBase(metaclass=abc.ABCMeta):
  242. @property
  243. @abc.abstractmethod
  244. def format_version(self) -> int:
  245. """The EventFormatVersion implemented by this event"""
  246. ...
  247. def __init__(
  248. self,
  249. event_dict: JsonDict,
  250. room_version: RoomVersion,
  251. signatures: Dict[str, Dict[str, str]],
  252. unsigned: JsonDict,
  253. internal_metadata_dict: JsonDict,
  254. rejected_reason: Optional[str],
  255. ):
  256. assert room_version.event_format == self.format_version
  257. self.room_version = room_version
  258. self.signatures = signatures
  259. self.unsigned = unsigned
  260. self.rejected_reason = rejected_reason
  261. self._dict = event_dict
  262. self.internal_metadata = _EventInternalMetadata(internal_metadata_dict)
  263. depth: DictProperty[int] = DictProperty("depth")
  264. content: DictProperty[JsonDict] = DictProperty("content")
  265. hashes: DictProperty[Dict[str, str]] = DictProperty("hashes")
  266. origin: DictProperty[str] = DictProperty("origin")
  267. origin_server_ts: DictProperty[int] = DictProperty("origin_server_ts")
  268. redacts: DefaultDictProperty[Optional[str]] = DefaultDictProperty("redacts", None)
  269. room_id: DictProperty[str] = DictProperty("room_id")
  270. sender: DictProperty[str] = DictProperty("sender")
  271. # TODO state_key should be Optional[str]. This is generally asserted in Synapse
  272. # by calling is_state() first (which ensures it is not None), but it is hard (not possible?)
  273. # to properly annotate that calling is_state() asserts that state_key exists
  274. # and is non-None. It would be better to replace such direct references with
  275. # get_state_key() (and a check for None).
  276. state_key: DictProperty[str] = DictProperty("state_key")
  277. type: DictProperty[str] = DictProperty("type")
  278. user_id: DictProperty[str] = DictProperty("sender")
  279. @property
  280. def event_id(self) -> str:
  281. raise NotImplementedError()
  282. @property
  283. def membership(self) -> str:
  284. return self.content["membership"]
  285. def is_state(self) -> bool:
  286. return self.get_state_key() is not None
  287. def get_state_key(self) -> Optional[str]:
  288. """Get the state key of this event, or None if it's not a state event"""
  289. return self._dict.get("state_key")
  290. def get_dict(self) -> JsonDict:
  291. d = dict(self._dict)
  292. d.update({"signatures": self.signatures, "unsigned": dict(self.unsigned)})
  293. return d
  294. def get(self, key: str, default: Optional[Any] = None) -> Any:
  295. return self._dict.get(key, default)
  296. def get_internal_metadata_dict(self) -> JsonDict:
  297. return self.internal_metadata.get_dict()
  298. def get_pdu_json(self, time_now: Optional[int] = None) -> JsonDict:
  299. pdu_json = self.get_dict()
  300. if time_now is not None and "age_ts" in pdu_json["unsigned"]:
  301. age = time_now - pdu_json["unsigned"]["age_ts"]
  302. pdu_json.setdefault("unsigned", {})["age"] = int(age)
  303. del pdu_json["unsigned"]["age_ts"]
  304. # This may be a frozen event
  305. pdu_json["unsigned"].pop("redacted_because", None)
  306. return pdu_json
  307. def get_templated_pdu_json(self) -> JsonDict:
  308. """
  309. Return a JSON object suitable for a templated event, as used in the
  310. make_{join,leave,knock} workflow.
  311. """
  312. # By using _dict directly we don't pull in signatures/unsigned.
  313. template_json = dict(self._dict)
  314. # The hashes (similar to the signature) need to be recalculated by the
  315. # joining/leaving/knocking server after (potentially) modifying the
  316. # event.
  317. template_json.pop("hashes")
  318. return template_json
  319. def __getitem__(self, field: str) -> Optional[Any]:
  320. return self._dict[field]
  321. def __contains__(self, field: str) -> bool:
  322. return field in self._dict
  323. def items(self) -> List[Tuple[str, Optional[Any]]]:
  324. return list(self._dict.items())
  325. def keys(self) -> Iterable[str]:
  326. return self._dict.keys()
  327. def prev_event_ids(self) -> Sequence[str]:
  328. """Returns the list of prev event IDs. The order matches the order
  329. specified in the event, though there is no meaning to it.
  330. Returns:
  331. The list of event IDs of this event's prev_events
  332. """
  333. return [e for e, _ in self._dict["prev_events"]]
  334. def auth_event_ids(self) -> Sequence[str]:
  335. """Returns the list of auth event IDs. The order matches the order
  336. specified in the event, though there is no meaning to it.
  337. Returns:
  338. The list of event IDs of this event's auth_events
  339. """
  340. return [e for e, _ in self._dict["auth_events"]]
  341. def freeze(self) -> None:
  342. """'Freeze' the event dict, so it cannot be modified by accident"""
  343. # this will be a no-op if the event dict is already frozen.
  344. self._dict = freeze(self._dict)
  345. def __str__(self) -> str:
  346. return self.__repr__()
  347. def __repr__(self) -> str:
  348. rejection = f"REJECTED={self.rejected_reason}, " if self.rejected_reason else ""
  349. return (
  350. f"<{self.__class__.__name__} "
  351. f"{rejection}"
  352. f"event_id={self.event_id}, "
  353. f"type={self.get('type')}, "
  354. f"state_key={self.get('state_key')}, "
  355. f"outlier={self.internal_metadata.is_outlier()}"
  356. ">"
  357. )
  358. class FrozenEvent(EventBase):
  359. format_version = EventFormatVersions.ROOM_V1_V2 # All events of this type are V1
  360. def __init__(
  361. self,
  362. event_dict: JsonDict,
  363. room_version: RoomVersion,
  364. internal_metadata_dict: Optional[JsonDict] = None,
  365. rejected_reason: Optional[str] = None,
  366. ):
  367. internal_metadata_dict = internal_metadata_dict or {}
  368. event_dict = dict(event_dict)
  369. # Signatures is a dict of dicts, and this is faster than doing a
  370. # copy.deepcopy
  371. signatures = {
  372. name: {sig_id: sig for sig_id, sig in sigs.items()}
  373. for name, sigs in event_dict.pop("signatures", {}).items()
  374. }
  375. unsigned = dict(event_dict.pop("unsigned", {}))
  376. # We intern these strings because they turn up a lot (especially when
  377. # caching).
  378. event_dict = intern_dict(event_dict)
  379. if USE_FROZEN_DICTS:
  380. frozen_dict = freeze(event_dict)
  381. else:
  382. frozen_dict = event_dict
  383. self._event_id = event_dict["event_id"]
  384. super().__init__(
  385. frozen_dict,
  386. room_version=room_version,
  387. signatures=signatures,
  388. unsigned=unsigned,
  389. internal_metadata_dict=internal_metadata_dict,
  390. rejected_reason=rejected_reason,
  391. )
  392. @property
  393. def event_id(self) -> str:
  394. return self._event_id
  395. class FrozenEventV2(EventBase):
  396. format_version = EventFormatVersions.ROOM_V3 # All events of this type are V2
  397. def __init__(
  398. self,
  399. event_dict: JsonDict,
  400. room_version: RoomVersion,
  401. internal_metadata_dict: Optional[JsonDict] = None,
  402. rejected_reason: Optional[str] = None,
  403. ):
  404. internal_metadata_dict = internal_metadata_dict or {}
  405. event_dict = dict(event_dict)
  406. # Signatures is a dict of dicts, and this is faster than doing a
  407. # copy.deepcopy
  408. signatures = {
  409. name: {sig_id: sig for sig_id, sig in sigs.items()}
  410. for name, sigs in event_dict.pop("signatures", {}).items()
  411. }
  412. assert "event_id" not in event_dict
  413. unsigned = dict(event_dict.pop("unsigned", {}))
  414. # We intern these strings because they turn up a lot (especially when
  415. # caching).
  416. event_dict = intern_dict(event_dict)
  417. if USE_FROZEN_DICTS:
  418. frozen_dict = freeze(event_dict)
  419. else:
  420. frozen_dict = event_dict
  421. self._event_id: Optional[str] = None
  422. super().__init__(
  423. frozen_dict,
  424. room_version=room_version,
  425. signatures=signatures,
  426. unsigned=unsigned,
  427. internal_metadata_dict=internal_metadata_dict,
  428. rejected_reason=rejected_reason,
  429. )
  430. @property
  431. def event_id(self) -> str:
  432. # We have to import this here as otherwise we get an import loop which
  433. # is hard to break.
  434. from synapse.crypto.event_signing import compute_event_reference_hash
  435. if self._event_id:
  436. return self._event_id
  437. self._event_id = "$" + encode_base64(compute_event_reference_hash(self)[1])
  438. return self._event_id
  439. def prev_event_ids(self) -> Sequence[str]:
  440. """Returns the list of prev event IDs. The order matches the order
  441. specified in the event, though there is no meaning to it.
  442. Returns:
  443. The list of event IDs of this event's prev_events
  444. """
  445. return self._dict["prev_events"]
  446. def auth_event_ids(self) -> Sequence[str]:
  447. """Returns the list of auth event IDs. The order matches the order
  448. specified in the event, though there is no meaning to it.
  449. Returns:
  450. The list of event IDs of this event's auth_events
  451. """
  452. return self._dict["auth_events"]
  453. class FrozenEventV3(FrozenEventV2):
  454. """FrozenEventV3, which differs from FrozenEventV2 only in the event_id format"""
  455. format_version = EventFormatVersions.ROOM_V4_PLUS # All events of this type are V3
  456. @property
  457. def event_id(self) -> str:
  458. # We have to import this here as otherwise we get an import loop which
  459. # is hard to break.
  460. from synapse.crypto.event_signing import compute_event_reference_hash
  461. if self._event_id:
  462. return self._event_id
  463. self._event_id = "$" + encode_base64(
  464. compute_event_reference_hash(self)[1], urlsafe=True
  465. )
  466. return self._event_id
  467. def _event_type_from_format_version(
  468. format_version: int,
  469. ) -> Type[Union[FrozenEvent, FrozenEventV2, FrozenEventV3]]:
  470. """Returns the python type to use to construct an Event object for the
  471. given event format version.
  472. Args:
  473. format_version: The event format version
  474. Returns:
  475. A type that can be initialized as per the initializer of `FrozenEvent`
  476. """
  477. if format_version == EventFormatVersions.ROOM_V1_V2:
  478. return FrozenEvent
  479. elif format_version == EventFormatVersions.ROOM_V3:
  480. return FrozenEventV2
  481. elif format_version == EventFormatVersions.ROOM_V4_PLUS:
  482. return FrozenEventV3
  483. else:
  484. raise Exception("No event format %r" % (format_version,))
  485. def make_event_from_dict(
  486. event_dict: JsonDict,
  487. room_version: RoomVersion = RoomVersions.V1,
  488. internal_metadata_dict: Optional[JsonDict] = None,
  489. rejected_reason: Optional[str] = None,
  490. ) -> EventBase:
  491. """Construct an EventBase from the given event dict"""
  492. event_type = _event_type_from_format_version(room_version.event_format)
  493. return event_type(
  494. event_dict, room_version, internal_metadata_dict or {}, rejected_reason
  495. )
  496. @attr.s(slots=True, frozen=True, auto_attribs=True)
  497. class _EventRelation:
  498. # The target event of the relation.
  499. parent_id: str
  500. # The relation type.
  501. rel_type: str
  502. # The aggregation key. Will be None if the rel_type is not m.annotation or is
  503. # not a string.
  504. aggregation_key: Optional[str]
  505. def relation_from_event(event: EventBase) -> Optional[_EventRelation]:
  506. """
  507. Attempt to parse relation information an event.
  508. Returns:
  509. The event relation information, if it is valid. None, otherwise.
  510. """
  511. relation = event.content.get("m.relates_to")
  512. if not relation or not isinstance(relation, collections.abc.Mapping):
  513. # No relation information.
  514. return None
  515. # Relations must have a type and parent event ID.
  516. rel_type = relation.get("rel_type")
  517. if not isinstance(rel_type, str):
  518. return None
  519. parent_id = relation.get("event_id")
  520. if not isinstance(parent_id, str):
  521. return None
  522. # Annotations have a key field.
  523. aggregation_key = None
  524. if rel_type == RelationTypes.ANNOTATION:
  525. aggregation_key = relation.get("key")
  526. if not isinstance(aggregation_key, str):
  527. aggregation_key = None
  528. return _EventRelation(parent_id, rel_type, aggregation_key)