validator.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 (
  120. EventContentFields.MSC3952_MENTIONS in event.content
  121. and config.experimental.msc3952_intentional_mentions
  122. ):
  123. validate_json_object(
  124. event.content[EventContentFields.MSC3952_MENTIONS], Mentions
  125. )
  126. def _validate_retention(self, event: EventBase) -> None:
  127. """Checks that an event that defines the retention policy for a room respects the
  128. format enforced by the spec.
  129. Args:
  130. event: The event to validate.
  131. """
  132. if not event.is_state():
  133. raise SynapseError(code=400, msg="must be a state event")
  134. min_lifetime = event.content.get("min_lifetime")
  135. max_lifetime = event.content.get("max_lifetime")
  136. if min_lifetime is not None:
  137. if type(min_lifetime) is not int:
  138. raise SynapseError(
  139. code=400,
  140. msg="'min_lifetime' must be an integer",
  141. errcode=Codes.BAD_JSON,
  142. )
  143. if max_lifetime is not None:
  144. if type(max_lifetime) is not int:
  145. raise SynapseError(
  146. code=400,
  147. msg="'max_lifetime' must be an integer",
  148. errcode=Codes.BAD_JSON,
  149. )
  150. if (
  151. min_lifetime is not None
  152. and max_lifetime is not None
  153. and min_lifetime > max_lifetime
  154. ):
  155. raise SynapseError(
  156. code=400,
  157. msg="'min_lifetime' can't be greater than 'max_lifetime",
  158. errcode=Codes.BAD_JSON,
  159. )
  160. def validate_builder(self, event: Union[EventBase, EventBuilder]) -> None:
  161. """Validates that the builder/event has roughly the right format. Only
  162. checks values that we expect a proto event to have, rather than all the
  163. fields an event would have
  164. """
  165. strings = ["room_id", "sender", "type"]
  166. if hasattr(event, "state_key"):
  167. strings.append("state_key")
  168. for s in strings:
  169. if not isinstance(getattr(event, s), str):
  170. raise SynapseError(400, "Not '%s' a string type" % (s,))
  171. RoomID.from_string(event.room_id)
  172. UserID.from_string(event.sender)
  173. if event.type == EventTypes.Message:
  174. strings = ["body", "msgtype"]
  175. self._ensure_strings(event.content, strings)
  176. elif event.type == EventTypes.Topic:
  177. self._ensure_strings(event.content, ["topic"])
  178. self._ensure_state_event(event)
  179. elif event.type == EventTypes.Name:
  180. self._ensure_strings(event.content, ["name"])
  181. self._ensure_state_event(event)
  182. elif event.type == EventTypes.Member:
  183. if "membership" not in event.content:
  184. raise SynapseError(400, "Content has not membership key")
  185. if event.content["membership"] not in Membership.LIST:
  186. raise SynapseError(400, "Invalid membership key")
  187. self._ensure_state_event(event)
  188. elif event.type == EventTypes.Tombstone:
  189. if "replacement_room" not in event.content:
  190. raise SynapseError(400, "Content has no replacement_room key")
  191. if event.content["replacement_room"] == event.room_id:
  192. raise SynapseError(
  193. 400, "Tombstone cannot reference the room it was sent in"
  194. )
  195. self._ensure_state_event(event)
  196. def _ensure_strings(self, d: JsonDict, keys: Iterable[str]) -> None:
  197. for s in keys:
  198. if s not in d:
  199. raise SynapseError(400, "'%s' not in content" % (s,))
  200. if not isinstance(d[s], str):
  201. raise SynapseError(400, "'%s' not a string type" % (s,))
  202. def _ensure_state_event(self, event: Union[EventBase, EventBuilder]) -> None:
  203. if not event.is_state():
  204. raise SynapseError(400, "'%s' must be state events" % (event.type,))
  205. POWER_LEVELS_SCHEMA = {
  206. "type": "object",
  207. "properties": {
  208. "ban": {"$ref": "#/definitions/int"},
  209. "events": {"$ref": "#/definitions/objectOfInts"},
  210. "events_default": {"$ref": "#/definitions/int"},
  211. "invite": {"$ref": "#/definitions/int"},
  212. "kick": {"$ref": "#/definitions/int"},
  213. "notifications": {"$ref": "#/definitions/objectOfInts"},
  214. "redact": {"$ref": "#/definitions/int"},
  215. "state_default": {"$ref": "#/definitions/int"},
  216. "users": {"$ref": "#/definitions/objectOfInts"},
  217. "users_default": {"$ref": "#/definitions/int"},
  218. },
  219. "definitions": {
  220. "int": {
  221. "type": "integer",
  222. "minimum": CANONICALJSON_MIN_INT,
  223. "maximum": CANONICALJSON_MAX_INT,
  224. },
  225. "objectOfInts": {
  226. "type": "object",
  227. "additionalProperties": {"$ref": "#/definitions/int"},
  228. },
  229. },
  230. }
  231. class Mentions(RequestBodyModel):
  232. user_ids: List[StrictStr] = Field(default_factory=list)
  233. room: StrictBool = False
  234. # This could return something newer than Draft 7, but that's the current "latest"
  235. # validator.
  236. def _create_validator(schema: JsonDict) -> Type[jsonschema.Draft7Validator]:
  237. validator = jsonschema.validators.validator_for(schema)
  238. # by default jsonschema does not consider a immutabledict to be an object so
  239. # we need to use a custom type checker
  240. # https://python-jsonschema.readthedocs.io/en/stable/validate/?highlight=object#validating-with-additional-types
  241. type_checker = validator.TYPE_CHECKER.redefine(
  242. "object", lambda checker, thing: isinstance(thing, collections.abc.Mapping)
  243. )
  244. return jsonschema.validators.extend(validator, type_checker=type_checker)
  245. POWER_LEVELS_VALIDATOR = _create_validator(POWER_LEVELS_SCHEMA)