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.
 
 
 
 
 
 

289 rivejä
11 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. from typing import Iterable, List, Type, Union, cast
  16. import jsonschema
  17. from pydantic import Field, StrictBool, StrictStr
  18. from synapse.api.constants import (
  19. MAX_ALIAS_LENGTH,
  20. EventContentFields,
  21. EventTypes,
  22. Membership,
  23. )
  24. from synapse.api.errors import Codes, SynapseError
  25. from synapse.api.room_versions import EventFormatVersions
  26. from synapse.config.homeserver import HomeServerConfig
  27. from synapse.events import EventBase
  28. from synapse.events.builder import EventBuilder
  29. from synapse.events.utils import (
  30. CANONICALJSON_MAX_INT,
  31. CANONICALJSON_MIN_INT,
  32. validate_canonicaljson,
  33. )
  34. from synapse.federation.federation_server import server_matches_acl_event
  35. from synapse.http.servlet import validate_json_object
  36. from synapse.rest.models import RequestBodyModel
  37. from synapse.types import EventID, JsonDict, RoomID, UserID
  38. class EventValidator:
  39. def validate_new(self, event: EventBase, config: HomeServerConfig) -> None:
  40. """Validates the event has roughly the right format
  41. Suitable for checking a locally-created event. It has stricter checks than
  42. is appropriate for an event received over federation (for which, see
  43. event_auth.validate_event_for_room_version)
  44. Args:
  45. event: The event to validate.
  46. config: The homeserver's configuration.
  47. """
  48. self.validate_builder(event)
  49. if event.format_version == EventFormatVersions.ROOM_V1_V2:
  50. EventID.from_string(event.event_id)
  51. required = [
  52. "auth_events",
  53. "content",
  54. "hashes",
  55. "origin",
  56. "prev_events",
  57. "sender",
  58. "type",
  59. ]
  60. for k in required:
  61. if k not in event:
  62. raise SynapseError(400, "Event does not have key %s" % (k,))
  63. # Check that the following keys have string values
  64. event_strings = ["origin"]
  65. for s in event_strings:
  66. if not isinstance(getattr(event, s), str):
  67. raise SynapseError(400, "'%s' not a string type" % (s,))
  68. # Depending on the room version, ensure the data is spec compliant JSON.
  69. if event.room_version.strict_canonicaljson:
  70. # Note that only the client controlled portion of the event is
  71. # checked, since we trust the portions of the event we created.
  72. validate_canonicaljson(event.content)
  73. if event.type == EventTypes.Aliases:
  74. if "aliases" in event.content:
  75. for alias in event.content["aliases"]:
  76. if len(alias) > MAX_ALIAS_LENGTH:
  77. raise SynapseError(
  78. 400,
  79. (
  80. "Can't create aliases longer than"
  81. " %d characters" % (MAX_ALIAS_LENGTH,)
  82. ),
  83. Codes.INVALID_PARAM,
  84. )
  85. elif event.type == EventTypes.Retention:
  86. self._validate_retention(event)
  87. elif event.type == EventTypes.ServerACL:
  88. if not server_matches_acl_event(config.server.server_name, event):
  89. raise SynapseError(
  90. 400, "Can't create an ACL event that denies the local server"
  91. )
  92. elif event.type == EventTypes.PowerLevels:
  93. try:
  94. jsonschema.validate(
  95. instance=event.content,
  96. schema=POWER_LEVELS_SCHEMA,
  97. cls=POWER_LEVELS_VALIDATOR,
  98. )
  99. except jsonschema.ValidationError as e:
  100. if e.path:
  101. # example: "users_default": '0' is not of type 'integer'
  102. # cast safety: path entries can be integers, if we fail to validate
  103. # items in an array. However, the POWER_LEVELS_SCHEMA doesn't expect
  104. # to see any arrays.
  105. message = (
  106. '"' + cast(str, e.path[-1]) + '": ' + e.message # noqa: B306
  107. )
  108. # jsonschema.ValidationError.message is a valid attribute
  109. else:
  110. # example: '0' is not of type 'integer'
  111. message = e.message # noqa: B306
  112. # jsonschema.ValidationError.message is a valid attribute
  113. raise SynapseError(
  114. code=400,
  115. msg=message,
  116. errcode=Codes.BAD_JSON,
  117. )
  118. # If the event contains a mentions key, validate it.
  119. if EventContentFields.MENTIONS in event.content:
  120. validate_json_object(event.content[EventContentFields.MENTIONS], Mentions)
  121. def _validate_retention(self, event: EventBase) -> None:
  122. """Checks that an event that defines the retention policy for a room respects the
  123. format enforced by the spec.
  124. Args:
  125. event: The event to validate.
  126. """
  127. if not event.is_state():
  128. raise SynapseError(code=400, msg="must be a state event")
  129. min_lifetime = event.content.get("min_lifetime")
  130. max_lifetime = event.content.get("max_lifetime")
  131. if min_lifetime is not None:
  132. if type(min_lifetime) is not int: # noqa: E721
  133. raise SynapseError(
  134. code=400,
  135. msg="'min_lifetime' must be an integer",
  136. errcode=Codes.BAD_JSON,
  137. )
  138. if max_lifetime is not None:
  139. if type(max_lifetime) is not int: # noqa: E721
  140. raise SynapseError(
  141. code=400,
  142. msg="'max_lifetime' must be an integer",
  143. errcode=Codes.BAD_JSON,
  144. )
  145. if (
  146. min_lifetime is not None
  147. and max_lifetime is not None
  148. and min_lifetime > max_lifetime
  149. ):
  150. raise SynapseError(
  151. code=400,
  152. msg="'min_lifetime' can't be greater than 'max_lifetime",
  153. errcode=Codes.BAD_JSON,
  154. )
  155. def validate_builder(self, event: Union[EventBase, EventBuilder]) -> None:
  156. """Validates that the builder/event has roughly the right format. Only
  157. checks values that we expect a proto event to have, rather than all the
  158. fields an event would have
  159. """
  160. strings = ["room_id", "sender", "type"]
  161. if hasattr(event, "state_key"):
  162. strings.append("state_key")
  163. for s in strings:
  164. if not isinstance(getattr(event, s), str):
  165. raise SynapseError(400, "Not '%s' a string type" % (s,))
  166. RoomID.from_string(event.room_id)
  167. UserID.from_string(event.sender)
  168. if event.type == EventTypes.Message:
  169. strings = ["body", "msgtype"]
  170. self._ensure_strings(event.content, strings)
  171. elif event.type == EventTypes.Topic:
  172. self._ensure_strings(event.content, ["topic"])
  173. self._ensure_state_event(event)
  174. elif event.type == EventTypes.Name:
  175. self._ensure_strings(event.content, ["name"])
  176. self._ensure_state_event(event)
  177. elif event.type == EventTypes.Member:
  178. if "membership" not in event.content:
  179. raise SynapseError(400, "Content has not membership key")
  180. if event.content["membership"] not in Membership.LIST:
  181. raise SynapseError(400, "Invalid membership key")
  182. self._ensure_state_event(event)
  183. elif event.type == EventTypes.Tombstone:
  184. if "replacement_room" not in event.content:
  185. raise SynapseError(400, "Content has no replacement_room key")
  186. if event.content["replacement_room"] == event.room_id:
  187. raise SynapseError(
  188. 400, "Tombstone cannot reference the room it was sent in"
  189. )
  190. self._ensure_state_event(event)
  191. def _ensure_strings(self, d: JsonDict, keys: Iterable[str]) -> None:
  192. for s in keys:
  193. if s not in d:
  194. raise SynapseError(400, "'%s' not in content" % (s,))
  195. if not isinstance(d[s], str):
  196. raise SynapseError(400, "'%s' not a string type" % (s,))
  197. def _ensure_state_event(self, event: Union[EventBase, EventBuilder]) -> None:
  198. if not event.is_state():
  199. raise SynapseError(400, "'%s' must be state events" % (event.type,))
  200. POWER_LEVELS_SCHEMA = {
  201. "type": "object",
  202. "properties": {
  203. "ban": {"$ref": "#/definitions/int"},
  204. "events": {"$ref": "#/definitions/objectOfInts"},
  205. "events_default": {"$ref": "#/definitions/int"},
  206. "invite": {"$ref": "#/definitions/int"},
  207. "kick": {"$ref": "#/definitions/int"},
  208. "notifications": {"$ref": "#/definitions/objectOfInts"},
  209. "redact": {"$ref": "#/definitions/int"},
  210. "state_default": {"$ref": "#/definitions/int"},
  211. "users": {"$ref": "#/definitions/objectOfInts"},
  212. "users_default": {"$ref": "#/definitions/int"},
  213. },
  214. "definitions": {
  215. "int": {
  216. "type": "integer",
  217. "minimum": CANONICALJSON_MIN_INT,
  218. "maximum": CANONICALJSON_MAX_INT,
  219. },
  220. "objectOfInts": {
  221. "type": "object",
  222. "additionalProperties": {"$ref": "#/definitions/int"},
  223. },
  224. },
  225. }
  226. class Mentions(RequestBodyModel):
  227. user_ids: List[StrictStr] = Field(default_factory=list)
  228. room: StrictBool = False
  229. # This could return something newer than Draft 7, but that's the current "latest"
  230. # validator.
  231. def _create_validator(schema: JsonDict) -> Type[jsonschema.Draft7Validator]:
  232. validator = jsonschema.validators.validator_for(schema)
  233. # by default jsonschema does not consider a immutabledict to be an object so
  234. # we need to use a custom type checker
  235. # https://python-jsonschema.readthedocs.io/en/stable/validate/?highlight=object#validating-with-additional-types
  236. type_checker = validator.TYPE_CHECKER.redefine(
  237. "object", lambda checker, thing: isinstance(thing, collections.abc.Mapping)
  238. )
  239. return jsonschema.validators.extend(validator, type_checker=type_checker)
  240. POWER_LEVELS_VALIDATOR = _create_validator(POWER_LEVELS_SCHEMA)