You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

611 lines
19 KiB

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