falcon.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import sentry_sdk
  2. from sentry_sdk.integrations import _check_minimum_version, Integration, DidNotEnable
  3. from sentry_sdk.integrations._wsgi_common import RequestExtractor
  4. from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware
  5. from sentry_sdk.tracing import SOURCE_FOR_STYLE
  6. from sentry_sdk.utils import (
  7. capture_internal_exceptions,
  8. ensure_integration_enabled,
  9. event_from_exception,
  10. parse_version,
  11. )
  12. from typing import TYPE_CHECKING
  13. if TYPE_CHECKING:
  14. from typing import Any
  15. from typing import Dict
  16. from typing import Optional
  17. from sentry_sdk._types import Event, EventProcessor
  18. # In Falcon 3.0 `falcon.api_helpers` is renamed to `falcon.app_helpers`
  19. # and `falcon.API` to `falcon.App`
  20. try:
  21. import falcon # type: ignore
  22. from falcon import __version__ as FALCON_VERSION
  23. except ImportError:
  24. raise DidNotEnable("Falcon not installed")
  25. try:
  26. import falcon.app_helpers # type: ignore
  27. falcon_helpers = falcon.app_helpers
  28. falcon_app_class = falcon.App
  29. FALCON3 = True
  30. except ImportError:
  31. import falcon.api_helpers # type: ignore
  32. falcon_helpers = falcon.api_helpers
  33. falcon_app_class = falcon.API
  34. FALCON3 = False
  35. _FALCON_UNSET = None # type: Optional[object]
  36. if FALCON3: # falcon.request._UNSET is only available in Falcon 3.0+
  37. with capture_internal_exceptions():
  38. from falcon.request import _UNSET as _FALCON_UNSET # type: ignore[import-not-found, no-redef]
  39. class FalconRequestExtractor(RequestExtractor):
  40. def env(self):
  41. # type: () -> Dict[str, Any]
  42. return self.request.env
  43. def cookies(self):
  44. # type: () -> Dict[str, Any]
  45. return self.request.cookies
  46. def form(self):
  47. # type: () -> None
  48. return None # No such concept in Falcon
  49. def files(self):
  50. # type: () -> None
  51. return None # No such concept in Falcon
  52. def raw_data(self):
  53. # type: () -> Optional[str]
  54. # As request data can only be read once we won't make this available
  55. # to Sentry. Just send back a dummy string in case there was a
  56. # content length.
  57. # TODO(jmagnusson): Figure out if there's a way to support this
  58. content_length = self.content_length()
  59. if content_length > 0:
  60. return "[REQUEST_CONTAINING_RAW_DATA]"
  61. else:
  62. return None
  63. def json(self):
  64. # type: () -> Optional[Dict[str, Any]]
  65. # fallback to cached_media = None if self.request._media is not available
  66. cached_media = None
  67. with capture_internal_exceptions():
  68. # self.request._media is the cached self.request.media
  69. # value. It is only available if self.request.media
  70. # has already been accessed. Therefore, reading
  71. # self.request._media will not exhaust the raw request
  72. # stream (self.request.bounded_stream) because it has
  73. # already been read if self.request._media is set.
  74. cached_media = self.request._media
  75. if cached_media is not _FALCON_UNSET:
  76. return cached_media
  77. return None
  78. class SentryFalconMiddleware:
  79. """Captures exceptions in Falcon requests and send to Sentry"""
  80. def process_request(self, req, resp, *args, **kwargs):
  81. # type: (Any, Any, *Any, **Any) -> None
  82. integration = sentry_sdk.get_client().get_integration(FalconIntegration)
  83. if integration is None:
  84. return
  85. scope = sentry_sdk.get_isolation_scope()
  86. scope._name = "falcon"
  87. scope.add_event_processor(_make_request_event_processor(req, integration))
  88. TRANSACTION_STYLE_VALUES = ("uri_template", "path")
  89. class FalconIntegration(Integration):
  90. identifier = "falcon"
  91. origin = f"auto.http.{identifier}"
  92. transaction_style = ""
  93. def __init__(self, transaction_style="uri_template"):
  94. # type: (str) -> None
  95. if transaction_style not in TRANSACTION_STYLE_VALUES:
  96. raise ValueError(
  97. "Invalid value for transaction_style: %s (must be in %s)"
  98. % (transaction_style, TRANSACTION_STYLE_VALUES)
  99. )
  100. self.transaction_style = transaction_style
  101. @staticmethod
  102. def setup_once():
  103. # type: () -> None
  104. version = parse_version(FALCON_VERSION)
  105. _check_minimum_version(FalconIntegration, version)
  106. _patch_wsgi_app()
  107. _patch_handle_exception()
  108. _patch_prepare_middleware()
  109. def _patch_wsgi_app():
  110. # type: () -> None
  111. original_wsgi_app = falcon_app_class.__call__
  112. def sentry_patched_wsgi_app(self, env, start_response):
  113. # type: (falcon.API, Any, Any) -> Any
  114. integration = sentry_sdk.get_client().get_integration(FalconIntegration)
  115. if integration is None:
  116. return original_wsgi_app(self, env, start_response)
  117. sentry_wrapped = SentryWsgiMiddleware(
  118. lambda envi, start_resp: original_wsgi_app(self, envi, start_resp),
  119. span_origin=FalconIntegration.origin,
  120. )
  121. return sentry_wrapped(env, start_response)
  122. falcon_app_class.__call__ = sentry_patched_wsgi_app
  123. def _patch_handle_exception():
  124. # type: () -> None
  125. original_handle_exception = falcon_app_class._handle_exception
  126. @ensure_integration_enabled(FalconIntegration, original_handle_exception)
  127. def sentry_patched_handle_exception(self, *args):
  128. # type: (falcon.API, *Any) -> Any
  129. # NOTE(jmagnusson): falcon 2.0 changed falcon.API._handle_exception
  130. # method signature from `(ex, req, resp, params)` to
  131. # `(req, resp, ex, params)`
  132. ex = response = None
  133. with capture_internal_exceptions():
  134. ex = next(argument for argument in args if isinstance(argument, Exception))
  135. response = next(
  136. argument for argument in args if isinstance(argument, falcon.Response)
  137. )
  138. was_handled = original_handle_exception(self, *args)
  139. if ex is None or response is None:
  140. # Both ex and response should have a non-None value at this point; otherwise,
  141. # there is an error with the SDK that will have been captured in the
  142. # capture_internal_exceptions block above.
  143. return was_handled
  144. if _exception_leads_to_http_5xx(ex, response):
  145. event, hint = event_from_exception(
  146. ex,
  147. client_options=sentry_sdk.get_client().options,
  148. mechanism={"type": "falcon", "handled": False},
  149. )
  150. sentry_sdk.capture_event(event, hint=hint)
  151. return was_handled
  152. falcon_app_class._handle_exception = sentry_patched_handle_exception
  153. def _patch_prepare_middleware():
  154. # type: () -> None
  155. original_prepare_middleware = falcon_helpers.prepare_middleware
  156. def sentry_patched_prepare_middleware(
  157. middleware=None, independent_middleware=False, asgi=False
  158. ):
  159. # type: (Any, Any, bool) -> Any
  160. if asgi:
  161. # We don't support ASGI Falcon apps, so we don't patch anything here
  162. return original_prepare_middleware(middleware, independent_middleware, asgi)
  163. integration = sentry_sdk.get_client().get_integration(FalconIntegration)
  164. if integration is not None:
  165. middleware = [SentryFalconMiddleware()] + (middleware or [])
  166. # We intentionally omit the asgi argument here, since the default is False anyways,
  167. # and this way, we remain backwards-compatible with pre-3.0.0 Falcon versions.
  168. return original_prepare_middleware(middleware, independent_middleware)
  169. falcon_helpers.prepare_middleware = sentry_patched_prepare_middleware
  170. def _exception_leads_to_http_5xx(ex, response):
  171. # type: (Exception, falcon.Response) -> bool
  172. is_server_error = isinstance(ex, falcon.HTTPError) and (ex.status or "").startswith(
  173. "5"
  174. )
  175. is_unhandled_error = not isinstance(
  176. ex, (falcon.HTTPError, falcon.http_status.HTTPStatus)
  177. )
  178. # We only check the HTTP status on Falcon 3 because in Falcon 2, the status on the response
  179. # at the stage where we capture it is listed as 200, even though we would expect to see a 500
  180. # status. Since at the time of this change, Falcon 2 is ca. 4 years old, we have decided to
  181. # only perform this check on Falcon 3+, despite the risk that some handled errors might be
  182. # reported to Sentry as unhandled on Falcon 2.
  183. return (is_server_error or is_unhandled_error) and (
  184. not FALCON3 or _has_http_5xx_status(response)
  185. )
  186. def _has_http_5xx_status(response):
  187. # type: (falcon.Response) -> bool
  188. return response.status.startswith("5")
  189. def _set_transaction_name_and_source(event, transaction_style, request):
  190. # type: (Event, str, falcon.Request) -> None
  191. name_for_style = {
  192. "uri_template": request.uri_template,
  193. "path": request.path,
  194. }
  195. event["transaction"] = name_for_style[transaction_style]
  196. event["transaction_info"] = {"source": SOURCE_FOR_STYLE[transaction_style]}
  197. def _make_request_event_processor(req, integration):
  198. # type: (falcon.Request, FalconIntegration) -> EventProcessor
  199. def event_processor(event, hint):
  200. # type: (Event, dict[str, Any]) -> Event
  201. _set_transaction_name_and_source(event, integration.transaction_style, req)
  202. with capture_internal_exceptions():
  203. FalconRequestExtractor(req).extract_into_event(event)
  204. return event
  205. return event_processor