errors.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. RESOURCE_LIMIT_EXCEEDED = "M_RESOURCE_LIMIT_EXCEEDED"
  53. UNSUPPORTED_ROOM_VERSION = "M_UNSUPPORTED_ROOM_VERSION"
  54. INCOMPATIBLE_ROOM_VERSION = "M_INCOMPATIBLE_ROOM_VERSION"
  55. WRONG_ROOM_KEYS_VERSION = "M_WRONG_ROOM_KEYS_VERSION"
  56. class CodeMessageException(RuntimeError):
  57. """An exception with integer code and message string attributes.
  58. Attributes:
  59. code (int): HTTP error code
  60. msg (str): string describing the error
  61. """
  62. def __init__(self, code, msg):
  63. super(CodeMessageException, self).__init__("%d: %s" % (code, msg))
  64. self.code = code
  65. self.msg = msg
  66. class SynapseError(CodeMessageException):
  67. """A base exception type for matrix errors which have an errcode and error
  68. message (as well as an HTTP status code).
  69. Attributes:
  70. errcode (str): Matrix error code e.g 'M_FORBIDDEN'
  71. """
  72. def __init__(self, code, msg, errcode=Codes.UNKNOWN):
  73. """Constructs a synapse error.
  74. Args:
  75. code (int): The integer error code (an HTTP response code)
  76. msg (str): The human-readable error message.
  77. errcode (str): The matrix error code e.g 'M_FORBIDDEN'
  78. """
  79. super(SynapseError, self).__init__(code, msg)
  80. self.errcode = errcode
  81. def error_dict(self):
  82. return cs_error(
  83. self.msg,
  84. self.errcode,
  85. )
  86. class ProxiedRequestError(SynapseError):
  87. """An error from a general matrix endpoint, eg. from a proxied Matrix API call.
  88. Attributes:
  89. errcode (str): Matrix error code e.g 'M_FORBIDDEN'
  90. """
  91. def __init__(self, code, msg, errcode=Codes.UNKNOWN, additional_fields=None):
  92. super(ProxiedRequestError, self).__init__(
  93. code, msg, errcode
  94. )
  95. if additional_fields is None:
  96. self._additional_fields = {}
  97. else:
  98. self._additional_fields = dict(additional_fields)
  99. def error_dict(self):
  100. return cs_error(
  101. self.msg,
  102. self.errcode,
  103. **self._additional_fields
  104. )
  105. class ConsentNotGivenError(SynapseError):
  106. """The error returned to the client when the user has not consented to the
  107. privacy policy.
  108. """
  109. def __init__(self, msg, consent_uri):
  110. """Constructs a ConsentNotGivenError
  111. Args:
  112. msg (str): The human-readable error message
  113. consent_url (str): The URL where the user can give their consent
  114. """
  115. super(ConsentNotGivenError, self).__init__(
  116. code=http_client.FORBIDDEN,
  117. msg=msg,
  118. errcode=Codes.CONSENT_NOT_GIVEN
  119. )
  120. self._consent_uri = consent_uri
  121. def error_dict(self):
  122. return cs_error(
  123. self.msg,
  124. self.errcode,
  125. consent_uri=self._consent_uri
  126. )
  127. class RegistrationError(SynapseError):
  128. """An error raised when a registration event fails."""
  129. pass
  130. class FederationDeniedError(SynapseError):
  131. """An error raised when the server tries to federate with a server which
  132. is not on its federation whitelist.
  133. Attributes:
  134. destination (str): The destination which has been denied
  135. """
  136. def __init__(self, destination):
  137. """Raised by federation client or server to indicate that we are
  138. are deliberately not attempting to contact a given server because it is
  139. not on our federation whitelist.
  140. Args:
  141. destination (str): the domain in question
  142. """
  143. self.destination = destination
  144. super(FederationDeniedError, self).__init__(
  145. code=403,
  146. msg="Federation denied with %s." % (self.destination,),
  147. errcode=Codes.FORBIDDEN,
  148. )
  149. class InteractiveAuthIncompleteError(Exception):
  150. """An error raised when UI auth is not yet complete
  151. (This indicates we should return a 401 with 'result' as the body)
  152. Attributes:
  153. result (dict): the server response to the request, which should be
  154. passed back to the client
  155. """
  156. def __init__(self, result):
  157. super(InteractiveAuthIncompleteError, self).__init__(
  158. "Interactive auth not yet complete",
  159. )
  160. self.result = result
  161. class UnrecognizedRequestError(SynapseError):
  162. """An error indicating we don't understand the request you're trying to make"""
  163. def __init__(self, *args, **kwargs):
  164. if "errcode" not in kwargs:
  165. kwargs["errcode"] = Codes.UNRECOGNIZED
  166. message = None
  167. if len(args) == 0:
  168. message = "Unrecognized request"
  169. else:
  170. message = args[0]
  171. super(UnrecognizedRequestError, self).__init__(
  172. 400,
  173. message,
  174. **kwargs
  175. )
  176. class NotFoundError(SynapseError):
  177. """An error indicating we can't find the thing you asked for"""
  178. def __init__(self, msg="Not found", errcode=Codes.NOT_FOUND):
  179. super(NotFoundError, self).__init__(
  180. 404,
  181. msg,
  182. errcode=errcode
  183. )
  184. class AuthError(SynapseError):
  185. """An error raised when there was a problem authorising an event."""
  186. def __init__(self, *args, **kwargs):
  187. if "errcode" not in kwargs:
  188. kwargs["errcode"] = Codes.FORBIDDEN
  189. super(AuthError, self).__init__(*args, **kwargs)
  190. class ResourceLimitError(SynapseError):
  191. """
  192. Any error raised when there is a problem with resource usage.
  193. For instance, the monthly active user limit for the server has been exceeded
  194. """
  195. def __init__(
  196. self, code, msg,
  197. errcode=Codes.RESOURCE_LIMIT_EXCEEDED,
  198. admin_contact=None,
  199. limit_type=None,
  200. ):
  201. self.admin_contact = admin_contact
  202. self.limit_type = limit_type
  203. super(ResourceLimitError, self).__init__(code, msg, errcode=errcode)
  204. def error_dict(self):
  205. return cs_error(
  206. self.msg,
  207. self.errcode,
  208. admin_contact=self.admin_contact,
  209. limit_type=self.limit_type
  210. )
  211. class EventSizeError(SynapseError):
  212. """An error raised when an event is too big."""
  213. def __init__(self, *args, **kwargs):
  214. if "errcode" not in kwargs:
  215. kwargs["errcode"] = Codes.TOO_LARGE
  216. super(EventSizeError, self).__init__(413, *args, **kwargs)
  217. class EventStreamError(SynapseError):
  218. """An error raised when there a problem with the event stream."""
  219. def __init__(self, *args, **kwargs):
  220. if "errcode" not in kwargs:
  221. kwargs["errcode"] = Codes.BAD_PAGINATION
  222. super(EventStreamError, self).__init__(*args, **kwargs)
  223. class LoginError(SynapseError):
  224. """An error raised when there was a problem logging in."""
  225. pass
  226. class StoreError(SynapseError):
  227. """An error raised when there was a problem storing some data."""
  228. pass
  229. class InvalidCaptchaError(SynapseError):
  230. def __init__(self, code=400, msg="Invalid captcha.", error_url=None,
  231. errcode=Codes.CAPTCHA_INVALID):
  232. super(InvalidCaptchaError, self).__init__(code, msg, errcode)
  233. self.error_url = error_url
  234. def error_dict(self):
  235. return cs_error(
  236. self.msg,
  237. self.errcode,
  238. error_url=self.error_url,
  239. )
  240. class LimitExceededError(SynapseError):
  241. """A client has sent too many requests and is being throttled.
  242. """
  243. def __init__(self, code=429, msg="Too Many Requests", retry_after_ms=None,
  244. errcode=Codes.LIMIT_EXCEEDED):
  245. super(LimitExceededError, self).__init__(code, msg, errcode)
  246. self.retry_after_ms = retry_after_ms
  247. def error_dict(self):
  248. return cs_error(
  249. self.msg,
  250. self.errcode,
  251. retry_after_ms=self.retry_after_ms,
  252. )
  253. class RoomKeysVersionError(SynapseError):
  254. """A client has tried to upload to a non-current version of the room_keys store
  255. """
  256. def __init__(self, current_version):
  257. """
  258. Args:
  259. current_version (str): the current version of the store they should have used
  260. """
  261. super(RoomKeysVersionError, self).__init__(
  262. 403, "Wrong room_keys version", Codes.WRONG_ROOM_KEYS_VERSION
  263. )
  264. self.current_version = current_version
  265. class IncompatibleRoomVersionError(SynapseError):
  266. """A server is trying to join a room whose version it does not support."""
  267. def __init__(self, room_version):
  268. super(IncompatibleRoomVersionError, self).__init__(
  269. code=400,
  270. msg="Your homeserver does not support the features required to "
  271. "join this room",
  272. errcode=Codes.INCOMPATIBLE_ROOM_VERSION,
  273. )
  274. self._room_version = room_version
  275. def error_dict(self):
  276. return cs_error(
  277. self.msg,
  278. self.errcode,
  279. room_version=self._room_version,
  280. )
  281. class RequestSendFailed(RuntimeError):
  282. """Sending a HTTP request over federation failed due to not being able to
  283. talk to the remote server for some reason.
  284. This exception is used to differentiate "expected" errors that arise due to
  285. networking (e.g. DNS failures, connection timeouts etc), versus unexpected
  286. errors (like programming errors).
  287. """
  288. def __init__(self, inner_exception, can_retry):
  289. super(RequestSendFailed, self).__init__(
  290. "Failed to send request: %s: %s" % (
  291. type(inner_exception).__name__, inner_exception,
  292. )
  293. )
  294. self.inner_exception = inner_exception
  295. self.can_retry = can_retry
  296. def cs_error(msg, code=Codes.UNKNOWN, **kwargs):
  297. """ Utility method for constructing an error response for client-server
  298. interactions.
  299. Args:
  300. msg (str): The error message.
  301. code (str): The error code.
  302. kwargs : Additional keys to add to the response.
  303. Returns:
  304. A dict representing the error response JSON.
  305. """
  306. err = {"error": msg, "errcode": code}
  307. for key, value in iteritems(kwargs):
  308. err[key] = value
  309. return err
  310. class FederationError(RuntimeError):
  311. """ This class is used to inform remote home servers about erroneous
  312. PDUs they sent us.
  313. FATAL: The remote server could not interpret the source event.
  314. (e.g., it was missing a required field)
  315. ERROR: The remote server interpreted the event, but it failed some other
  316. check (e.g. auth)
  317. WARN: The remote server accepted the event, but believes some part of it
  318. is wrong (e.g., it referred to an invalid event)
  319. """
  320. def __init__(self, level, code, reason, affected, source=None):
  321. if level not in ["FATAL", "ERROR", "WARN"]:
  322. raise ValueError("Level is not valid: %s" % (level,))
  323. self.level = level
  324. self.code = code
  325. self.reason = reason
  326. self.affected = affected
  327. self.source = source
  328. msg = "%s %s: %s" % (level, code, reason,)
  329. super(FederationError, self).__init__(msg)
  330. def get_dict(self):
  331. return {
  332. "level": self.level,
  333. "code": self.code,
  334. "reason": self.reason,
  335. "affected": self.affected,
  336. "source": self.source if self.source else self.affected,
  337. }
  338. class HttpResponseException(CodeMessageException):
  339. """
  340. Represents an HTTP-level failure of an outbound request
  341. Attributes:
  342. response (bytes): body of response
  343. """
  344. def __init__(self, code, msg, response):
  345. """
  346. Args:
  347. code (int): HTTP status code
  348. msg (str): reason phrase from HTTP response status line
  349. response (bytes): body of response
  350. """
  351. super(HttpResponseException, self).__init__(code, msg)
  352. self.response = response
  353. def to_synapse_error(self):
  354. """Make a SynapseError based on an HTTPResponseException
  355. This is useful when a proxied request has failed, and we need to
  356. decide how to map the failure onto a matrix error to send back to the
  357. client.
  358. An attempt is made to parse the body of the http response as a matrix
  359. error. If that succeeds, the errcode and error message from the body
  360. are used as the errcode and error message in the new synapse error.
  361. Otherwise, the errcode is set to M_UNKNOWN, and the error message is
  362. set to the reason code from the HTTP response.
  363. Returns:
  364. SynapseError:
  365. """
  366. # try to parse the body as json, to get better errcode/msg, but
  367. # default to M_UNKNOWN with the HTTP status as the error text
  368. try:
  369. j = json.loads(self.response)
  370. except ValueError:
  371. j = {}
  372. if not isinstance(j, dict):
  373. j = {}
  374. errcode = j.pop('errcode', Codes.UNKNOWN)
  375. errmsg = j.pop('error', self.msg)
  376. return ProxiedRequestError(self.code, errmsg, errcode, j)