errors.py 19 KB

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