errors.py 20 KB

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