utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. import collections
  16. import re
  17. from typing import Any, Mapping, Union
  18. from frozendict import frozendict
  19. from twisted.internet import defer
  20. from synapse.api.constants import EventTypes, RelationTypes
  21. from synapse.api.errors import Codes, SynapseError
  22. from synapse.api.room_versions import RoomVersion
  23. from synapse.util.async_helpers import yieldable_gather_results
  24. from . import EventBase
  25. # Split strings on "." but not "\." This uses a negative lookbehind assertion for '\'
  26. # (?<!stuff) matches if the current position in the string is not preceded
  27. # by a match for 'stuff'.
  28. # TODO: This is fast, but fails to handle "foo\\.bar" which should be treated as
  29. # the literal fields "foo\" and "bar" but will instead be treated as "foo\\.bar"
  30. SPLIT_FIELD_REGEX = re.compile(r"(?<!\\)\.")
  31. def prune_event(event: EventBase) -> EventBase:
  32. """ Returns a pruned version of the given event, which removes all keys we
  33. don't know about or think could potentially be dodgy.
  34. This is used when we "redact" an event. We want to remove all fields that
  35. the user has specified, but we do want to keep necessary information like
  36. type, state_key etc.
  37. """
  38. pruned_event_dict = prune_event_dict(event.room_version, event.get_dict())
  39. from . import make_event_from_dict
  40. pruned_event = make_event_from_dict(
  41. pruned_event_dict, event.room_version, event.internal_metadata.get_dict()
  42. )
  43. # Mark the event as redacted
  44. pruned_event.internal_metadata.redacted = True
  45. return pruned_event
  46. def prune_event_dict(room_version: RoomVersion, event_dict: dict) -> dict:
  47. """Redacts the event_dict in the same way as `prune_event`, except it
  48. operates on dicts rather than event objects
  49. Returns:
  50. A copy of the pruned event dict
  51. """
  52. allowed_keys = [
  53. "event_id",
  54. "sender",
  55. "room_id",
  56. "hashes",
  57. "signatures",
  58. "content",
  59. "type",
  60. "state_key",
  61. "depth",
  62. "prev_events",
  63. "prev_state",
  64. "auth_events",
  65. "origin",
  66. "origin_server_ts",
  67. "membership",
  68. ]
  69. event_type = event_dict["type"]
  70. new_content = {}
  71. def add_fields(*fields):
  72. for field in fields:
  73. if field in event_dict["content"]:
  74. new_content[field] = event_dict["content"][field]
  75. if event_type == EventTypes.Member:
  76. add_fields("membership")
  77. elif event_type == EventTypes.Create:
  78. add_fields("creator")
  79. elif event_type == EventTypes.JoinRules:
  80. add_fields("join_rule")
  81. elif event_type == EventTypes.PowerLevels:
  82. add_fields(
  83. "users",
  84. "users_default",
  85. "events",
  86. "events_default",
  87. "state_default",
  88. "ban",
  89. "kick",
  90. "redact",
  91. )
  92. elif event_type == EventTypes.Aliases and room_version.special_case_aliases_auth:
  93. add_fields("aliases")
  94. elif event_type == EventTypes.RoomHistoryVisibility:
  95. add_fields("history_visibility")
  96. allowed_fields = {k: v for k, v in event_dict.items() if k in allowed_keys}
  97. allowed_fields["content"] = new_content
  98. unsigned = {}
  99. allowed_fields["unsigned"] = unsigned
  100. event_unsigned = event_dict.get("unsigned", {})
  101. if "age_ts" in event_unsigned:
  102. unsigned["age_ts"] = event_unsigned["age_ts"]
  103. if "replaces_state" in event_unsigned:
  104. unsigned["replaces_state"] = event_unsigned["replaces_state"]
  105. return allowed_fields
  106. def _copy_field(src, dst, field):
  107. """Copy the field in 'src' to 'dst'.
  108. For example, if src={"foo":{"bar":5}} and dst={}, and field=["foo","bar"]
  109. then dst={"foo":{"bar":5}}.
  110. Args:
  111. src(dict): The dict to read from.
  112. dst(dict): The dict to modify.
  113. field(list<str>): List of keys to drill down to in 'src'.
  114. """
  115. if len(field) == 0: # this should be impossible
  116. return
  117. if len(field) == 1: # common case e.g. 'origin_server_ts'
  118. if field[0] in src:
  119. dst[field[0]] = src[field[0]]
  120. return
  121. # Else is a nested field e.g. 'content.body'
  122. # Pop the last field as that's the key to move across and we need the
  123. # parent dict in order to access the data. Drill down to the right dict.
  124. key_to_move = field.pop(-1)
  125. sub_dict = src
  126. for sub_field in field: # e.g. sub_field => "content"
  127. if sub_field in sub_dict and type(sub_dict[sub_field]) in [dict, frozendict]:
  128. sub_dict = sub_dict[sub_field]
  129. else:
  130. return
  131. if key_to_move not in sub_dict:
  132. return
  133. # Insert the key into the output dictionary, creating nested objects
  134. # as required. We couldn't do this any earlier or else we'd need to delete
  135. # the empty objects if the key didn't exist.
  136. sub_out_dict = dst
  137. for sub_field in field:
  138. sub_out_dict = sub_out_dict.setdefault(sub_field, {})
  139. sub_out_dict[key_to_move] = sub_dict[key_to_move]
  140. def only_fields(dictionary, fields):
  141. """Return a new dict with only the fields in 'dictionary' which are present
  142. in 'fields'.
  143. If there are no event fields specified then all fields are included.
  144. The entries may include '.' charaters to indicate sub-fields.
  145. So ['content.body'] will include the 'body' field of the 'content' object.
  146. A literal '.' character in a field name may be escaped using a '\'.
  147. Args:
  148. dictionary(dict): The dictionary to read from.
  149. fields(list<str>): A list of fields to copy over. Only shallow refs are
  150. taken.
  151. Returns:
  152. dict: A new dictionary with only the given fields. If fields was empty,
  153. the same dictionary is returned.
  154. """
  155. if len(fields) == 0:
  156. return dictionary
  157. # for each field, convert it:
  158. # ["content.body.thing\.with\.dots"] => [["content", "body", "thing\.with\.dots"]]
  159. split_fields = [SPLIT_FIELD_REGEX.split(f) for f in fields]
  160. # for each element of the output array of arrays:
  161. # remove escaping so we can use the right key names.
  162. split_fields[:] = [
  163. [f.replace(r"\.", r".") for f in field_array] for field_array in split_fields
  164. ]
  165. output = {}
  166. for field_array in split_fields:
  167. _copy_field(dictionary, output, field_array)
  168. return output
  169. def format_event_raw(d):
  170. return d
  171. def format_event_for_client_v1(d):
  172. d = format_event_for_client_v2(d)
  173. sender = d.get("sender")
  174. if sender is not None:
  175. d["user_id"] = sender
  176. copy_keys = (
  177. "age",
  178. "redacted_because",
  179. "replaces_state",
  180. "prev_content",
  181. "invite_room_state",
  182. )
  183. for key in copy_keys:
  184. if key in d["unsigned"]:
  185. d[key] = d["unsigned"][key]
  186. return d
  187. def format_event_for_client_v2(d):
  188. drop_keys = (
  189. "auth_events",
  190. "prev_events",
  191. "hashes",
  192. "signatures",
  193. "depth",
  194. "origin",
  195. "prev_state",
  196. )
  197. for key in drop_keys:
  198. d.pop(key, None)
  199. return d
  200. def format_event_for_client_v2_without_room_id(d):
  201. d = format_event_for_client_v2(d)
  202. d.pop("room_id", None)
  203. return d
  204. def serialize_event(
  205. e,
  206. time_now_ms,
  207. as_client_event=True,
  208. event_format=format_event_for_client_v1,
  209. token_id=None,
  210. only_event_fields=None,
  211. is_invite=False,
  212. ):
  213. """Serialize event for clients
  214. Args:
  215. e (EventBase)
  216. time_now_ms (int)
  217. as_client_event (bool)
  218. event_format
  219. token_id
  220. only_event_fields
  221. is_invite (bool): Whether this is an invite that is being sent to the
  222. invitee
  223. Returns:
  224. dict
  225. """
  226. # FIXME(erikj): To handle the case of presence events and the like
  227. if not isinstance(e, EventBase):
  228. return e
  229. time_now_ms = int(time_now_ms)
  230. # Should this strip out None's?
  231. d = {k: v for k, v in e.get_dict().items()}
  232. d["event_id"] = e.event_id
  233. if "age_ts" in d["unsigned"]:
  234. d["unsigned"]["age"] = time_now_ms - d["unsigned"]["age_ts"]
  235. del d["unsigned"]["age_ts"]
  236. if "redacted_because" in e.unsigned:
  237. d["unsigned"]["redacted_because"] = serialize_event(
  238. e.unsigned["redacted_because"], time_now_ms, event_format=event_format
  239. )
  240. if token_id is not None:
  241. if token_id == getattr(e.internal_metadata, "token_id", None):
  242. txn_id = getattr(e.internal_metadata, "txn_id", None)
  243. if txn_id is not None:
  244. d["unsigned"]["transaction_id"] = txn_id
  245. # If this is an invite for somebody else, then we don't care about the
  246. # invite_room_state as that's meant solely for the invitee. Other clients
  247. # will already have the state since they're in the room.
  248. if not is_invite:
  249. d["unsigned"].pop("invite_room_state", None)
  250. if as_client_event:
  251. d = event_format(d)
  252. if only_event_fields:
  253. if not isinstance(only_event_fields, list) or not all(
  254. isinstance(f, str) for f in only_event_fields
  255. ):
  256. raise TypeError("only_event_fields must be a list of strings")
  257. d = only_fields(d, only_event_fields)
  258. return d
  259. class EventClientSerializer(object):
  260. """Serializes events that are to be sent to clients.
  261. This is used for bundling extra information with any events to be sent to
  262. clients.
  263. """
  264. def __init__(self, hs):
  265. self.store = hs.get_datastore()
  266. self.experimental_msc1849_support_enabled = (
  267. hs.config.experimental_msc1849_support_enabled
  268. )
  269. @defer.inlineCallbacks
  270. def serialize_event(self, event, time_now, bundle_aggregations=True, **kwargs):
  271. """Serializes a single event.
  272. Args:
  273. event (EventBase)
  274. time_now (int): The current time in milliseconds
  275. bundle_aggregations (bool): Whether to bundle in related events
  276. **kwargs: Arguments to pass to `serialize_event`
  277. Returns:
  278. Deferred[dict]: The serialized event
  279. """
  280. # To handle the case of presence events and the like
  281. if not isinstance(event, EventBase):
  282. return event
  283. event_id = event.event_id
  284. serialized_event = serialize_event(event, time_now, **kwargs)
  285. # If MSC1849 is enabled then we need to look if there are any relations
  286. # we need to bundle in with the event.
  287. # Do not bundle relations if the event has been redacted
  288. if not event.internal_metadata.is_redacted() and (
  289. self.experimental_msc1849_support_enabled and bundle_aggregations
  290. ):
  291. annotations = yield self.store.get_aggregation_groups_for_event(event_id)
  292. references = yield self.store.get_relations_for_event(
  293. event_id, RelationTypes.REFERENCE, direction="f"
  294. )
  295. if annotations.chunk:
  296. r = serialized_event["unsigned"].setdefault("m.relations", {})
  297. r[RelationTypes.ANNOTATION] = annotations.to_dict()
  298. if references.chunk:
  299. r = serialized_event["unsigned"].setdefault("m.relations", {})
  300. r[RelationTypes.REFERENCE] = references.to_dict()
  301. edit = None
  302. if event.type == EventTypes.Message:
  303. edit = yield self.store.get_applicable_edit(event_id)
  304. if edit:
  305. # If there is an edit replace the content, preserving existing
  306. # relations.
  307. relations = event.content.get("m.relates_to")
  308. serialized_event["content"] = edit.content.get("m.new_content", {})
  309. if relations:
  310. serialized_event["content"]["m.relates_to"] = relations
  311. else:
  312. serialized_event["content"].pop("m.relates_to", None)
  313. r = serialized_event["unsigned"].setdefault("m.relations", {})
  314. r[RelationTypes.REPLACE] = {
  315. "event_id": edit.event_id,
  316. "origin_server_ts": edit.origin_server_ts,
  317. "sender": edit.sender,
  318. }
  319. return serialized_event
  320. def serialize_events(self, events, time_now, **kwargs):
  321. """Serializes multiple events.
  322. Args:
  323. event (iter[EventBase])
  324. time_now (int): The current time in milliseconds
  325. **kwargs: Arguments to pass to `serialize_event`
  326. Returns:
  327. Deferred[list[dict]]: The list of serialized events
  328. """
  329. return yieldable_gather_results(
  330. self.serialize_event, events, time_now=time_now, **kwargs
  331. )
  332. def copy_power_levels_contents(
  333. old_power_levels: Mapping[str, Union[int, Mapping[str, int]]]
  334. ):
  335. """Copy the content of a power_levels event, unfreezing frozendicts along the way
  336. Raises:
  337. TypeError if the input does not look like a valid power levels event content
  338. """
  339. if not isinstance(old_power_levels, collections.Mapping):
  340. raise TypeError("Not a valid power-levels content: %r" % (old_power_levels,))
  341. power_levels = {}
  342. for k, v in old_power_levels.items():
  343. if isinstance(v, int):
  344. power_levels[k] = v
  345. continue
  346. if isinstance(v, collections.Mapping):
  347. power_levels[k] = h = {}
  348. for k1, v1 in v.items():
  349. # we should only have one level of nesting
  350. if not isinstance(v1, int):
  351. raise TypeError(
  352. "Invalid power_levels value for %s.%s: %r" % (k, k1, v1)
  353. )
  354. h[k1] = v1
  355. continue
  356. raise TypeError("Invalid power_levels value for %s: %r" % (k, v))
  357. return power_levels
  358. def validate_canonicaljson(value: Any):
  359. """
  360. Ensure that the JSON object is valid according to the rules of canonical JSON.
  361. See the appendix section 3.1: Canonical JSON.
  362. This rejects JSON that has:
  363. * An integer outside the range of [-2 ^ 53 + 1, 2 ^ 53 - 1]
  364. * Floats
  365. * NaN, Infinity, -Infinity
  366. """
  367. if isinstance(value, int):
  368. if value <= -(2 ** 53) or 2 ** 53 <= value:
  369. raise SynapseError(400, "JSON integer out of range", Codes.BAD_JSON)
  370. elif isinstance(value, float):
  371. # Note that Infinity, -Infinity, and NaN are also considered floats.
  372. raise SynapseError(400, "Bad JSON value: float", Codes.BAD_JSON)
  373. elif isinstance(value, (dict, frozendict)):
  374. for v in value.values():
  375. validate_canonicaljson(v)
  376. elif isinstance(value, (list, tuple)):
  377. for i in value:
  378. validate_canonicaljson(i)
  379. elif not isinstance(value, (bool, str)) and value is not None:
  380. # Other potential JSON values (bool, None, str) are safe.
  381. raise SynapseError(400, "Unknown JSON value", Codes.BAD_JSON)