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.
 
 
 
 
 
 

188 lines
6.9 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. from typing import Union
  15. from synapse.api.constants import MAX_ALIAS_LENGTH, EventTypes, Membership
  16. from synapse.api.errors import Codes, SynapseError
  17. from synapse.api.room_versions import EventFormatVersions
  18. from synapse.config.homeserver import HomeServerConfig
  19. from synapse.events import EventBase
  20. from synapse.events.builder import EventBuilder
  21. from synapse.events.utils import validate_canonicaljson
  22. from synapse.federation.federation_server import server_matches_acl_event
  23. from synapse.types import EventID, RoomID, UserID
  24. class EventValidator:
  25. def validate_new(self, event: EventBase, config: HomeServerConfig):
  26. """Validates the event has roughly the right format
  27. Args:
  28. event: The event to validate.
  29. config: The homeserver's configuration.
  30. """
  31. self.validate_builder(event)
  32. if event.format_version == EventFormatVersions.V1:
  33. EventID.from_string(event.event_id)
  34. required = [
  35. "auth_events",
  36. "content",
  37. "hashes",
  38. "origin",
  39. "prev_events",
  40. "sender",
  41. "type",
  42. ]
  43. for k in required:
  44. if not hasattr(event, k):
  45. raise SynapseError(400, "Event does not have key %s" % (k,))
  46. # Check that the following keys have string values
  47. event_strings = ["origin"]
  48. for s in event_strings:
  49. if not isinstance(getattr(event, s), str):
  50. raise SynapseError(400, "'%s' not a string type" % (s,))
  51. # Depending on the room version, ensure the data is spec compliant JSON.
  52. if event.room_version.strict_canonicaljson:
  53. # Note that only the client controlled portion of the event is
  54. # checked, since we trust the portions of the event we created.
  55. validate_canonicaljson(event.content)
  56. if event.type == EventTypes.Aliases:
  57. if "aliases" in event.content:
  58. for alias in event.content["aliases"]:
  59. if len(alias) > MAX_ALIAS_LENGTH:
  60. raise SynapseError(
  61. 400,
  62. (
  63. "Can't create aliases longer than"
  64. " %d characters" % (MAX_ALIAS_LENGTH,)
  65. ),
  66. Codes.INVALID_PARAM,
  67. )
  68. if event.type == EventTypes.Retention:
  69. self._validate_retention(event)
  70. if event.type == EventTypes.ServerACL:
  71. if not server_matches_acl_event(config.server_name, event):
  72. raise SynapseError(
  73. 400, "Can't create an ACL event that denies the local server"
  74. )
  75. def _validate_retention(self, event: EventBase):
  76. """Checks that an event that defines the retention policy for a room respects the
  77. format enforced by the spec.
  78. Args:
  79. event: The event to validate.
  80. """
  81. if not event.is_state():
  82. raise SynapseError(code=400, msg="must be a state event")
  83. min_lifetime = event.content.get("min_lifetime")
  84. max_lifetime = event.content.get("max_lifetime")
  85. if min_lifetime is not None:
  86. if not isinstance(min_lifetime, int):
  87. raise SynapseError(
  88. code=400,
  89. msg="'min_lifetime' must be an integer",
  90. errcode=Codes.BAD_JSON,
  91. )
  92. if max_lifetime is not None:
  93. if not isinstance(max_lifetime, int):
  94. raise SynapseError(
  95. code=400,
  96. msg="'max_lifetime' must be an integer",
  97. errcode=Codes.BAD_JSON,
  98. )
  99. if (
  100. min_lifetime is not None
  101. and max_lifetime is not None
  102. and min_lifetime > max_lifetime
  103. ):
  104. raise SynapseError(
  105. code=400,
  106. msg="'min_lifetime' can't be greater than 'max_lifetime",
  107. errcode=Codes.BAD_JSON,
  108. )
  109. def validate_builder(self, event: Union[EventBase, EventBuilder]):
  110. """Validates that the builder/event has roughly the right format. Only
  111. checks values that we expect a proto event to have, rather than all the
  112. fields an event would have
  113. """
  114. strings = ["room_id", "sender", "type"]
  115. if hasattr(event, "state_key"):
  116. strings.append("state_key")
  117. for s in strings:
  118. if not isinstance(getattr(event, s), str):
  119. raise SynapseError(400, "Not '%s' a string type" % (s,))
  120. RoomID.from_string(event.room_id)
  121. UserID.from_string(event.sender)
  122. if event.type == EventTypes.Message:
  123. strings = ["body", "msgtype"]
  124. self._ensure_strings(event.content, strings)
  125. elif event.type == EventTypes.Topic:
  126. self._ensure_strings(event.content, ["topic"])
  127. self._ensure_state_event(event)
  128. elif event.type == EventTypes.Name:
  129. self._ensure_strings(event.content, ["name"])
  130. self._ensure_state_event(event)
  131. elif event.type == EventTypes.Member:
  132. if "membership" not in event.content:
  133. raise SynapseError(400, "Content has not membership key")
  134. if event.content["membership"] not in Membership.LIST:
  135. raise SynapseError(400, "Invalid membership key")
  136. self._ensure_state_event(event)
  137. elif event.type == EventTypes.Tombstone:
  138. if "replacement_room" not in event.content:
  139. raise SynapseError(400, "Content has no replacement_room key")
  140. if event.content["replacement_room"] == event.room_id:
  141. raise SynapseError(
  142. 400, "Tombstone cannot reference the room it was sent in"
  143. )
  144. self._ensure_state_event(event)
  145. def _ensure_strings(self, d, keys):
  146. for s in keys:
  147. if s not in d:
  148. raise SynapseError(400, "'%s' not in content" % (s,))
  149. if not isinstance(d[s], str):
  150. raise SynapseError(400, "'%s' not a string type" % (s,))
  151. def _ensure_state_event(self, event):
  152. if not event.is_state():
  153. raise SynapseError(400, "'%s' must be state events" % (event.type,))