errors.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Contains exceptions and error codes."""
  17. import logging
  18. from six import iteritems
  19. from six.moves import http_client
  20. from canonicaljson import json
  21. logger = logging.getLogger(__name__)
  22. class Codes(object):
  23. UNRECOGNIZED = "M_UNRECOGNIZED"
  24. UNAUTHORIZED = "M_UNAUTHORIZED"
  25. FORBIDDEN = "M_FORBIDDEN"
  26. BAD_JSON = "M_BAD_JSON"
  27. NOT_JSON = "M_NOT_JSON"
  28. USER_IN_USE = "M_USER_IN_USE"
  29. ROOM_IN_USE = "M_ROOM_IN_USE"
  30. BAD_PAGINATION = "M_BAD_PAGINATION"
  31. BAD_STATE = "M_BAD_STATE"
  32. UNKNOWN = "M_UNKNOWN"
  33. NOT_FOUND = "M_NOT_FOUND"
  34. MISSING_TOKEN = "M_MISSING_TOKEN"
  35. UNKNOWN_TOKEN = "M_UNKNOWN_TOKEN"
  36. GUEST_ACCESS_FORBIDDEN = "M_GUEST_ACCESS_FORBIDDEN"
  37. LIMIT_EXCEEDED = "M_LIMIT_EXCEEDED"
  38. CAPTCHA_NEEDED = "M_CAPTCHA_NEEDED"
  39. CAPTCHA_INVALID = "M_CAPTCHA_INVALID"
  40. MISSING_PARAM = "M_MISSING_PARAM"
  41. INVALID_PARAM = "M_INVALID_PARAM"
  42. TOO_LARGE = "M_TOO_LARGE"
  43. EXCLUSIVE = "M_EXCLUSIVE"
  44. THREEPID_AUTH_FAILED = "M_THREEPID_AUTH_FAILED"
  45. THREEPID_IN_USE = "M_THREEPID_IN_USE"
  46. THREEPID_NOT_FOUND = "M_THREEPID_NOT_FOUND"
  47. THREEPID_DENIED = "M_THREEPID_DENIED"
  48. INVALID_USERNAME = "M_INVALID_USERNAME"
  49. SERVER_NOT_TRUSTED = "M_SERVER_NOT_TRUSTED"
  50. CONSENT_NOT_GIVEN = "M_CONSENT_NOT_GIVEN"
  51. CANNOT_LEAVE_SERVER_NOTICE_ROOM = "M_CANNOT_LEAVE_SERVER_NOTICE_ROOM"
  52. MAU_LIMIT_EXCEEDED = "M_MAU_LIMIT_EXCEEDED"
  53. UNSUPPORTED_ROOM_VERSION = "M_UNSUPPORTED_ROOM_VERSION"
  54. INCOMPATIBLE_ROOM_VERSION = "M_INCOMPATIBLE_ROOM_VERSION"
  55. class CodeMessageException(RuntimeError):
  56. """An exception with integer code and message string attributes.
  57. Attributes:
  58. code (int): HTTP error code
  59. msg (str): string describing the error
  60. """
  61. def __init__(self, code, msg):
  62. super(CodeMessageException, self).__init__("%d: %s" % (code, msg))
  63. self.code = code
  64. self.msg = msg
  65. class SynapseError(CodeMessageException):
  66. """A base exception type for matrix errors which have an errcode and error
  67. message (as well as an HTTP status code).
  68. Attributes:
  69. errcode (str): Matrix error code e.g 'M_FORBIDDEN'
  70. """
  71. def __init__(self, code, msg, errcode=Codes.UNKNOWN):
  72. """Constructs a synapse error.
  73. Args:
  74. code (int): The integer error code (an HTTP response code)
  75. msg (str): The human-readable error message.
  76. errcode (str): The matrix error code e.g 'M_FORBIDDEN'
  77. """
  78. super(SynapseError, self).__init__(code, msg)
  79. self.errcode = errcode
  80. def error_dict(self):
  81. return cs_error(
  82. self.msg,
  83. self.errcode,
  84. )
  85. class ProxiedRequestError(SynapseError):
  86. """An error from a general matrix endpoint, eg. from a proxied Matrix API call.
  87. Attributes:
  88. errcode (str): Matrix error code e.g 'M_FORBIDDEN'
  89. """
  90. def __init__(self, code, msg, errcode=Codes.UNKNOWN, additional_fields=None):
  91. super(ProxiedRequestError, self).__init__(
  92. code, msg, errcode
  93. )
  94. if additional_fields is None:
  95. self._additional_fields = {}
  96. else:
  97. self._additional_fields = dict(additional_fields)
  98. def error_dict(self):
  99. return cs_error(
  100. self.msg,
  101. self.errcode,
  102. **self._additional_fields
  103. )
  104. class ConsentNotGivenError(SynapseError):
  105. """The error returned to the client when the user has not consented to the
  106. privacy policy.
  107. """
  108. def __init__(self, msg, consent_uri):
  109. """Constructs a ConsentNotGivenError
  110. Args:
  111. msg (str): The human-readable error message
  112. consent_url (str): The URL where the user can give their consent
  113. """
  114. super(ConsentNotGivenError, self).__init__(
  115. code=http_client.FORBIDDEN,
  116. msg=msg,
  117. errcode=Codes.CONSENT_NOT_GIVEN
  118. )
  119. self._consent_uri = consent_uri
  120. def error_dict(self):
  121. return cs_error(
  122. self.msg,
  123. self.errcode,
  124. consent_uri=self._consent_uri
  125. )
  126. class RegistrationError(SynapseError):
  127. """An error raised when a registration event fails."""
  128. pass
  129. class FederationDeniedError(SynapseError):
  130. """An error raised when the server tries to federate with a server which
  131. is not on its federation whitelist.
  132. Attributes:
  133. destination (str): The destination which has been denied
  134. """
  135. def __init__(self, destination):
  136. """Raised by federation client or server to indicate that we are
  137. are deliberately not attempting to contact a given server because it is
  138. not on our federation whitelist.
  139. Args:
  140. destination (str): the domain in question
  141. """
  142. self.destination = destination
  143. super(FederationDeniedError, self).__init__(
  144. code=403,
  145. msg="Federation denied with %s." % (self.destination,),
  146. errcode=Codes.FORBIDDEN,
  147. )
  148. class InteractiveAuthIncompleteError(Exception):
  149. """An error raised when UI auth is not yet complete
  150. (This indicates we should return a 401 with 'result' as the body)
  151. Attributes:
  152. result (dict): the server response to the request, which should be
  153. passed back to the client
  154. """
  155. def __init__(self, result):
  156. super(InteractiveAuthIncompleteError, self).__init__(
  157. "Interactive auth not yet complete",
  158. )
  159. self.result = result
  160. class UnrecognizedRequestError(SynapseError):
  161. """An error indicating we don't understand the request you're trying to make"""
  162. def __init__(self, *args, **kwargs):
  163. if "errcode" not in kwargs:
  164. kwargs["errcode"] = Codes.UNRECOGNIZED
  165. message = None
  166. if len(args) == 0:
  167. message = "Unrecognized request"
  168. else:
  169. message = args[0]
  170. super(UnrecognizedRequestError, self).__init__(
  171. 400,
  172. message,
  173. **kwargs
  174. )
  175. class NotFoundError(SynapseError):
  176. """An error indicating we can't find the thing you asked for"""
  177. def __init__(self, msg="Not found", errcode=Codes.NOT_FOUND):
  178. super(NotFoundError, self).__init__(
  179. 404,
  180. msg,
  181. errcode=errcode
  182. )
  183. class AuthError(SynapseError):
  184. """An error raised when there was a problem authorising an event."""
  185. def __init__(self, *args, **kwargs):
  186. if "errcode" not in kwargs:
  187. kwargs["errcode"] = Codes.FORBIDDEN
  188. super(AuthError, self).__init__(*args, **kwargs)
  189. class EventSizeError(SynapseError):
  190. """An error raised when an event is too big."""
  191. def __init__(self, *args, **kwargs):
  192. if "errcode" not in kwargs:
  193. kwargs["errcode"] = Codes.TOO_LARGE
  194. super(EventSizeError, self).__init__(413, *args, **kwargs)
  195. class EventStreamError(SynapseError):
  196. """An error raised when there a problem with the event stream."""
  197. def __init__(self, *args, **kwargs):
  198. if "errcode" not in kwargs:
  199. kwargs["errcode"] = Codes.BAD_PAGINATION
  200. super(EventStreamError, self).__init__(*args, **kwargs)
  201. class LoginError(SynapseError):
  202. """An error raised when there was a problem logging in."""
  203. pass
  204. class StoreError(SynapseError):
  205. """An error raised when there was a problem storing some data."""
  206. pass
  207. class InvalidCaptchaError(SynapseError):
  208. def __init__(self, code=400, msg="Invalid captcha.", error_url=None,
  209. errcode=Codes.CAPTCHA_INVALID):
  210. super(InvalidCaptchaError, self).__init__(code, msg, errcode)
  211. self.error_url = error_url
  212. def error_dict(self):
  213. return cs_error(
  214. self.msg,
  215. self.errcode,
  216. error_url=self.error_url,
  217. )
  218. class LimitExceededError(SynapseError):
  219. """A client has sent too many requests and is being throttled.
  220. """
  221. def __init__(self, code=429, msg="Too Many Requests", retry_after_ms=None,
  222. errcode=Codes.LIMIT_EXCEEDED):
  223. super(LimitExceededError, self).__init__(code, msg, errcode)
  224. self.retry_after_ms = retry_after_ms
  225. def error_dict(self):
  226. return cs_error(
  227. self.msg,
  228. self.errcode,
  229. retry_after_ms=self.retry_after_ms,
  230. )
  231. class IncompatibleRoomVersionError(SynapseError):
  232. """A server is trying to join a room whose version it does not support."""
  233. def __init__(self, room_version):
  234. super(IncompatibleRoomVersionError, self).__init__(
  235. code=400,
  236. msg="Your homeserver does not support the features required to "
  237. "join this room",
  238. errcode=Codes.INCOMPATIBLE_ROOM_VERSION,
  239. )
  240. self._room_version = room_version
  241. def error_dict(self):
  242. return cs_error(
  243. self.msg,
  244. self.errcode,
  245. room_version=self._room_version,
  246. )
  247. def cs_error(msg, code=Codes.UNKNOWN, **kwargs):
  248. """ Utility method for constructing an error response for client-server
  249. interactions.
  250. Args:
  251. msg (str): The error message.
  252. code (str): The error code.
  253. kwargs : Additional keys to add to the response.
  254. Returns:
  255. A dict representing the error response JSON.
  256. """
  257. err = {"error": msg, "errcode": code}
  258. for key, value in iteritems(kwargs):
  259. err[key] = value
  260. return err
  261. class FederationError(RuntimeError):
  262. """ This class is used to inform remote home servers about erroneous
  263. PDUs they sent us.
  264. FATAL: The remote server could not interpret the source event.
  265. (e.g., it was missing a required field)
  266. ERROR: The remote server interpreted the event, but it failed some other
  267. check (e.g. auth)
  268. WARN: The remote server accepted the event, but believes some part of it
  269. is wrong (e.g., it referred to an invalid event)
  270. """
  271. def __init__(self, level, code, reason, affected, source=None):
  272. if level not in ["FATAL", "ERROR", "WARN"]:
  273. raise ValueError("Level is not valid: %s" % (level,))
  274. self.level = level
  275. self.code = code
  276. self.reason = reason
  277. self.affected = affected
  278. self.source = source
  279. msg = "%s %s: %s" % (level, code, reason,)
  280. super(FederationError, self).__init__(msg)
  281. def get_dict(self):
  282. return {
  283. "level": self.level,
  284. "code": self.code,
  285. "reason": self.reason,
  286. "affected": self.affected,
  287. "source": self.source if self.source else self.affected,
  288. }
  289. class HttpResponseException(CodeMessageException):
  290. """
  291. Represents an HTTP-level failure of an outbound request
  292. Attributes:
  293. response (bytes): body of response
  294. """
  295. def __init__(self, code, msg, response):
  296. """
  297. Args:
  298. code (int): HTTP status code
  299. msg (str): reason phrase from HTTP response status line
  300. response (bytes): body of response
  301. """
  302. super(HttpResponseException, self).__init__(code, msg)
  303. self.response = response
  304. def to_synapse_error(self):
  305. """Make a SynapseError based on an HTTPResponseException
  306. This is useful when a proxied request has failed, and we need to
  307. decide how to map the failure onto a matrix error to send back to the
  308. client.
  309. An attempt is made to parse the body of the http response as a matrix
  310. error. If that succeeds, the errcode and error message from the body
  311. are used as the errcode and error message in the new synapse error.
  312. Otherwise, the errcode is set to M_UNKNOWN, and the error message is
  313. set to the reason code from the HTTP response.
  314. Returns:
  315. SynapseError:
  316. """
  317. # try to parse the body as json, to get better errcode/msg, but
  318. # default to M_UNKNOWN with the HTTP status as the error text
  319. try:
  320. j = json.loads(self.response)
  321. except ValueError:
  322. j = {}
  323. if not isinstance(j, dict):
  324. j = {}
  325. errcode = j.pop('errcode', Codes.UNKNOWN)
  326. errmsg = j.pop('error', self.msg)
  327. return ProxiedRequestError(self.code, errmsg, errcode, j)