errors.py 15 KB

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