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.
 
 
 
 
 
 

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