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.
 
 
 
 
 
 

510 lines
16 KiB

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