errors.py 12 KB

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