errors.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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 typing import Dict
  19. from six import iteritems
  20. from six.moves import http_client
  21. from canonicaljson import json
  22. logger = logging.getLogger(__name__)
  23. class Codes(object):
  24. UNRECOGNIZED = "M_UNRECOGNIZED"
  25. UNAUTHORIZED = "M_UNAUTHORIZED"
  26. FORBIDDEN = "M_FORBIDDEN"
  27. BAD_JSON = "M_BAD_JSON"
  28. NOT_JSON = "M_NOT_JSON"
  29. USER_IN_USE = "M_USER_IN_USE"
  30. ROOM_IN_USE = "M_ROOM_IN_USE"
  31. BAD_PAGINATION = "M_BAD_PAGINATION"
  32. BAD_STATE = "M_BAD_STATE"
  33. UNKNOWN = "M_UNKNOWN"
  34. NOT_FOUND = "M_NOT_FOUND"
  35. MISSING_TOKEN = "M_MISSING_TOKEN"
  36. UNKNOWN_TOKEN = "M_UNKNOWN_TOKEN"
  37. GUEST_ACCESS_FORBIDDEN = "M_GUEST_ACCESS_FORBIDDEN"
  38. LIMIT_EXCEEDED = "M_LIMIT_EXCEEDED"
  39. CAPTCHA_NEEDED = "M_CAPTCHA_NEEDED"
  40. CAPTCHA_INVALID = "M_CAPTCHA_INVALID"
  41. MISSING_PARAM = "M_MISSING_PARAM"
  42. INVALID_PARAM = "M_INVALID_PARAM"
  43. TOO_LARGE = "M_TOO_LARGE"
  44. EXCLUSIVE = "M_EXCLUSIVE"
  45. THREEPID_AUTH_FAILED = "M_THREEPID_AUTH_FAILED"
  46. THREEPID_IN_USE = "M_THREEPID_IN_USE"
  47. THREEPID_NOT_FOUND = "M_THREEPID_NOT_FOUND"
  48. THREEPID_DENIED = "M_THREEPID_DENIED"
  49. INVALID_USERNAME = "M_INVALID_USERNAME"
  50. SERVER_NOT_TRUSTED = "M_SERVER_NOT_TRUSTED"
  51. CONSENT_NOT_GIVEN = "M_CONSENT_NOT_GIVEN"
  52. CANNOT_LEAVE_SERVER_NOTICE_ROOM = "M_CANNOT_LEAVE_SERVER_NOTICE_ROOM"
  53. RESOURCE_LIMIT_EXCEEDED = "M_RESOURCE_LIMIT_EXCEEDED"
  54. UNSUPPORTED_ROOM_VERSION = "M_UNSUPPORTED_ROOM_VERSION"
  55. INCOMPATIBLE_ROOM_VERSION = "M_INCOMPATIBLE_ROOM_VERSION"
  56. WRONG_ROOM_KEYS_VERSION = "M_WRONG_ROOM_KEYS_VERSION"
  57. EXPIRED_ACCOUNT = "ORG_MATRIX_EXPIRED_ACCOUNT"
  58. INVALID_SIGNATURE = "M_INVALID_SIGNATURE"
  59. USER_DEACTIVATED = "M_USER_DEACTIVATED"
  60. class CodeMessageException(RuntimeError):
  61. """An exception with integer code and message string attributes.
  62. Attributes:
  63. code (int): HTTP error code
  64. msg (str): string describing the error
  65. """
  66. def __init__(self, code, msg):
  67. super(CodeMessageException, self).__init__("%d: %s" % (code, msg))
  68. self.code = code
  69. self.msg = msg
  70. class SynapseError(CodeMessageException):
  71. """A base exception type for matrix errors which have an errcode and error
  72. message (as well as an HTTP status code).
  73. Attributes:
  74. errcode (str): Matrix error code e.g 'M_FORBIDDEN'
  75. """
  76. def __init__(self, code, msg, errcode=Codes.UNKNOWN):
  77. """Constructs a synapse error.
  78. Args:
  79. code (int): The integer error code (an HTTP response code)
  80. msg (str): The human-readable error message.
  81. errcode (str): The matrix error code e.g 'M_FORBIDDEN'
  82. """
  83. super(SynapseError, self).__init__(code, msg)
  84. self.errcode = errcode
  85. def error_dict(self):
  86. return cs_error(self.msg, self.errcode)
  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__(code, msg, errcode)
  94. if additional_fields is None:
  95. self._additional_fields = {} # type: Dict
  96. else:
  97. self._additional_fields = dict(additional_fields)
  98. def error_dict(self):
  99. return cs_error(self.msg, self.errcode, **self._additional_fields)
  100. class ConsentNotGivenError(SynapseError):
  101. """The error returned to the client when the user has not consented to the
  102. privacy policy.
  103. """
  104. def __init__(self, msg, consent_uri):
  105. """Constructs a ConsentNotGivenError
  106. Args:
  107. msg (str): The human-readable error message
  108. consent_url (str): The URL where the user can give their consent
  109. """
  110. super(ConsentNotGivenError, self).__init__(
  111. code=http_client.FORBIDDEN, msg=msg, errcode=Codes.CONSENT_NOT_GIVEN
  112. )
  113. self._consent_uri = consent_uri
  114. def error_dict(self):
  115. return cs_error(self.msg, self.errcode, consent_uri=self._consent_uri)
  116. class UserDeactivatedError(SynapseError):
  117. """The error returned to the client when the user attempted to access an
  118. authenticated endpoint, but the account has been deactivated.
  119. """
  120. def __init__(self, msg):
  121. """Constructs a UserDeactivatedError
  122. Args:
  123. msg (str): The human-readable error message
  124. """
  125. super(UserDeactivatedError, self).__init__(
  126. code=http_client.FORBIDDEN, msg=msg, errcode=Codes.USER_DEACTIVATED
  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__(400, message, **kwargs)
  173. class NotFoundError(SynapseError):
  174. """An error indicating we can't find the thing you asked for"""
  175. def __init__(self, msg="Not found", errcode=Codes.NOT_FOUND):
  176. super(NotFoundError, self).__init__(404, msg, errcode=errcode)
  177. class AuthError(SynapseError):
  178. """An error raised when there was a problem authorising an event, and at various
  179. other poorly-defined times.
  180. """
  181. def __init__(self, *args, **kwargs):
  182. if "errcode" not in kwargs:
  183. kwargs["errcode"] = Codes.FORBIDDEN
  184. super(AuthError, self).__init__(*args, **kwargs)
  185. class InvalidClientCredentialsError(SynapseError):
  186. """An error raised when there was a problem with the authorisation credentials
  187. in a client request.
  188. https://matrix.org/docs/spec/client_server/r0.5.0#using-access-tokens:
  189. When credentials are required but missing or invalid, the HTTP call will
  190. return with a status of 401 and the error code, M_MISSING_TOKEN or
  191. M_UNKNOWN_TOKEN respectively.
  192. """
  193. def __init__(self, msg, errcode):
  194. super().__init__(code=401, msg=msg, errcode=errcode)
  195. class MissingClientTokenError(InvalidClientCredentialsError):
  196. """Raised when we couldn't find the access token in a request"""
  197. def __init__(self, msg="Missing access token"):
  198. super().__init__(msg=msg, errcode="M_MISSING_TOKEN")
  199. class InvalidClientTokenError(InvalidClientCredentialsError):
  200. """Raised when we didn't understand the access token in a request"""
  201. def __init__(self, msg="Unrecognised access token", soft_logout=False):
  202. super().__init__(msg=msg, errcode="M_UNKNOWN_TOKEN")
  203. self._soft_logout = soft_logout
  204. def error_dict(self):
  205. d = super().error_dict()
  206. d["soft_logout"] = self._soft_logout
  207. return d
  208. class ResourceLimitError(SynapseError):
  209. """
  210. Any error raised when there is a problem with resource usage.
  211. For instance, the monthly active user limit for the server has been exceeded
  212. """
  213. def __init__(
  214. self,
  215. code,
  216. msg,
  217. errcode=Codes.RESOURCE_LIMIT_EXCEEDED,
  218. admin_contact=None,
  219. limit_type=None,
  220. ):
  221. self.admin_contact = admin_contact
  222. self.limit_type = limit_type
  223. super(ResourceLimitError, self).__init__(code, msg, errcode=errcode)
  224. def error_dict(self):
  225. return cs_error(
  226. self.msg,
  227. self.errcode,
  228. admin_contact=self.admin_contact,
  229. limit_type=self.limit_type,
  230. )
  231. class EventSizeError(SynapseError):
  232. """An error raised when an event is too big."""
  233. def __init__(self, *args, **kwargs):
  234. if "errcode" not in kwargs:
  235. kwargs["errcode"] = Codes.TOO_LARGE
  236. super(EventSizeError, self).__init__(413, *args, **kwargs)
  237. class EventStreamError(SynapseError):
  238. """An error raised when there a problem with the event stream."""
  239. def __init__(self, *args, **kwargs):
  240. if "errcode" not in kwargs:
  241. kwargs["errcode"] = Codes.BAD_PAGINATION
  242. super(EventStreamError, self).__init__(*args, **kwargs)
  243. class LoginError(SynapseError):
  244. """An error raised when there was a problem logging in."""
  245. pass
  246. class StoreError(SynapseError):
  247. """An error raised when there was a problem storing some data."""
  248. pass
  249. class InvalidCaptchaError(SynapseError):
  250. def __init__(
  251. self,
  252. code=400,
  253. msg="Invalid captcha.",
  254. error_url=None,
  255. errcode=Codes.CAPTCHA_INVALID,
  256. ):
  257. super(InvalidCaptchaError, self).__init__(code, msg, errcode)
  258. self.error_url = error_url
  259. def error_dict(self):
  260. return cs_error(self.msg, self.errcode, error_url=self.error_url)
  261. class LimitExceededError(SynapseError):
  262. """A client has sent too many requests and is being throttled.
  263. """
  264. def __init__(
  265. self,
  266. code=429,
  267. msg="Too Many Requests",
  268. retry_after_ms=None,
  269. errcode=Codes.LIMIT_EXCEEDED,
  270. ):
  271. super(LimitExceededError, self).__init__(code, msg, errcode)
  272. self.retry_after_ms = retry_after_ms
  273. def error_dict(self):
  274. return cs_error(self.msg, self.errcode, retry_after_ms=self.retry_after_ms)
  275. class RoomKeysVersionError(SynapseError):
  276. """A client has tried to upload to a non-current version of the room_keys store
  277. """
  278. def __init__(self, current_version):
  279. """
  280. Args:
  281. current_version (str): the current version of the store they should have used
  282. """
  283. super(RoomKeysVersionError, self).__init__(
  284. 403, "Wrong room_keys version", Codes.WRONG_ROOM_KEYS_VERSION
  285. )
  286. self.current_version = current_version
  287. class UnsupportedRoomVersionError(SynapseError):
  288. """The client's request to create a room used a room version that the server does
  289. not support."""
  290. def __init__(self):
  291. super(UnsupportedRoomVersionError, self).__init__(
  292. code=400,
  293. msg="Homeserver does not support this room version",
  294. errcode=Codes.UNSUPPORTED_ROOM_VERSION,
  295. )
  296. class ThreepidValidationError(SynapseError):
  297. """An error raised when there was a problem authorising an event."""
  298. def __init__(self, *args, **kwargs):
  299. if "errcode" not in kwargs:
  300. kwargs["errcode"] = Codes.FORBIDDEN
  301. super(ThreepidValidationError, self).__init__(*args, **kwargs)
  302. class IncompatibleRoomVersionError(SynapseError):
  303. """A server is trying to join a room whose version it does not support.
  304. Unlike UnsupportedRoomVersionError, it is specific to the case of the make_join
  305. failing.
  306. """
  307. def __init__(self, room_version):
  308. super(IncompatibleRoomVersionError, self).__init__(
  309. code=400,
  310. msg="Your homeserver does not support the features required to "
  311. "join this room",
  312. errcode=Codes.INCOMPATIBLE_ROOM_VERSION,
  313. )
  314. self._room_version = room_version
  315. def error_dict(self):
  316. return cs_error(self.msg, self.errcode, room_version=self._room_version)
  317. class RequestSendFailed(RuntimeError):
  318. """Sending a HTTP request over federation failed due to not being able to
  319. talk to the remote server for some reason.
  320. This exception is used to differentiate "expected" errors that arise due to
  321. networking (e.g. DNS failures, connection timeouts etc), versus unexpected
  322. errors (like programming errors).
  323. """
  324. def __init__(self, inner_exception, can_retry):
  325. super(RequestSendFailed, self).__init__(
  326. "Failed to send request: %s: %s"
  327. % (type(inner_exception).__name__, inner_exception)
  328. )
  329. self.inner_exception = inner_exception
  330. self.can_retry = can_retry
  331. def cs_error(msg, code=Codes.UNKNOWN, **kwargs):
  332. """ Utility method for constructing an error response for client-server
  333. interactions.
  334. Args:
  335. msg (str): The error message.
  336. code (str): The error code.
  337. kwargs : Additional keys to add to the response.
  338. Returns:
  339. A dict representing the error response JSON.
  340. """
  341. err = {"error": msg, "errcode": code}
  342. for key, value in iteritems(kwargs):
  343. err[key] = value
  344. return err
  345. class FederationError(RuntimeError):
  346. """ This class is used to inform remote home servers about erroneous
  347. PDUs they sent us.
  348. FATAL: The remote server could not interpret the source event.
  349. (e.g., it was missing a required field)
  350. ERROR: The remote server interpreted the event, but it failed some other
  351. check (e.g. auth)
  352. WARN: The remote server accepted the event, but believes some part of it
  353. is wrong (e.g., it referred to an invalid event)
  354. """
  355. def __init__(self, level, code, reason, affected, source=None):
  356. if level not in ["FATAL", "ERROR", "WARN"]:
  357. raise ValueError("Level is not valid: %s" % (level,))
  358. self.level = level
  359. self.code = code
  360. self.reason = reason
  361. self.affected = affected
  362. self.source = source
  363. msg = "%s %s: %s" % (level, code, reason)
  364. super(FederationError, self).__init__(msg)
  365. def get_dict(self):
  366. return {
  367. "level": self.level,
  368. "code": self.code,
  369. "reason": self.reason,
  370. "affected": self.affected,
  371. "source": self.source if self.source else self.affected,
  372. }
  373. class HttpResponseException(CodeMessageException):
  374. """
  375. Represents an HTTP-level failure of an outbound request
  376. Attributes:
  377. response (bytes): body of response
  378. """
  379. def __init__(self, code, msg, response):
  380. """
  381. Args:
  382. code (int): HTTP status code
  383. msg (str): reason phrase from HTTP response status line
  384. response (bytes): body of response
  385. """
  386. super(HttpResponseException, self).__init__(code, msg)
  387. self.response = response
  388. def to_synapse_error(self):
  389. """Make a SynapseError based on an HTTPResponseException
  390. This is useful when a proxied request has failed, and we need to
  391. decide how to map the failure onto a matrix error to send back to the
  392. client.
  393. An attempt is made to parse the body of the http response as a matrix
  394. error. If that succeeds, the errcode and error message from the body
  395. are used as the errcode and error message in the new synapse error.
  396. Otherwise, the errcode is set to M_UNKNOWN, and the error message is
  397. set to the reason code from the HTTP response.
  398. Returns:
  399. SynapseError:
  400. """
  401. # try to parse the body as json, to get better errcode/msg, but
  402. # default to M_UNKNOWN with the HTTP status as the error text
  403. try:
  404. j = json.loads(self.response)
  405. except ValueError:
  406. j = {}
  407. if not isinstance(j, dict):
  408. j = {}
  409. errcode = j.pop("errcode", Codes.UNKNOWN)
  410. errmsg = j.pop("error", self.msg)
  411. return ProxiedRequestError(self.code, errmsg, errcode, j)