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.
 
 
 
 
 
 

286 lines
8.9 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from typing import Optional
  16. import attr
  17. from nacl.signing import SigningKey
  18. from synapse.api.auth import Auth
  19. from synapse.api.constants import MAX_DEPTH
  20. from synapse.api.errors import UnsupportedRoomVersionError
  21. from synapse.api.room_versions import (
  22. KNOWN_EVENT_FORMAT_VERSIONS,
  23. KNOWN_ROOM_VERSIONS,
  24. EventFormatVersions,
  25. RoomVersion,
  26. )
  27. from synapse.crypto.event_signing import add_hashes_and_signatures
  28. from synapse.events import EventBase, _EventInternalMetadata, make_event_from_dict
  29. from synapse.state import StateHandler
  30. from synapse.storage.databases.main import DataStore
  31. from synapse.types import EventID, JsonDict
  32. from synapse.util import Clock
  33. from synapse.util.stringutils import random_string
  34. @attr.s(slots=True, cmp=False, frozen=True)
  35. class EventBuilder(object):
  36. """A format independent event builder used to build up the event content
  37. before signing the event.
  38. (Note that while objects of this class are frozen, the
  39. content/unsigned/internal_metadata fields are still mutable)
  40. Attributes:
  41. room_version: Version of the target room
  42. room_id
  43. type
  44. sender
  45. content
  46. unsigned
  47. internal_metadata
  48. _state
  49. _auth
  50. _store
  51. _clock
  52. _hostname: The hostname of the server creating the event
  53. _signing_key: The signing key to use to sign the event as the server
  54. """
  55. _state = attr.ib(type=StateHandler)
  56. _auth = attr.ib(type=Auth)
  57. _store = attr.ib(type=DataStore)
  58. _clock = attr.ib(type=Clock)
  59. _hostname = attr.ib(type=str)
  60. _signing_key = attr.ib(type=SigningKey)
  61. room_version = attr.ib(type=RoomVersion)
  62. room_id = attr.ib(type=str)
  63. type = attr.ib(type=str)
  64. sender = attr.ib(type=str)
  65. content = attr.ib(default=attr.Factory(dict), type=JsonDict)
  66. unsigned = attr.ib(default=attr.Factory(dict), type=JsonDict)
  67. # These only exist on a subset of events, so they raise AttributeError if
  68. # someone tries to get them when they don't exist.
  69. _state_key = attr.ib(default=None, type=Optional[str])
  70. _redacts = attr.ib(default=None, type=Optional[str])
  71. _origin_server_ts = attr.ib(default=None, type=Optional[int])
  72. internal_metadata = attr.ib(
  73. default=attr.Factory(lambda: _EventInternalMetadata({})),
  74. type=_EventInternalMetadata,
  75. )
  76. @property
  77. def state_key(self):
  78. if self._state_key is not None:
  79. return self._state_key
  80. raise AttributeError("state_key")
  81. def is_state(self):
  82. return self._state_key is not None
  83. async def build(self, prev_event_ids):
  84. """Transform into a fully signed and hashed event
  85. Args:
  86. prev_event_ids (list[str]): The event IDs to use as the prev events
  87. Returns:
  88. FrozenEvent
  89. """
  90. state_ids = await self._state.get_current_state_ids(
  91. self.room_id, prev_event_ids
  92. )
  93. auth_ids = self._auth.compute_auth_events(self, state_ids)
  94. format_version = self.room_version.event_format
  95. if format_version == EventFormatVersions.V1:
  96. auth_events = await self._store.add_event_hashes(auth_ids)
  97. prev_events = await self._store.add_event_hashes(prev_event_ids)
  98. else:
  99. auth_events = auth_ids
  100. prev_events = prev_event_ids
  101. old_depth = await self._store.get_max_depth_of(prev_event_ids)
  102. depth = old_depth + 1
  103. # we cap depth of generated events, to ensure that they are not
  104. # rejected by other servers (and so that they can be persisted in
  105. # the db)
  106. depth = min(depth, MAX_DEPTH)
  107. event_dict = {
  108. "auth_events": auth_events,
  109. "prev_events": prev_events,
  110. "type": self.type,
  111. "room_id": self.room_id,
  112. "sender": self.sender,
  113. "content": self.content,
  114. "unsigned": self.unsigned,
  115. "depth": depth,
  116. "prev_state": [],
  117. }
  118. if self.is_state():
  119. event_dict["state_key"] = self._state_key
  120. if self._redacts is not None:
  121. event_dict["redacts"] = self._redacts
  122. if self._origin_server_ts is not None:
  123. event_dict["origin_server_ts"] = self._origin_server_ts
  124. return create_local_event_from_event_dict(
  125. clock=self._clock,
  126. hostname=self._hostname,
  127. signing_key=self._signing_key,
  128. room_version=self.room_version,
  129. event_dict=event_dict,
  130. internal_metadata_dict=self.internal_metadata.get_dict(),
  131. )
  132. class EventBuilderFactory(object):
  133. def __init__(self, hs):
  134. self.clock = hs.get_clock()
  135. self.hostname = hs.hostname
  136. self.signing_key = hs.signing_key
  137. self.store = hs.get_datastore()
  138. self.state = hs.get_state_handler()
  139. self.auth = hs.get_auth()
  140. def new(self, room_version, key_values):
  141. """Generate an event builder appropriate for the given room version
  142. Deprecated: use for_room_version with a RoomVersion object instead
  143. Args:
  144. room_version (str): Version of the room that we're creating an event builder
  145. for
  146. key_values (dict): Fields used as the basis of the new event
  147. Returns:
  148. EventBuilder
  149. """
  150. v = KNOWN_ROOM_VERSIONS.get(room_version)
  151. if not v:
  152. # this can happen if support is withdrawn for a room version
  153. raise UnsupportedRoomVersionError()
  154. return self.for_room_version(v, key_values)
  155. def for_room_version(self, room_version, key_values):
  156. """Generate an event builder appropriate for the given room version
  157. Args:
  158. room_version (synapse.api.room_versions.RoomVersion):
  159. Version of the room that we're creating an event builder for
  160. key_values (dict): Fields used as the basis of the new event
  161. Returns:
  162. EventBuilder
  163. """
  164. return EventBuilder(
  165. store=self.store,
  166. state=self.state,
  167. auth=self.auth,
  168. clock=self.clock,
  169. hostname=self.hostname,
  170. signing_key=self.signing_key,
  171. room_version=room_version,
  172. type=key_values["type"],
  173. state_key=key_values.get("state_key"),
  174. room_id=key_values["room_id"],
  175. sender=key_values["sender"],
  176. content=key_values.get("content", {}),
  177. unsigned=key_values.get("unsigned", {}),
  178. redacts=key_values.get("redacts", None),
  179. origin_server_ts=key_values.get("origin_server_ts", None),
  180. )
  181. def create_local_event_from_event_dict(
  182. clock: Clock,
  183. hostname: str,
  184. signing_key: SigningKey,
  185. room_version: RoomVersion,
  186. event_dict: JsonDict,
  187. internal_metadata_dict: Optional[JsonDict] = None,
  188. ) -> EventBase:
  189. """Takes a fully formed event dict, ensuring that fields like `origin`
  190. and `origin_server_ts` have correct values for a locally produced event,
  191. then signs and hashes it.
  192. """
  193. format_version = room_version.event_format
  194. if format_version not in KNOWN_EVENT_FORMAT_VERSIONS:
  195. raise Exception("No event format defined for version %r" % (format_version,))
  196. if internal_metadata_dict is None:
  197. internal_metadata_dict = {}
  198. time_now = int(clock.time_msec())
  199. if format_version == EventFormatVersions.V1:
  200. event_dict["event_id"] = _create_event_id(clock, hostname)
  201. event_dict["origin"] = hostname
  202. event_dict.setdefault("origin_server_ts", time_now)
  203. event_dict.setdefault("unsigned", {})
  204. age = event_dict["unsigned"].pop("age", 0)
  205. event_dict["unsigned"].setdefault("age_ts", time_now - age)
  206. event_dict.setdefault("signatures", {})
  207. add_hashes_and_signatures(room_version, event_dict, hostname, signing_key)
  208. return make_event_from_dict(
  209. event_dict, room_version, internal_metadata_dict=internal_metadata_dict
  210. )
  211. # A counter used when generating new event IDs
  212. _event_id_counter = 0
  213. def _create_event_id(clock, hostname):
  214. """Create a new event ID
  215. Args:
  216. clock (Clock)
  217. hostname (str): The server name for the event ID
  218. Returns:
  219. str
  220. """
  221. global _event_id_counter
  222. i = str(_event_id_counter)
  223. _event_id_counter += 1
  224. local_part = str(int(clock.time())) + i + random_string(5)
  225. e_id = EventID(local_part, hostname)
  226. return e_id.to_string()