25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

669 satır
23 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 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. Tuple,
  28. Type,
  29. TypeVar,
  30. Union,
  31. overload,
  32. )
  33. import attr
  34. from typing_extensions import Literal
  35. from unpaddedbase64 import encode_base64
  36. from synapse.api.constants import RelationTypes
  37. from synapse.api.room_versions import EventFormatVersions, RoomVersion, RoomVersions
  38. from synapse.types import JsonDict, RoomStreamToken, StrCollection
  39. from synapse.util.caches import intern_dict
  40. from synapse.util.frozenutils import freeze
  41. from synapse.util.stringutils import strtobool
  42. if TYPE_CHECKING:
  43. from synapse.events.builder import EventBuilder
  44. # Whether we should use frozen_dict in FrozenEvent. Using frozen_dicts prevents
  45. # bugs where we accidentally share e.g. signature dicts. However, converting a
  46. # dict to frozen_dicts is expensive.
  47. #
  48. # NOTE: This is overridden by the configuration by the Synapse worker apps, but
  49. # for the sake of tests, it is set here while it cannot be configured on the
  50. # homeserver object itself.
  51. USE_FROZEN_DICTS = strtobool(os.environ.get("SYNAPSE_USE_FROZEN_DICTS", "0"))
  52. T = TypeVar("T")
  53. # DictProperty (and DefaultDictProperty) require the classes they're used with to
  54. # have a _dict property to pull properties from.
  55. #
  56. # TODO _DictPropertyInstance should not include EventBuilder but due to
  57. # https://github.com/python/mypy/issues/5570 it thinks the DictProperty and
  58. # DefaultDictProperty get applied to EventBuilder when it is in a Union with
  59. # EventBase. This is the least invasive hack to get mypy to comply.
  60. #
  61. # Note that DictProperty/DefaultDictProperty cannot actually be used with
  62. # EventBuilder as it lacks a _dict property.
  63. _DictPropertyInstance = Union["_EventInternalMetadata", "EventBase", "EventBuilder"]
  64. class DictProperty(Generic[T]):
  65. """An object property which delegates to the `_dict` within its parent object."""
  66. __slots__ = ["key"]
  67. def __init__(self, key: str):
  68. self.key = key
  69. @overload
  70. def __get__(
  71. self,
  72. instance: Literal[None],
  73. owner: Optional[Type[_DictPropertyInstance]] = None,
  74. ) -> "DictProperty":
  75. ...
  76. @overload
  77. def __get__(
  78. self,
  79. instance: _DictPropertyInstance,
  80. owner: Optional[Type[_DictPropertyInstance]] = None,
  81. ) -> T:
  82. ...
  83. def __get__(
  84. self,
  85. instance: Optional[_DictPropertyInstance],
  86. owner: Optional[Type[_DictPropertyInstance]] = None,
  87. ) -> Union[T, "DictProperty"]:
  88. # if the property is accessed as a class property rather than an instance
  89. # property, return the property itself rather than the value
  90. if instance is None:
  91. return self
  92. try:
  93. assert isinstance(instance, (EventBase, _EventInternalMetadata))
  94. return instance._dict[self.key]
  95. except KeyError as e1:
  96. # We want this to look like a regular attribute error (mostly so that
  97. # hasattr() works correctly), so we convert the KeyError into an
  98. # AttributeError.
  99. #
  100. # To exclude the KeyError from the traceback, we explicitly
  101. # 'raise from e1.__context__' (which is better than 'raise from None',
  102. # because that would omit any *earlier* exceptions).
  103. #
  104. raise AttributeError(
  105. "'%s' has no '%s' property" % (type(instance), self.key)
  106. ) from e1.__context__
  107. def __set__(self, instance: _DictPropertyInstance, v: T) -> None:
  108. assert isinstance(instance, (EventBase, _EventInternalMetadata))
  109. instance._dict[self.key] = v
  110. def __delete__(self, instance: _DictPropertyInstance) -> None:
  111. assert isinstance(instance, (EventBase, _EventInternalMetadata))
  112. try:
  113. del instance._dict[self.key]
  114. except KeyError as e1:
  115. raise AttributeError(
  116. "'%s' has no '%s' property" % (type(instance), self.key)
  117. ) from e1.__context__
  118. class DefaultDictProperty(DictProperty, Generic[T]):
  119. """An extension of DictProperty which provides a default if the property is
  120. not present in the parent's _dict.
  121. Note that this means that hasattr() on the property always returns True.
  122. """
  123. __slots__ = ["default"]
  124. def __init__(self, key: str, default: T):
  125. super().__init__(key)
  126. self.default = default
  127. @overload
  128. def __get__(
  129. self,
  130. instance: Literal[None],
  131. owner: Optional[Type[_DictPropertyInstance]] = None,
  132. ) -> "DefaultDictProperty":
  133. ...
  134. @overload
  135. def __get__(
  136. self,
  137. instance: _DictPropertyInstance,
  138. owner: Optional[Type[_DictPropertyInstance]] = None,
  139. ) -> T:
  140. ...
  141. def __get__(
  142. self,
  143. instance: Optional[_DictPropertyInstance],
  144. owner: Optional[Type[_DictPropertyInstance]] = None,
  145. ) -> Union[T, "DefaultDictProperty"]:
  146. if instance is None:
  147. return self
  148. assert isinstance(instance, (EventBase, _EventInternalMetadata))
  149. return instance._dict.get(self.key, self.default)
  150. class _EventInternalMetadata:
  151. __slots__ = ["_dict", "stream_ordering", "outlier"]
  152. def __init__(self, internal_metadata_dict: JsonDict):
  153. # we have to copy the dict, because it turns out that the same dict is
  154. # reused. TODO: fix that
  155. self._dict = dict(internal_metadata_dict)
  156. # the stream ordering of this event. None, until it has been persisted.
  157. self.stream_ordering: Optional[int] = None
  158. # whether this event is an outlier (ie, whether we have the state at that point
  159. # in the DAG)
  160. self.outlier = False
  161. out_of_band_membership: DictProperty[bool] = DictProperty("out_of_band_membership")
  162. send_on_behalf_of: DictProperty[str] = DictProperty("send_on_behalf_of")
  163. recheck_redaction: DictProperty[bool] = DictProperty("recheck_redaction")
  164. soft_failed: DictProperty[bool] = DictProperty("soft_failed")
  165. proactively_send: DictProperty[bool] = DictProperty("proactively_send")
  166. redacted: DictProperty[bool] = DictProperty("redacted")
  167. txn_id: DictProperty[str] = DictProperty("txn_id")
  168. """The transaction ID, if it was set when the event was created."""
  169. token_id: DictProperty[int] = DictProperty("token_id")
  170. """The access token ID of the user who sent this event, if any."""
  171. device_id: DictProperty[str] = DictProperty("device_id")
  172. """The device ID of the user who sent this event, if any."""
  173. # XXX: These are set by StreamWorkerStore._set_before_and_after.
  174. # I'm pretty sure that these are never persisted to the database, so shouldn't
  175. # be here
  176. before: DictProperty[RoomStreamToken] = DictProperty("before")
  177. after: DictProperty[RoomStreamToken] = DictProperty("after")
  178. order: DictProperty[Tuple[int, int]] = DictProperty("order")
  179. def get_dict(self) -> JsonDict:
  180. return dict(self._dict)
  181. def is_outlier(self) -> bool:
  182. return self.outlier
  183. def is_out_of_band_membership(self) -> bool:
  184. """Whether this event is an out-of-band membership.
  185. OOB memberships are a special case of outlier events: they are membership events
  186. for federated rooms that we aren't full members of. Examples include invites
  187. received over federation, and rejections for such invites.
  188. The concept of an OOB membership is needed because these events need to be
  189. processed as if they're new regular events (e.g. updating membership state in
  190. the database, relaying to clients via /sync, etc) despite being outliers.
  191. See also https://matrix-org.github.io/synapse/develop/development/room-dag-concepts.html#out-of-band-membership-events.
  192. (Added in synapse 0.99.0, so may be unreliable for events received before that)
  193. """
  194. return self._dict.get("out_of_band_membership", False)
  195. def get_send_on_behalf_of(self) -> Optional[str]:
  196. """Whether this server should send the event on behalf of another server.
  197. This is used by the federation "send_join" API to forward the initial join
  198. event for a server in the room.
  199. returns a str with the name of the server this event is sent on behalf of.
  200. """
  201. return self._dict.get("send_on_behalf_of")
  202. def need_to_check_redaction(self) -> bool:
  203. """Whether the redaction event needs to be rechecked when fetching
  204. from the database.
  205. Starting in room v3 redaction events are accepted up front, and later
  206. checked to see if the redacter and redactee's domains match.
  207. If the sender of the redaction event is allowed to redact any event
  208. due to auth rules, then this will always return false.
  209. """
  210. return self._dict.get("recheck_redaction", False)
  211. def is_soft_failed(self) -> bool:
  212. """Whether the event has been soft failed.
  213. Soft failed events should be handled as usual, except:
  214. 1. They should not go down sync or event streams, or generally
  215. sent to clients.
  216. 2. They should not be added to the forward extremities (and
  217. therefore not to current state).
  218. """
  219. return self._dict.get("soft_failed", False)
  220. def should_proactively_send(self) -> bool:
  221. """Whether the event, if ours, should be sent to other clients and
  222. servers.
  223. This is used for sending dummy events internally. Servers and clients
  224. can still explicitly fetch the event.
  225. """
  226. return self._dict.get("proactively_send", True)
  227. def is_redacted(self) -> bool:
  228. """Whether the event has been redacted.
  229. This is used for efficiently checking whether an event has been
  230. marked as redacted without needing to make another database call.
  231. """
  232. return self._dict.get("redacted", False)
  233. def is_notifiable(self) -> bool:
  234. """Whether this event can trigger a push notification"""
  235. return not self.is_outlier() or self.is_out_of_band_membership()
  236. class EventBase(metaclass=abc.ABCMeta):
  237. @property
  238. @abc.abstractmethod
  239. def format_version(self) -> int:
  240. """The EventFormatVersion implemented by this event"""
  241. ...
  242. def __init__(
  243. self,
  244. event_dict: JsonDict,
  245. room_version: RoomVersion,
  246. signatures: Dict[str, Dict[str, str]],
  247. unsigned: JsonDict,
  248. internal_metadata_dict: JsonDict,
  249. rejected_reason: Optional[str],
  250. ):
  251. assert room_version.event_format == self.format_version
  252. self.room_version = room_version
  253. self.signatures = signatures
  254. self.unsigned = unsigned
  255. self.rejected_reason = rejected_reason
  256. self._dict = event_dict
  257. self.internal_metadata = _EventInternalMetadata(internal_metadata_dict)
  258. depth: DictProperty[int] = DictProperty("depth")
  259. content: DictProperty[JsonDict] = DictProperty("content")
  260. hashes: DictProperty[Dict[str, str]] = DictProperty("hashes")
  261. origin: DictProperty[str] = DictProperty("origin")
  262. origin_server_ts: DictProperty[int] = DictProperty("origin_server_ts")
  263. room_id: DictProperty[str] = DictProperty("room_id")
  264. sender: DictProperty[str] = DictProperty("sender")
  265. # TODO state_key should be Optional[str]. This is generally asserted in Synapse
  266. # by calling is_state() first (which ensures it is not None), but it is hard (not possible?)
  267. # to properly annotate that calling is_state() asserts that state_key exists
  268. # and is non-None. It would be better to replace such direct references with
  269. # get_state_key() (and a check for None).
  270. state_key: DictProperty[str] = DictProperty("state_key")
  271. type: DictProperty[str] = DictProperty("type")
  272. user_id: DictProperty[str] = DictProperty("sender")
  273. @property
  274. def event_id(self) -> str:
  275. raise NotImplementedError()
  276. @property
  277. def membership(self) -> str:
  278. return self.content["membership"]
  279. @property
  280. def redacts(self) -> Optional[str]:
  281. """MSC2176 moved the redacts field into the content."""
  282. if self.room_version.updated_redaction_rules:
  283. return self.content.get("redacts")
  284. return self.get("redacts")
  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) -> List[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) -> StrCollection:
  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: dict(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: dict(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) -> List[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) -> StrCollection:
  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)