errors.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket 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. logger = logging.getLogger(__name__)
  18. class Codes(object):
  19. UNRECOGNIZED = "M_UNRECOGNIZED"
  20. UNAUTHORIZED = "M_UNAUTHORIZED"
  21. FORBIDDEN = "M_FORBIDDEN"
  22. BAD_JSON = "M_BAD_JSON"
  23. NOT_JSON = "M_NOT_JSON"
  24. USER_IN_USE = "M_USER_IN_USE"
  25. ROOM_IN_USE = "M_ROOM_IN_USE"
  26. BAD_PAGINATION = "M_BAD_PAGINATION"
  27. BAD_STATE = "M_BAD_STATE"
  28. UNKNOWN = "M_UNKNOWN"
  29. NOT_FOUND = "M_NOT_FOUND"
  30. MISSING_TOKEN = "M_MISSING_TOKEN"
  31. UNKNOWN_TOKEN = "M_UNKNOWN_TOKEN"
  32. GUEST_ACCESS_FORBIDDEN = "M_GUEST_ACCESS_FORBIDDEN"
  33. LIMIT_EXCEEDED = "M_LIMIT_EXCEEDED"
  34. CAPTCHA_NEEDED = "M_CAPTCHA_NEEDED"
  35. CAPTCHA_INVALID = "M_CAPTCHA_INVALID"
  36. MISSING_PARAM = "M_MISSING_PARAM"
  37. TOO_LARGE = "M_TOO_LARGE"
  38. EXCLUSIVE = "M_EXCLUSIVE"
  39. THREEPID_AUTH_FAILED = "M_THREEPID_AUTH_FAILED"
  40. THREEPID_IN_USE = "THREEPID_IN_USE"
  41. INVALID_USERNAME = "M_INVALID_USERNAME"
  42. class CodeMessageException(RuntimeError):
  43. """An exception with integer code and message string attributes."""
  44. def __init__(self, code, msg):
  45. super(CodeMessageException, self).__init__("%d: %s" % (code, msg))
  46. self.code = code
  47. self.msg = msg
  48. self.response_code_message = None
  49. def error_dict(self):
  50. return cs_error(self.msg)
  51. class SynapseError(CodeMessageException):
  52. """A base error which can be caught for all synapse events."""
  53. def __init__(self, code, msg, errcode=Codes.UNKNOWN):
  54. """Constructs a synapse error.
  55. Args:
  56. code (int): The integer error code (an HTTP response code)
  57. msg (str): The human-readable error message.
  58. err (str): The error code e.g 'M_FORBIDDEN'
  59. """
  60. super(SynapseError, self).__init__(code, msg)
  61. self.errcode = errcode
  62. def error_dict(self):
  63. return cs_error(
  64. self.msg,
  65. self.errcode,
  66. )
  67. class RegistrationError(SynapseError):
  68. """An error raised when a registration event fails."""
  69. pass
  70. class UnrecognizedRequestError(SynapseError):
  71. """An error indicating we don't understand the request you're trying to make"""
  72. def __init__(self, *args, **kwargs):
  73. if "errcode" not in kwargs:
  74. kwargs["errcode"] = Codes.UNRECOGNIZED
  75. message = None
  76. if len(args) == 0:
  77. message = "Unrecognized request"
  78. else:
  79. message = args[0]
  80. super(UnrecognizedRequestError, self).__init__(
  81. 400,
  82. message,
  83. **kwargs
  84. )
  85. class NotFoundError(SynapseError):
  86. """An error indicating we can't find the thing you asked for"""
  87. def __init__(self, *args, **kwargs):
  88. if "errcode" not in kwargs:
  89. kwargs["errcode"] = Codes.NOT_FOUND
  90. super(NotFoundError, self).__init__(
  91. 404,
  92. "Not found",
  93. **kwargs
  94. )
  95. class AuthError(SynapseError):
  96. """An error raised when there was a problem authorising an event."""
  97. def __init__(self, *args, **kwargs):
  98. if "errcode" not in kwargs:
  99. kwargs["errcode"] = Codes.FORBIDDEN
  100. super(AuthError, self).__init__(*args, **kwargs)
  101. class EventSizeError(SynapseError):
  102. """An error raised when an event is too big."""
  103. def __init__(self, *args, **kwargs):
  104. if "errcode" not in kwargs:
  105. kwargs["errcode"] = Codes.TOO_LARGE
  106. super(EventSizeError, self).__init__(413, *args, **kwargs)
  107. class EventStreamError(SynapseError):
  108. """An error raised when there a problem with the event stream."""
  109. def __init__(self, *args, **kwargs):
  110. if "errcode" not in kwargs:
  111. kwargs["errcode"] = Codes.BAD_PAGINATION
  112. super(EventStreamError, self).__init__(*args, **kwargs)
  113. class LoginError(SynapseError):
  114. """An error raised when there was a problem logging in."""
  115. pass
  116. class StoreError(SynapseError):
  117. """An error raised when there was a problem storing some data."""
  118. pass
  119. class InvalidCaptchaError(SynapseError):
  120. def __init__(self, code=400, msg="Invalid captcha.", error_url=None,
  121. errcode=Codes.CAPTCHA_INVALID):
  122. super(InvalidCaptchaError, self).__init__(code, msg, errcode)
  123. self.error_url = error_url
  124. def error_dict(self):
  125. return cs_error(
  126. self.msg,
  127. self.errcode,
  128. error_url=self.error_url,
  129. )
  130. class LimitExceededError(SynapseError):
  131. """A client has sent too many requests and is being throttled.
  132. """
  133. def __init__(self, code=429, msg="Too Many Requests", retry_after_ms=None,
  134. errcode=Codes.LIMIT_EXCEEDED):
  135. super(LimitExceededError, self).__init__(code, msg, errcode)
  136. self.retry_after_ms = retry_after_ms
  137. self.response_code_message = "Too Many Requests"
  138. def error_dict(self):
  139. return cs_error(
  140. self.msg,
  141. self.errcode,
  142. retry_after_ms=self.retry_after_ms,
  143. )
  144. def cs_exception(exception):
  145. if isinstance(exception, CodeMessageException):
  146. return exception.error_dict()
  147. else:
  148. logger.error("Unknown exception type: %s", type(exception))
  149. return {}
  150. def cs_error(msg, code=Codes.UNKNOWN, **kwargs):
  151. """ Utility method for constructing an error response for client-server
  152. interactions.
  153. Args:
  154. msg (str): The error message.
  155. code (int): The error code.
  156. kwargs : Additional keys to add to the response.
  157. Returns:
  158. A dict representing the error response JSON.
  159. """
  160. err = {"error": msg, "errcode": code}
  161. for key, value in kwargs.iteritems():
  162. err[key] = value
  163. return err
  164. class FederationError(RuntimeError):
  165. """ This class is used to inform remote home servers about erroneous
  166. PDUs they sent us.
  167. FATAL: The remote server could not interpret the source event.
  168. (e.g., it was missing a required field)
  169. ERROR: The remote server interpreted the event, but it failed some other
  170. check (e.g. auth)
  171. WARN: The remote server accepted the event, but believes some part of it
  172. is wrong (e.g., it referred to an invalid event)
  173. """
  174. def __init__(self, level, code, reason, affected, source=None):
  175. if level not in ["FATAL", "ERROR", "WARN"]:
  176. raise ValueError("Level is not valid: %s" % (level,))
  177. self.level = level
  178. self.code = code
  179. self.reason = reason
  180. self.affected = affected
  181. self.source = source
  182. msg = "%s %s: %s" % (level, code, reason,)
  183. super(FederationError, self).__init__(msg)
  184. def get_dict(self):
  185. return {
  186. "level": self.level,
  187. "code": self.code,
  188. "reason": self.reason,
  189. "affected": self.affected,
  190. "source": self.source if self.source else self.affected,
  191. }
  192. class HttpResponseException(CodeMessageException):
  193. def __init__(self, code, msg, response):
  194. self.response = response
  195. super(HttpResponseException, self).__init__(code, msg)