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.
 
 
 
 
 
 

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