Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

298 wiersze
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.http.servlet import validate_json_object
  39. from synapse.rest.models import RequestBodyModel
  40. from synapse.storage.controllers.state import server_acl_evaluator_from_event
  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. server_acl_evaluator = server_acl_evaluator_from_event(event)
  93. if not server_acl_evaluator.server_matches_acl_event(
  94. config.server.server_name
  95. ):
  96. raise SynapseError(
  97. 400, "Can't create an ACL event that denies the local server"
  98. )
  99. elif event.type == EventTypes.PowerLevels:
  100. try:
  101. jsonschema.validate(
  102. instance=event.content,
  103. schema=POWER_LEVELS_SCHEMA,
  104. cls=POWER_LEVELS_VALIDATOR,
  105. )
  106. except jsonschema.ValidationError as e:
  107. if e.path:
  108. # example: "users_default": '0' is not of type 'integer'
  109. # cast safety: path entries can be integers, if we fail to validate
  110. # items in an array. However, the POWER_LEVELS_SCHEMA doesn't expect
  111. # to see any arrays.
  112. message = (
  113. '"' + cast(str, e.path[-1]) + '": ' + e.message # noqa: B306
  114. )
  115. # jsonschema.ValidationError.message is a valid attribute
  116. else:
  117. # example: '0' is not of type 'integer'
  118. message = e.message # noqa: B306
  119. # jsonschema.ValidationError.message is a valid attribute
  120. raise SynapseError(
  121. code=400,
  122. msg=message,
  123. errcode=Codes.BAD_JSON,
  124. )
  125. # If the event contains a mentions key, validate it.
  126. if EventContentFields.MENTIONS in event.content:
  127. validate_json_object(event.content[EventContentFields.MENTIONS], Mentions)
  128. def _validate_retention(self, event: EventBase) -> None:
  129. """Checks that an event that defines the retention policy for a room respects the
  130. format enforced by the spec.
  131. Args:
  132. event: The event to validate.
  133. """
  134. if not event.is_state():
  135. raise SynapseError(code=400, msg="must be a state event")
  136. min_lifetime = event.content.get("min_lifetime")
  137. max_lifetime = event.content.get("max_lifetime")
  138. if min_lifetime is not None:
  139. if type(min_lifetime) is not int: # noqa: E721
  140. raise SynapseError(
  141. code=400,
  142. msg="'min_lifetime' must be an integer",
  143. errcode=Codes.BAD_JSON,
  144. )
  145. if max_lifetime is not None:
  146. if type(max_lifetime) is not int: # noqa: E721
  147. raise SynapseError(
  148. code=400,
  149. msg="'max_lifetime' must be an integer",
  150. errcode=Codes.BAD_JSON,
  151. )
  152. if (
  153. min_lifetime is not None
  154. and max_lifetime is not None
  155. and min_lifetime > max_lifetime
  156. ):
  157. raise SynapseError(
  158. code=400,
  159. msg="'min_lifetime' can't be greater than 'max_lifetime",
  160. errcode=Codes.BAD_JSON,
  161. )
  162. def validate_builder(self, event: Union[EventBase, EventBuilder]) -> None:
  163. """Validates that the builder/event has roughly the right format. Only
  164. checks values that we expect a proto event to have, rather than all the
  165. fields an event would have
  166. """
  167. strings = ["room_id", "sender", "type"]
  168. if hasattr(event, "state_key"):
  169. strings.append("state_key")
  170. for s in strings:
  171. if not isinstance(getattr(event, s), str):
  172. raise SynapseError(400, "Not '%s' a string type" % (s,))
  173. RoomID.from_string(event.room_id)
  174. UserID.from_string(event.sender)
  175. if event.type == EventTypes.Message:
  176. strings = ["body", "msgtype"]
  177. self._ensure_strings(event.content, strings)
  178. elif event.type == EventTypes.Topic:
  179. self._ensure_strings(event.content, ["topic"])
  180. self._ensure_state_event(event)
  181. elif event.type == EventTypes.Name:
  182. self._ensure_strings(event.content, ["name"])
  183. self._ensure_state_event(event)
  184. elif event.type == EventTypes.Member:
  185. if "membership" not in event.content:
  186. raise SynapseError(400, "Content has not membership key")
  187. if event.content["membership"] not in Membership.LIST:
  188. raise SynapseError(400, "Invalid membership key")
  189. self._ensure_state_event(event)
  190. elif event.type == EventTypes.Tombstone:
  191. if "replacement_room" not in event.content:
  192. raise SynapseError(400, "Content has no replacement_room key")
  193. if event.content["replacement_room"] == event.room_id:
  194. raise SynapseError(
  195. 400, "Tombstone cannot reference the room it was sent in"
  196. )
  197. self._ensure_state_event(event)
  198. def _ensure_strings(self, d: JsonDict, keys: StrCollection) -> None:
  199. for s in keys:
  200. if s not in d:
  201. raise SynapseError(400, "'%s' not in content" % (s,))
  202. if not isinstance(d[s], str):
  203. raise SynapseError(400, "'%s' not a string type" % (s,))
  204. def _ensure_state_event(self, event: Union[EventBase, EventBuilder]) -> None:
  205. if not event.is_state():
  206. raise SynapseError(400, "'%s' must be state events" % (event.type,))
  207. POWER_LEVELS_SCHEMA = {
  208. "type": "object",
  209. "properties": {
  210. "ban": {"$ref": "#/definitions/int"},
  211. "events": {"$ref": "#/definitions/objectOfInts"},
  212. "events_default": {"$ref": "#/definitions/int"},
  213. "invite": {"$ref": "#/definitions/int"},
  214. "kick": {"$ref": "#/definitions/int"},
  215. "notifications": {"$ref": "#/definitions/objectOfInts"},
  216. "redact": {"$ref": "#/definitions/int"},
  217. "state_default": {"$ref": "#/definitions/int"},
  218. "users": {"$ref": "#/definitions/objectOfInts"},
  219. "users_default": {"$ref": "#/definitions/int"},
  220. },
  221. "definitions": {
  222. "int": {
  223. "type": "integer",
  224. "minimum": CANONICALJSON_MIN_INT,
  225. "maximum": CANONICALJSON_MAX_INT,
  226. },
  227. "objectOfInts": {
  228. "type": "object",
  229. "additionalProperties": {"$ref": "#/definitions/int"},
  230. },
  231. },
  232. }
  233. class Mentions(RequestBodyModel):
  234. user_ids: List[StrictStr] = Field(default_factory=list)
  235. room: StrictBool = False
  236. # This could return something newer than Draft 7, but that's the current "latest"
  237. # validator.
  238. def _create_validator(schema: JsonDict) -> Type[jsonschema.Draft7Validator]:
  239. validator = jsonschema.validators.validator_for(schema)
  240. # by default jsonschema does not consider a immutabledict to be an object so
  241. # we need to use a custom type checker
  242. # https://python-jsonschema.readthedocs.io/en/stable/validate/?highlight=object#validating-with-additional-types
  243. type_checker = validator.TYPE_CHECKER.redefine(
  244. "object", lambda checker, thing: isinstance(thing, collections.abc.Mapping)
  245. )
  246. return jsonschema.validators.extend(validator, type_checker=type_checker)
  247. POWER_LEVELS_VALIDATOR = _create_validator(POWER_LEVELS_SCHEMA)