errors.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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 http import HTTPStatus
  19. from typing import Dict, List
  20. from canonicaljson import json
  21. from twisted.web import http
  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. PASSWORD_TOO_SHORT = "M_PASSWORD_TOO_SHORT"
  59. PASSWORD_NO_DIGIT = "M_PASSWORD_NO_DIGIT"
  60. PASSWORD_NO_UPPERCASE = "M_PASSWORD_NO_UPPERCASE"
  61. PASSWORD_NO_LOWERCASE = "M_PASSWORD_NO_LOWERCASE"
  62. PASSWORD_NO_SYMBOL = "M_PASSWORD_NO_SYMBOL"
  63. PASSWORD_IN_DICTIONARY = "M_PASSWORD_IN_DICTIONARY"
  64. WEAK_PASSWORD = "M_WEAK_PASSWORD"
  65. INVALID_SIGNATURE = "M_INVALID_SIGNATURE"
  66. USER_DEACTIVATED = "M_USER_DEACTIVATED"
  67. BAD_ALIAS = "M_BAD_ALIAS"
  68. class CodeMessageException(RuntimeError):
  69. """An exception with integer code and message string attributes.
  70. Attributes:
  71. code (int): HTTP error code
  72. msg (str): string describing the error
  73. """
  74. def __init__(self, code, msg):
  75. super(CodeMessageException, self).__init__("%d: %s" % (code, msg))
  76. # Some calls to this method pass instances of http.HTTPStatus for `code`.
  77. # While HTTPStatus is a subclass of int, it has magic __str__ methods
  78. # which emit `HTTPStatus.FORBIDDEN` when converted to a str, instead of `403`.
  79. # This causes inconsistency in our log lines.
  80. #
  81. # To eliminate this behaviour, we convert them to their integer equivalents here.
  82. self.code = int(code)
  83. self.msg = msg
  84. class RedirectException(CodeMessageException):
  85. """A pseudo-error indicating that we want to redirect the client to a different
  86. location
  87. Attributes:
  88. cookies: a list of set-cookies values to add to the response. For example:
  89. b"sessionId=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT"
  90. """
  91. def __init__(self, location: bytes, http_code: int = http.FOUND):
  92. """
  93. Args:
  94. location: the URI to redirect to
  95. http_code: the HTTP response code
  96. """
  97. msg = "Redirect to %s" % (location.decode("utf-8"),)
  98. super().__init__(code=http_code, msg=msg)
  99. self.location = location
  100. self.cookies = [] # type: List[bytes]
  101. class SynapseError(CodeMessageException):
  102. """A base exception type for matrix errors which have an errcode and error
  103. message (as well as an HTTP status code).
  104. Attributes:
  105. errcode (str): Matrix error code e.g 'M_FORBIDDEN'
  106. """
  107. def __init__(self, code, msg, errcode=Codes.UNKNOWN):
  108. """Constructs a synapse error.
  109. Args:
  110. code (int): The integer error code (an HTTP response code)
  111. msg (str): The human-readable error message.
  112. errcode (str): The matrix error code e.g 'M_FORBIDDEN'
  113. """
  114. super(SynapseError, self).__init__(code, msg)
  115. self.errcode = errcode
  116. def error_dict(self):
  117. return cs_error(self.msg, self.errcode)
  118. class ProxiedRequestError(SynapseError):
  119. """An error from a general matrix endpoint, eg. from a proxied Matrix API call.
  120. Attributes:
  121. errcode (str): Matrix error code e.g 'M_FORBIDDEN'
  122. """
  123. def __init__(self, code, msg, errcode=Codes.UNKNOWN, additional_fields=None):
  124. super(ProxiedRequestError, self).__init__(code, msg, errcode)
  125. if additional_fields is None:
  126. self._additional_fields = {} # type: Dict
  127. else:
  128. self._additional_fields = dict(additional_fields)
  129. def error_dict(self):
  130. return cs_error(self.msg, self.errcode, **self._additional_fields)
  131. class ConsentNotGivenError(SynapseError):
  132. """The error returned to the client when the user has not consented to the
  133. privacy policy.
  134. """
  135. def __init__(self, msg, consent_uri):
  136. """Constructs a ConsentNotGivenError
  137. Args:
  138. msg (str): The human-readable error message
  139. consent_url (str): The URL where the user can give their consent
  140. """
  141. super(ConsentNotGivenError, self).__init__(
  142. code=HTTPStatus.FORBIDDEN, msg=msg, errcode=Codes.CONSENT_NOT_GIVEN
  143. )
  144. self._consent_uri = consent_uri
  145. def error_dict(self):
  146. return cs_error(self.msg, self.errcode, consent_uri=self._consent_uri)
  147. class UserDeactivatedError(SynapseError):
  148. """The error returned to the client when the user attempted to access an
  149. authenticated endpoint, but the account has been deactivated.
  150. """
  151. def __init__(self, msg):
  152. """Constructs a UserDeactivatedError
  153. Args:
  154. msg (str): The human-readable error message
  155. """
  156. super(UserDeactivatedError, self).__init__(
  157. code=HTTPStatus.FORBIDDEN, msg=msg, errcode=Codes.USER_DEACTIVATED
  158. )
  159. class FederationDeniedError(SynapseError):
  160. """An error raised when the server tries to federate with a server which
  161. is not on its federation whitelist.
  162. Attributes:
  163. destination (str): The destination which has been denied
  164. """
  165. def __init__(self, destination):
  166. """Raised by federation client or server to indicate that we are
  167. are deliberately not attempting to contact a given server because it is
  168. not on our federation whitelist.
  169. Args:
  170. destination (str): the domain in question
  171. """
  172. self.destination = destination
  173. super(FederationDeniedError, self).__init__(
  174. code=403,
  175. msg="Federation denied with %s." % (self.destination,),
  176. errcode=Codes.FORBIDDEN,
  177. )
  178. class InteractiveAuthIncompleteError(Exception):
  179. """An error raised when UI auth is not yet complete
  180. (This indicates we should return a 401 with 'result' as the body)
  181. Attributes:
  182. result (dict): the server response to the request, which should be
  183. passed back to the client
  184. """
  185. def __init__(self, result):
  186. super(InteractiveAuthIncompleteError, self).__init__(
  187. "Interactive auth not yet complete"
  188. )
  189. self.result = result
  190. class UnrecognizedRequestError(SynapseError):
  191. """An error indicating we don't understand the request you're trying to make"""
  192. def __init__(self, *args, **kwargs):
  193. if "errcode" not in kwargs:
  194. kwargs["errcode"] = Codes.UNRECOGNIZED
  195. message = None
  196. if len(args) == 0:
  197. message = "Unrecognized request"
  198. else:
  199. message = args[0]
  200. super(UnrecognizedRequestError, self).__init__(400, message, **kwargs)
  201. class NotFoundError(SynapseError):
  202. """An error indicating we can't find the thing you asked for"""
  203. def __init__(self, msg="Not found", errcode=Codes.NOT_FOUND):
  204. super(NotFoundError, self).__init__(404, msg, errcode=errcode)
  205. class AuthError(SynapseError):
  206. """An error raised when there was a problem authorising an event, and at various
  207. other poorly-defined times.
  208. """
  209. def __init__(self, *args, **kwargs):
  210. if "errcode" not in kwargs:
  211. kwargs["errcode"] = Codes.FORBIDDEN
  212. super(AuthError, self).__init__(*args, **kwargs)
  213. class InvalidClientCredentialsError(SynapseError):
  214. """An error raised when there was a problem with the authorisation credentials
  215. in a client request.
  216. https://matrix.org/docs/spec/client_server/r0.5.0#using-access-tokens:
  217. When credentials are required but missing or invalid, the HTTP call will
  218. return with a status of 401 and the error code, M_MISSING_TOKEN or
  219. M_UNKNOWN_TOKEN respectively.
  220. """
  221. def __init__(self, msg, errcode):
  222. super().__init__(code=401, msg=msg, errcode=errcode)
  223. class MissingClientTokenError(InvalidClientCredentialsError):
  224. """Raised when we couldn't find the access token in a request"""
  225. def __init__(self, msg="Missing access token"):
  226. super().__init__(msg=msg, errcode="M_MISSING_TOKEN")
  227. class InvalidClientTokenError(InvalidClientCredentialsError):
  228. """Raised when we didn't understand the access token in a request"""
  229. def __init__(self, msg="Unrecognised access token", soft_logout=False):
  230. super().__init__(msg=msg, errcode="M_UNKNOWN_TOKEN")
  231. self._soft_logout = soft_logout
  232. def error_dict(self):
  233. d = super().error_dict()
  234. d["soft_logout"] = self._soft_logout
  235. return d
  236. class ResourceLimitError(SynapseError):
  237. """
  238. Any error raised when there is a problem with resource usage.
  239. For instance, the monthly active user limit for the server has been exceeded
  240. """
  241. def __init__(
  242. self,
  243. code,
  244. msg,
  245. errcode=Codes.RESOURCE_LIMIT_EXCEEDED,
  246. admin_contact=None,
  247. limit_type=None,
  248. ):
  249. self.admin_contact = admin_contact
  250. self.limit_type = limit_type
  251. super(ResourceLimitError, self).__init__(code, msg, errcode=errcode)
  252. def error_dict(self):
  253. return cs_error(
  254. self.msg,
  255. self.errcode,
  256. admin_contact=self.admin_contact,
  257. limit_type=self.limit_type,
  258. )
  259. class EventSizeError(SynapseError):
  260. """An error raised when an event is too big."""
  261. def __init__(self, *args, **kwargs):
  262. if "errcode" not in kwargs:
  263. kwargs["errcode"] = Codes.TOO_LARGE
  264. super(EventSizeError, self).__init__(413, *args, **kwargs)
  265. class EventStreamError(SynapseError):
  266. """An error raised when there a problem with the event stream."""
  267. def __init__(self, *args, **kwargs):
  268. if "errcode" not in kwargs:
  269. kwargs["errcode"] = Codes.BAD_PAGINATION
  270. super(EventStreamError, self).__init__(*args, **kwargs)
  271. class LoginError(SynapseError):
  272. """An error raised when there was a problem logging in."""
  273. pass
  274. class StoreError(SynapseError):
  275. """An error raised when there was a problem storing some data."""
  276. pass
  277. class InvalidCaptchaError(SynapseError):
  278. def __init__(
  279. self,
  280. code=400,
  281. msg="Invalid captcha.",
  282. error_url=None,
  283. errcode=Codes.CAPTCHA_INVALID,
  284. ):
  285. super(InvalidCaptchaError, self).__init__(code, msg, errcode)
  286. self.error_url = error_url
  287. def error_dict(self):
  288. return cs_error(self.msg, self.errcode, error_url=self.error_url)
  289. class LimitExceededError(SynapseError):
  290. """A client has sent too many requests and is being throttled.
  291. """
  292. def __init__(
  293. self,
  294. code=429,
  295. msg="Too Many Requests",
  296. retry_after_ms=None,
  297. errcode=Codes.LIMIT_EXCEEDED,
  298. ):
  299. super(LimitExceededError, self).__init__(code, msg, errcode)
  300. self.retry_after_ms = retry_after_ms
  301. def error_dict(self):
  302. return cs_error(self.msg, self.errcode, retry_after_ms=self.retry_after_ms)
  303. class RoomKeysVersionError(SynapseError):
  304. """A client has tried to upload to a non-current version of the room_keys store
  305. """
  306. def __init__(self, current_version):
  307. """
  308. Args:
  309. current_version (str): the current version of the store they should have used
  310. """
  311. super(RoomKeysVersionError, self).__init__(
  312. 403, "Wrong room_keys version", Codes.WRONG_ROOM_KEYS_VERSION
  313. )
  314. self.current_version = current_version
  315. class UnsupportedRoomVersionError(SynapseError):
  316. """The client's request to create a room used a room version that the server does
  317. not support."""
  318. def __init__(self, msg="Homeserver does not support this room version"):
  319. super(UnsupportedRoomVersionError, self).__init__(
  320. code=400, msg=msg, errcode=Codes.UNSUPPORTED_ROOM_VERSION,
  321. )
  322. class ThreepidValidationError(SynapseError):
  323. """An error raised when there was a problem authorising an event."""
  324. def __init__(self, *args, **kwargs):
  325. if "errcode" not in kwargs:
  326. kwargs["errcode"] = Codes.FORBIDDEN
  327. super(ThreepidValidationError, self).__init__(*args, **kwargs)
  328. class IncompatibleRoomVersionError(SynapseError):
  329. """A server is trying to join a room whose version it does not support.
  330. Unlike UnsupportedRoomVersionError, it is specific to the case of the make_join
  331. failing.
  332. """
  333. def __init__(self, room_version):
  334. super(IncompatibleRoomVersionError, self).__init__(
  335. code=400,
  336. msg="Your homeserver does not support the features required to "
  337. "join this room",
  338. errcode=Codes.INCOMPATIBLE_ROOM_VERSION,
  339. )
  340. self._room_version = room_version
  341. def error_dict(self):
  342. return cs_error(self.msg, self.errcode, room_version=self._room_version)
  343. class PasswordRefusedError(SynapseError):
  344. """A password has been refused, either during password reset/change or registration.
  345. """
  346. def __init__(
  347. self,
  348. msg="This password doesn't comply with the server's policy",
  349. errcode=Codes.WEAK_PASSWORD,
  350. ):
  351. super(PasswordRefusedError, self).__init__(
  352. code=400, msg=msg, errcode=errcode,
  353. )
  354. class RequestSendFailed(RuntimeError):
  355. """Sending a HTTP request over federation failed due to not being able to
  356. talk to the remote server for some reason.
  357. This exception is used to differentiate "expected" errors that arise due to
  358. networking (e.g. DNS failures, connection timeouts etc), versus unexpected
  359. errors (like programming errors).
  360. """
  361. def __init__(self, inner_exception, can_retry):
  362. super(RequestSendFailed, self).__init__(
  363. "Failed to send request: %s: %s"
  364. % (type(inner_exception).__name__, inner_exception)
  365. )
  366. self.inner_exception = inner_exception
  367. self.can_retry = can_retry
  368. def cs_error(msg, code=Codes.UNKNOWN, **kwargs):
  369. """ Utility method for constructing an error response for client-server
  370. interactions.
  371. Args:
  372. msg (str): The error message.
  373. code (str): The error code.
  374. kwargs : Additional keys to add to the response.
  375. Returns:
  376. A dict representing the error response JSON.
  377. """
  378. err = {"error": msg, "errcode": code}
  379. for key, value in kwargs.items():
  380. err[key] = value
  381. return err
  382. class FederationError(RuntimeError):
  383. """ This class is used to inform remote homeservers about erroneous
  384. PDUs they sent us.
  385. FATAL: The remote server could not interpret the source event.
  386. (e.g., it was missing a required field)
  387. ERROR: The remote server interpreted the event, but it failed some other
  388. check (e.g. auth)
  389. WARN: The remote server accepted the event, but believes some part of it
  390. is wrong (e.g., it referred to an invalid event)
  391. """
  392. def __init__(self, level, code, reason, affected, source=None):
  393. if level not in ["FATAL", "ERROR", "WARN"]:
  394. raise ValueError("Level is not valid: %s" % (level,))
  395. self.level = level
  396. self.code = code
  397. self.reason = reason
  398. self.affected = affected
  399. self.source = source
  400. msg = "%s %s: %s" % (level, code, reason)
  401. super(FederationError, self).__init__(msg)
  402. def get_dict(self):
  403. return {
  404. "level": self.level,
  405. "code": self.code,
  406. "reason": self.reason,
  407. "affected": self.affected,
  408. "source": self.source if self.source else self.affected,
  409. }
  410. class HttpResponseException(CodeMessageException):
  411. """
  412. Represents an HTTP-level failure of an outbound request
  413. Attributes:
  414. response (bytes): body of response
  415. """
  416. def __init__(self, code, msg, response):
  417. """
  418. Args:
  419. code (int): HTTP status code
  420. msg (str): reason phrase from HTTP response status line
  421. response (bytes): body of response
  422. """
  423. super(HttpResponseException, self).__init__(code, msg)
  424. self.response = response
  425. def to_synapse_error(self):
  426. """Make a SynapseError based on an HTTPResponseException
  427. This is useful when a proxied request has failed, and we need to
  428. decide how to map the failure onto a matrix error to send back to the
  429. client.
  430. An attempt is made to parse the body of the http response as a matrix
  431. error. If that succeeds, the errcode and error message from the body
  432. are used as the errcode and error message in the new synapse error.
  433. Otherwise, the errcode is set to M_UNKNOWN, and the error message is
  434. set to the reason code from the HTTP response.
  435. Returns:
  436. SynapseError:
  437. """
  438. # try to parse the body as json, to get better errcode/msg, but
  439. # default to M_UNKNOWN with the HTTP status as the error text
  440. try:
  441. j = json.loads(self.response)
  442. except ValueError:
  443. j = {}
  444. if not isinstance(j, dict):
  445. j = {}
  446. errcode = j.pop("errcode", Codes.UNKNOWN)
  447. errmsg = j.pop("error", self.msg)
  448. return ProxiedRequestError(self.code, errmsg, errcode, j)