errors.py 20 KB

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