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.
 
 
 
 
 
 

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