errors.py 17 KB

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