Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

845 řádky
28 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 math
  18. import typing
  19. from enum import Enum
  20. from http import HTTPStatus
  21. from typing import Any, Dict, List, Optional, Union
  22. from twisted.web import http
  23. from synapse.util import json_decoder
  24. if typing.TYPE_CHECKING:
  25. from synapse.config.homeserver import HomeServerConfig
  26. from synapse.types import JsonDict, StrCollection
  27. logger = logging.getLogger(__name__)
  28. class Codes(str, Enum):
  29. """
  30. All known error codes, as an enum of strings.
  31. """
  32. UNRECOGNIZED = "M_UNRECOGNIZED"
  33. UNAUTHORIZED = "M_UNAUTHORIZED"
  34. FORBIDDEN = "M_FORBIDDEN"
  35. BAD_JSON = "M_BAD_JSON"
  36. NOT_JSON = "M_NOT_JSON"
  37. USER_IN_USE = "M_USER_IN_USE"
  38. ROOM_IN_USE = "M_ROOM_IN_USE"
  39. BAD_PAGINATION = "M_BAD_PAGINATION"
  40. BAD_STATE = "M_BAD_STATE"
  41. UNKNOWN = "M_UNKNOWN"
  42. NOT_FOUND = "M_NOT_FOUND"
  43. MISSING_TOKEN = "M_MISSING_TOKEN"
  44. UNKNOWN_TOKEN = "M_UNKNOWN_TOKEN"
  45. GUEST_ACCESS_FORBIDDEN = "M_GUEST_ACCESS_FORBIDDEN"
  46. LIMIT_EXCEEDED = "M_LIMIT_EXCEEDED"
  47. CAPTCHA_NEEDED = "M_CAPTCHA_NEEDED"
  48. CAPTCHA_INVALID = "M_CAPTCHA_INVALID"
  49. MISSING_PARAM = "M_MISSING_PARAM"
  50. INVALID_PARAM = "M_INVALID_PARAM"
  51. TOO_LARGE = "M_TOO_LARGE"
  52. EXCLUSIVE = "M_EXCLUSIVE"
  53. THREEPID_AUTH_FAILED = "M_THREEPID_AUTH_FAILED"
  54. THREEPID_IN_USE = "M_THREEPID_IN_USE"
  55. THREEPID_NOT_FOUND = "M_THREEPID_NOT_FOUND"
  56. THREEPID_DENIED = "M_THREEPID_DENIED"
  57. INVALID_USERNAME = "M_INVALID_USERNAME"
  58. SERVER_NOT_TRUSTED = "M_SERVER_NOT_TRUSTED"
  59. CONSENT_NOT_GIVEN = "M_CONSENT_NOT_GIVEN"
  60. CANNOT_LEAVE_SERVER_NOTICE_ROOM = "M_CANNOT_LEAVE_SERVER_NOTICE_ROOM"
  61. RESOURCE_LIMIT_EXCEEDED = "M_RESOURCE_LIMIT_EXCEEDED"
  62. UNSUPPORTED_ROOM_VERSION = "M_UNSUPPORTED_ROOM_VERSION"
  63. INCOMPATIBLE_ROOM_VERSION = "M_INCOMPATIBLE_ROOM_VERSION"
  64. WRONG_ROOM_KEYS_VERSION = "M_WRONG_ROOM_KEYS_VERSION"
  65. EXPIRED_ACCOUNT = "ORG_MATRIX_EXPIRED_ACCOUNT"
  66. PASSWORD_TOO_SHORT = "M_PASSWORD_TOO_SHORT"
  67. PASSWORD_NO_DIGIT = "M_PASSWORD_NO_DIGIT"
  68. PASSWORD_NO_UPPERCASE = "M_PASSWORD_NO_UPPERCASE"
  69. PASSWORD_NO_LOWERCASE = "M_PASSWORD_NO_LOWERCASE"
  70. PASSWORD_NO_SYMBOL = "M_PASSWORD_NO_SYMBOL"
  71. PASSWORD_IN_DICTIONARY = "M_PASSWORD_IN_DICTIONARY"
  72. WEAK_PASSWORD = "M_WEAK_PASSWORD"
  73. INVALID_SIGNATURE = "M_INVALID_SIGNATURE"
  74. USER_DEACTIVATED = "M_USER_DEACTIVATED"
  75. # USER_LOCKED = "M_USER_LOCKED"
  76. USER_LOCKED = "ORG_MATRIX_MSC3939_USER_LOCKED"
  77. NOT_YET_UPLOADED = "M_NOT_YET_UPLOADED"
  78. CANNOT_OVERWRITE_MEDIA = "M_CANNOT_OVERWRITE_MEDIA"
  79. # Part of MSC3848
  80. # https://github.com/matrix-org/matrix-spec-proposals/pull/3848
  81. ALREADY_JOINED = "ORG.MATRIX.MSC3848.ALREADY_JOINED"
  82. NOT_JOINED = "ORG.MATRIX.MSC3848.NOT_JOINED"
  83. INSUFFICIENT_POWER = "ORG.MATRIX.MSC3848.INSUFFICIENT_POWER"
  84. # The account has been suspended on the server.
  85. # By opposition to `USER_DEACTIVATED`, this is a reversible measure
  86. # that can possibly be appealed and reverted.
  87. # Part of MSC3823.
  88. USER_ACCOUNT_SUSPENDED = "ORG.MATRIX.MSC3823.USER_ACCOUNT_SUSPENDED"
  89. BAD_ALIAS = "M_BAD_ALIAS"
  90. # For restricted join rules.
  91. UNABLE_AUTHORISE_JOIN = "M_UNABLE_TO_AUTHORISE_JOIN"
  92. UNABLE_TO_GRANT_JOIN = "M_UNABLE_TO_GRANT_JOIN"
  93. UNREDACTED_CONTENT_DELETED = "FI.MAU.MSC2815_UNREDACTED_CONTENT_DELETED"
  94. # Returned for federation requests where we can't process a request as we
  95. # can't ensure the sending server is in a room which is partial-stated on
  96. # our side.
  97. # Part of MSC3895.
  98. UNABLE_DUE_TO_PARTIAL_STATE = "ORG.MATRIX.MSC3895_UNABLE_DUE_TO_PARTIAL_STATE"
  99. USER_AWAITING_APPROVAL = "ORG.MATRIX.MSC3866_USER_AWAITING_APPROVAL"
  100. AS_PING_URL_NOT_SET = "M_URL_NOT_SET"
  101. AS_PING_BAD_STATUS = "M_BAD_STATUS"
  102. AS_PING_CONNECTION_TIMEOUT = "M_CONNECTION_TIMEOUT"
  103. AS_PING_CONNECTION_FAILED = "M_CONNECTION_FAILED"
  104. # Attempt to send a second annotation with the same event type & annotation key
  105. # MSC2677
  106. DUPLICATE_ANNOTATION = "M_DUPLICATE_ANNOTATION"
  107. class CodeMessageException(RuntimeError):
  108. """An exception with integer code, a message string attributes and optional headers.
  109. Attributes:
  110. code: HTTP error code
  111. msg: string describing the error
  112. headers: optional response headers to send
  113. """
  114. def __init__(
  115. self,
  116. code: Union[int, HTTPStatus],
  117. msg: str,
  118. headers: Optional[Dict[str, str]] = None,
  119. ):
  120. super().__init__("%d: %s" % (code, msg))
  121. # Some calls to this method pass instances of http.HTTPStatus for `code`.
  122. # While HTTPStatus is a subclass of int, it has magic __str__ methods
  123. # which emit `HTTPStatus.FORBIDDEN` when converted to a str, instead of `403`.
  124. # This causes inconsistency in our log lines.
  125. #
  126. # To eliminate this behaviour, we convert them to their integer equivalents here.
  127. self.code = int(code)
  128. self.msg = msg
  129. self.headers = headers
  130. class RedirectException(CodeMessageException):
  131. """A pseudo-error indicating that we want to redirect the client to a different
  132. location
  133. Attributes:
  134. cookies: a list of set-cookies values to add to the response. For example:
  135. b"sessionId=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT"
  136. """
  137. def __init__(self, location: bytes, http_code: int = http.FOUND):
  138. """
  139. Args:
  140. location: the URI to redirect to
  141. http_code: the HTTP response code
  142. """
  143. msg = "Redirect to %s" % (location.decode("utf-8"),)
  144. super().__init__(code=http_code, msg=msg)
  145. self.location = location
  146. self.cookies: List[bytes] = []
  147. class SynapseError(CodeMessageException):
  148. """A base exception type for matrix errors which have an errcode and error
  149. message (as well as an HTTP status code). These often bubble all the way up to the
  150. client API response so the error code and status often reach the client directly as
  151. defined here. If the error doesn't make sense to present to a client, then it
  152. probably shouldn't be a `SynapseError`. For example, if we contact another
  153. homeserver over federation, we shouldn't automatically ferry response errors back to
  154. the client on our end (a 500 from a remote server does not make sense to a client
  155. when our server did not experience a 500).
  156. Attributes:
  157. errcode: Matrix error code e.g 'M_FORBIDDEN'
  158. """
  159. def __init__(
  160. self,
  161. code: int,
  162. msg: str,
  163. errcode: str = Codes.UNKNOWN,
  164. additional_fields: Optional[Dict] = None,
  165. headers: Optional[Dict[str, str]] = None,
  166. ):
  167. """Constructs a synapse error.
  168. Args:
  169. code: The integer error code (an HTTP response code)
  170. msg: The human-readable error message.
  171. errcode: The matrix error code e.g 'M_FORBIDDEN'
  172. """
  173. super().__init__(code, msg, headers)
  174. self.errcode = errcode
  175. if additional_fields is None:
  176. self._additional_fields: Dict = {}
  177. else:
  178. self._additional_fields = dict(additional_fields)
  179. def error_dict(self, config: Optional["HomeServerConfig"]) -> "JsonDict":
  180. return cs_error(self.msg, self.errcode, **self._additional_fields)
  181. @property
  182. def debug_context(self) -> Optional[str]:
  183. """Override this to add debugging context that shouldn't be sent to clients."""
  184. return None
  185. class InvalidAPICallError(SynapseError):
  186. """You called an existing API endpoint, but fed that endpoint
  187. invalid or incomplete data."""
  188. def __init__(self, msg: str):
  189. super().__init__(HTTPStatus.BAD_REQUEST, msg, Codes.BAD_JSON)
  190. class InvalidProxyCredentialsError(SynapseError):
  191. """Error raised when the proxy credentials are invalid."""
  192. def __init__(self, msg: str, errcode: str = Codes.UNKNOWN):
  193. super().__init__(401, msg, errcode)
  194. class ProxiedRequestError(SynapseError):
  195. """An error from a general matrix endpoint, eg. from a proxied Matrix API call.
  196. Attributes:
  197. errcode: Matrix error code e.g 'M_FORBIDDEN'
  198. """
  199. def __init__(
  200. self,
  201. code: int,
  202. msg: str,
  203. errcode: str = Codes.UNKNOWN,
  204. additional_fields: Optional[Dict] = None,
  205. ):
  206. super().__init__(code, msg, errcode, additional_fields)
  207. class ConsentNotGivenError(SynapseError):
  208. """The error returned to the client when the user has not consented to the
  209. privacy policy.
  210. """
  211. def __init__(self, msg: str, consent_uri: str):
  212. """Constructs a ConsentNotGivenError
  213. Args:
  214. msg: The human-readable error message
  215. consent_url: The URL where the user can give their consent
  216. """
  217. super().__init__(
  218. code=HTTPStatus.FORBIDDEN, msg=msg, errcode=Codes.CONSENT_NOT_GIVEN
  219. )
  220. self._consent_uri = consent_uri
  221. def error_dict(self, config: Optional["HomeServerConfig"]) -> "JsonDict":
  222. return cs_error(self.msg, self.errcode, consent_uri=self._consent_uri)
  223. class UserDeactivatedError(SynapseError):
  224. """The error returned to the client when the user attempted to access an
  225. authenticated endpoint, but the account has been deactivated.
  226. """
  227. def __init__(self, msg: str):
  228. """Constructs a UserDeactivatedError
  229. Args:
  230. msg: The human-readable error message
  231. """
  232. super().__init__(
  233. code=HTTPStatus.FORBIDDEN, msg=msg, errcode=Codes.USER_DEACTIVATED
  234. )
  235. class FederationDeniedError(SynapseError):
  236. """An error raised when the server tries to federate with a server which
  237. is not on its federation whitelist.
  238. Attributes:
  239. destination: The destination which has been denied
  240. """
  241. def __init__(self, destination: Optional[str]):
  242. """Raised by federation client or server to indicate that we are
  243. are deliberately not attempting to contact a given server because it is
  244. not on our federation whitelist.
  245. Args:
  246. destination: the domain in question
  247. """
  248. self.destination = destination
  249. super().__init__(
  250. code=403,
  251. msg="Federation denied with %s." % (self.destination,),
  252. errcode=Codes.FORBIDDEN,
  253. )
  254. class InteractiveAuthIncompleteError(Exception):
  255. """An error raised when UI auth is not yet complete
  256. (This indicates we should return a 401 with 'result' as the body)
  257. Attributes:
  258. session_id: The ID of the ongoing interactive auth session.
  259. result: the server response to the request, which should be
  260. passed back to the client
  261. """
  262. def __init__(self, session_id: str, result: "JsonDict"):
  263. super().__init__("Interactive auth not yet complete")
  264. self.session_id = session_id
  265. self.result = result
  266. class UnrecognizedRequestError(SynapseError):
  267. """An error indicating we don't understand the request you're trying to make"""
  268. def __init__(self, msg: str = "Unrecognized request", code: int = 400):
  269. super().__init__(code, msg, Codes.UNRECOGNIZED)
  270. class NotFoundError(SynapseError):
  271. """An error indicating we can't find the thing you asked for"""
  272. def __init__(self, msg: str = "Not found", errcode: str = Codes.NOT_FOUND):
  273. super().__init__(404, msg, errcode=errcode)
  274. class AuthError(SynapseError):
  275. """An error raised when there was a problem authorising an event, and at various
  276. other poorly-defined times.
  277. """
  278. def __init__(
  279. self,
  280. code: int,
  281. msg: str,
  282. errcode: str = Codes.FORBIDDEN,
  283. additional_fields: Optional[dict] = None,
  284. ):
  285. super().__init__(code, msg, errcode, additional_fields)
  286. class OAuthInsufficientScopeError(SynapseError):
  287. """An error raised when the caller does not have sufficient scope to perform the requested action"""
  288. def __init__(
  289. self,
  290. required_scopes: List[str],
  291. ):
  292. headers = {
  293. "WWW-Authenticate": 'Bearer error="insufficient_scope", scope="%s"'
  294. % (" ".join(required_scopes))
  295. }
  296. super().__init__(401, "Insufficient scope", Codes.FORBIDDEN, None, headers)
  297. class UnstableSpecAuthError(AuthError):
  298. """An error raised when a new error code is being proposed to replace a previous one.
  299. This error will return a "org.matrix.unstable.errcode" property with the new error code,
  300. with the previous error code still being defined in the "errcode" property.
  301. This error will include `org.matrix.msc3848.unstable.errcode` in the C-S error body.
  302. """
  303. def __init__(
  304. self,
  305. code: int,
  306. msg: str,
  307. errcode: str,
  308. previous_errcode: str = Codes.FORBIDDEN,
  309. additional_fields: Optional[dict] = None,
  310. ):
  311. self.previous_errcode = previous_errcode
  312. super().__init__(code, msg, errcode, additional_fields)
  313. def error_dict(self, config: Optional["HomeServerConfig"]) -> "JsonDict":
  314. fields = {}
  315. if config is not None and config.experimental.msc3848_enabled:
  316. fields["org.matrix.msc3848.unstable.errcode"] = self.errcode
  317. return cs_error(
  318. self.msg,
  319. self.previous_errcode,
  320. **fields,
  321. **self._additional_fields,
  322. )
  323. class InvalidClientCredentialsError(SynapseError):
  324. """An error raised when there was a problem with the authorisation credentials
  325. in a client request.
  326. https://matrix.org/docs/spec/client_server/r0.5.0#using-access-tokens:
  327. When credentials are required but missing or invalid, the HTTP call will
  328. return with a status of 401 and the error code, M_MISSING_TOKEN or
  329. M_UNKNOWN_TOKEN respectively.
  330. """
  331. def __init__(self, msg: str, errcode: str):
  332. super().__init__(code=401, msg=msg, errcode=errcode)
  333. class MissingClientTokenError(InvalidClientCredentialsError):
  334. """Raised when we couldn't find the access token in a request"""
  335. def __init__(self, msg: str = "Missing access token"):
  336. super().__init__(msg=msg, errcode="M_MISSING_TOKEN")
  337. class InvalidClientTokenError(InvalidClientCredentialsError):
  338. """Raised when we didn't understand the access token in a request"""
  339. def __init__(
  340. self, msg: str = "Unrecognised access token", soft_logout: bool = False
  341. ):
  342. super().__init__(msg=msg, errcode="M_UNKNOWN_TOKEN")
  343. self._soft_logout = soft_logout
  344. def error_dict(self, config: Optional["HomeServerConfig"]) -> "JsonDict":
  345. d = super().error_dict(config)
  346. d["soft_logout"] = self._soft_logout
  347. return d
  348. class ResourceLimitError(SynapseError):
  349. """
  350. Any error raised when there is a problem with resource usage.
  351. For instance, the monthly active user limit for the server has been exceeded
  352. """
  353. def __init__(
  354. self,
  355. code: int,
  356. msg: str,
  357. errcode: str = Codes.RESOURCE_LIMIT_EXCEEDED,
  358. admin_contact: Optional[str] = None,
  359. limit_type: Optional[str] = None,
  360. ):
  361. self.admin_contact = admin_contact
  362. self.limit_type = limit_type
  363. super().__init__(code, msg, errcode=errcode)
  364. def error_dict(self, config: Optional["HomeServerConfig"]) -> "JsonDict":
  365. return cs_error(
  366. self.msg,
  367. self.errcode,
  368. admin_contact=self.admin_contact,
  369. limit_type=self.limit_type,
  370. )
  371. class EventSizeError(SynapseError):
  372. """An error raised when an event is too big."""
  373. def __init__(self, msg: str, unpersistable: bool):
  374. """
  375. unpersistable:
  376. if True, the PDU must not be persisted, not even as a rejected PDU
  377. when received over federation.
  378. This is notably true when the entire PDU exceeds the size limit for a PDU,
  379. (as opposed to an individual key's size limit being exceeded).
  380. """
  381. super().__init__(413, msg, Codes.TOO_LARGE)
  382. self.unpersistable = unpersistable
  383. class LoginError(SynapseError):
  384. """An error raised when there was a problem logging in."""
  385. class StoreError(SynapseError):
  386. """An error raised when there was a problem storing some data."""
  387. class InvalidCaptchaError(SynapseError):
  388. def __init__(
  389. self,
  390. code: int = 400,
  391. msg: str = "Invalid captcha.",
  392. error_url: Optional[str] = None,
  393. errcode: str = Codes.CAPTCHA_INVALID,
  394. ):
  395. super().__init__(code, msg, errcode)
  396. self.error_url = error_url
  397. def error_dict(self, config: Optional["HomeServerConfig"]) -> "JsonDict":
  398. return cs_error(self.msg, self.errcode, error_url=self.error_url)
  399. class LimitExceededError(SynapseError):
  400. """A client has sent too many requests and is being throttled."""
  401. include_retry_after_header = False
  402. def __init__(
  403. self,
  404. limiter_name: str,
  405. code: int = 429,
  406. retry_after_ms: Optional[int] = None,
  407. errcode: str = Codes.LIMIT_EXCEEDED,
  408. ):
  409. headers = (
  410. {"Retry-After": str(math.ceil(retry_after_ms / 1000))}
  411. if self.include_retry_after_header and retry_after_ms is not None
  412. else None
  413. )
  414. super().__init__(code, "Too Many Requests", errcode, headers=headers)
  415. self.retry_after_ms = retry_after_ms
  416. self.limiter_name = limiter_name
  417. def error_dict(self, config: Optional["HomeServerConfig"]) -> "JsonDict":
  418. return cs_error(self.msg, self.errcode, retry_after_ms=self.retry_after_ms)
  419. @property
  420. def debug_context(self) -> Optional[str]:
  421. return self.limiter_name
  422. class RoomKeysVersionError(SynapseError):
  423. """A client has tried to upload to a non-current version of the room_keys store"""
  424. def __init__(self, current_version: str):
  425. """
  426. Args:
  427. current_version: the current version of the store they should have used
  428. """
  429. super().__init__(403, "Wrong room_keys version", Codes.WRONG_ROOM_KEYS_VERSION)
  430. self.current_version = current_version
  431. def error_dict(self, config: Optional["HomeServerConfig"]) -> "JsonDict":
  432. return cs_error(self.msg, self.errcode, current_version=self.current_version)
  433. class UnsupportedRoomVersionError(SynapseError):
  434. """The client's request to create a room used a room version that the server does
  435. not support."""
  436. def __init__(self, msg: str = "Homeserver does not support this room version"):
  437. super().__init__(
  438. code=400,
  439. msg=msg,
  440. errcode=Codes.UNSUPPORTED_ROOM_VERSION,
  441. )
  442. class ThreepidValidationError(SynapseError):
  443. """An error raised when there was a problem authorising an event."""
  444. def __init__(self, msg: str, errcode: str = Codes.FORBIDDEN):
  445. super().__init__(400, msg, errcode)
  446. class IncompatibleRoomVersionError(SynapseError):
  447. """A server is trying to join a room whose version it does not support.
  448. Unlike UnsupportedRoomVersionError, it is specific to the case of the make_join
  449. failing.
  450. """
  451. def __init__(self, room_version: str):
  452. super().__init__(
  453. code=400,
  454. msg="Your homeserver does not support the features required to "
  455. "interact with this room",
  456. errcode=Codes.INCOMPATIBLE_ROOM_VERSION,
  457. )
  458. self._room_version = room_version
  459. def error_dict(self, config: Optional["HomeServerConfig"]) -> "JsonDict":
  460. return cs_error(self.msg, self.errcode, room_version=self._room_version)
  461. class PasswordRefusedError(SynapseError):
  462. """A password has been refused, either during password reset/change or registration."""
  463. def __init__(
  464. self,
  465. msg: str = "This password doesn't comply with the server's policy",
  466. errcode: str = Codes.WEAK_PASSWORD,
  467. ):
  468. super().__init__(
  469. code=400,
  470. msg=msg,
  471. errcode=errcode,
  472. )
  473. class RequestSendFailed(RuntimeError):
  474. """Sending a HTTP request over federation failed due to not being able to
  475. talk to the remote server for some reason.
  476. This exception is used to differentiate "expected" errors that arise due to
  477. networking (e.g. DNS failures, connection timeouts etc), versus unexpected
  478. errors (like programming errors).
  479. """
  480. def __init__(self, inner_exception: BaseException, can_retry: bool):
  481. super().__init__(
  482. "Failed to send request: %s: %s"
  483. % (type(inner_exception).__name__, inner_exception)
  484. )
  485. self.inner_exception = inner_exception
  486. self.can_retry = can_retry
  487. class UnredactedContentDeletedError(SynapseError):
  488. def __init__(self, content_keep_ms: Optional[int] = None):
  489. super().__init__(
  490. 404,
  491. "The content for that event has already been erased from the database",
  492. errcode=Codes.UNREDACTED_CONTENT_DELETED,
  493. )
  494. self.content_keep_ms = content_keep_ms
  495. def error_dict(self, config: Optional["HomeServerConfig"]) -> "JsonDict":
  496. extra = {}
  497. if self.content_keep_ms is not None:
  498. extra = {"fi.mau.msc2815.content_keep_ms": self.content_keep_ms}
  499. return cs_error(self.msg, self.errcode, **extra)
  500. class NotApprovedError(SynapseError):
  501. def __init__(
  502. self,
  503. msg: str,
  504. approval_notice_medium: str,
  505. ):
  506. super().__init__(
  507. code=403,
  508. msg=msg,
  509. errcode=Codes.USER_AWAITING_APPROVAL,
  510. additional_fields={"approval_notice_medium": approval_notice_medium},
  511. )
  512. def cs_error(msg: str, code: str = Codes.UNKNOWN, **kwargs: Any) -> "JsonDict":
  513. """Utility method for constructing an error response for client-server
  514. interactions.
  515. Args:
  516. msg: The error message.
  517. code: The error code.
  518. kwargs: Additional keys to add to the response.
  519. Returns:
  520. A dict representing the error response JSON.
  521. """
  522. err = {"error": msg, "errcode": code}
  523. for key, value in kwargs.items():
  524. err[key] = value
  525. return err
  526. class FederationError(RuntimeError):
  527. """
  528. Raised when we process an erroneous PDU.
  529. There are two kinds of scenarios where this exception can be raised:
  530. 1. We may pull an invalid PDU from a remote homeserver (e.g. during backfill). We
  531. raise this exception to signal an error to the rest of the application.
  532. 2. We may be pushed an invalid PDU as part of a `/send` transaction from a remote
  533. homeserver. We raise so that we can respond to the transaction and include the
  534. error string in the "PDU Processing Result". The message which will likely be
  535. ignored by the remote homeserver and is not machine parse-able since it's just a
  536. string.
  537. TODO: In the future, we should split these usage scenarios into their own error types.
  538. FATAL: The remote server could not interpret the source event.
  539. (e.g., it was missing a required field)
  540. ERROR: The remote server interpreted the event, but it failed some other
  541. check (e.g. auth)
  542. WARN: The remote server accepted the event, but believes some part of it
  543. is wrong (e.g., it referred to an invalid event)
  544. """
  545. def __init__(
  546. self,
  547. level: str,
  548. code: int,
  549. reason: str,
  550. affected: str,
  551. source: Optional[str] = None,
  552. ):
  553. if level not in ["FATAL", "ERROR", "WARN"]:
  554. raise ValueError("Level is not valid: %s" % (level,))
  555. self.level = level
  556. self.code = code
  557. self.reason = reason
  558. self.affected = affected
  559. self.source = source
  560. msg = "%s %s: %s" % (level, code, reason)
  561. super().__init__(msg)
  562. def get_dict(self) -> "JsonDict":
  563. return {
  564. "level": self.level,
  565. "code": self.code,
  566. "reason": self.reason,
  567. "affected": self.affected,
  568. "source": self.source if self.source else self.affected,
  569. }
  570. class FederationPullAttemptBackoffError(RuntimeError):
  571. """
  572. Raised to indicate that we are are deliberately not attempting to pull the given
  573. event over federation because we've already done so recently and are backing off.
  574. Attributes:
  575. event_id: The event_id which we are refusing to pull
  576. message: A custom error message that gives more context
  577. retry_after_ms: The remaining backoff interval, in milliseconds
  578. """
  579. def __init__(
  580. self, event_ids: "StrCollection", message: Optional[str], retry_after_ms: int
  581. ):
  582. event_ids = list(event_ids)
  583. if message:
  584. error_message = message
  585. else:
  586. error_message = (
  587. f"Not attempting to pull event_ids={event_ids} because we already "
  588. "tried to pull them recently (backing off)."
  589. )
  590. super().__init__(error_message)
  591. self.event_ids = event_ids
  592. self.retry_after_ms = retry_after_ms
  593. class HttpResponseException(CodeMessageException):
  594. """
  595. Represents an HTTP-level failure of an outbound request
  596. Attributes:
  597. response: body of response
  598. """
  599. def __init__(self, code: int, msg: str, response: bytes):
  600. """
  601. Args:
  602. code: HTTP status code
  603. msg: reason phrase from HTTP response status line
  604. response: body of response
  605. """
  606. super().__init__(code, msg)
  607. self.response = response
  608. def to_synapse_error(self) -> SynapseError:
  609. """Make a SynapseError based on an HTTPResponseException
  610. This is useful when a proxied request has failed, and we need to
  611. decide how to map the failure onto a matrix error to send back to the
  612. client.
  613. An attempt is made to parse the body of the http response as a matrix
  614. error. If that succeeds, the errcode and error message from the body
  615. are used as the errcode and error message in the new synapse error.
  616. Otherwise, the errcode is set to M_UNKNOWN, and the error message is
  617. set to the reason code from the HTTP response.
  618. Returns:
  619. The error converted to a SynapseError.
  620. """
  621. # try to parse the body as json, to get better errcode/msg, but
  622. # default to M_UNKNOWN with the HTTP status as the error text
  623. try:
  624. j = json_decoder.decode(self.response.decode("utf-8"))
  625. except ValueError:
  626. j = {}
  627. if not isinstance(j, dict):
  628. j = {}
  629. errcode = j.pop("errcode", Codes.UNKNOWN)
  630. errmsg = j.pop("error", self.msg)
  631. return ProxiedRequestError(self.code, errmsg, errcode, j)
  632. class ShadowBanError(Exception):
  633. """
  634. Raised when a shadow-banned user attempts to perform an action.
  635. This should be caught and a proper "fake" success response sent to the user.
  636. """
  637. class ModuleFailedException(Exception):
  638. """
  639. Raised when a module API callback fails, for example because it raised an
  640. exception.
  641. """
  642. class PartialStateConflictError(SynapseError):
  643. """An internal error raised when attempting to persist an event with partial state
  644. after the room containing the event has been un-partial stated.
  645. This error should be handled by recomputing the event context and trying again.
  646. This error has an HTTP status code so that it can be transported over replication.
  647. It should not be exposed to clients.
  648. """
  649. @staticmethod
  650. def message() -> str:
  651. return "Cannot persist partial state event in un-partial stated room"
  652. def __init__(self) -> None:
  653. super().__init__(
  654. HTTPStatus.CONFLICT,
  655. msg=PartialStateConflictError.message(),
  656. errcode=Codes.UNKNOWN,
  657. )