authentik.lib.tracing.sentry

authentik Sentry integration

  1"""authentik Sentry integration"""
  2
  3from contextlib import contextmanager
  4from typing import Any
  5
  6import sentry_sdk
  7from django.conf import settings
  8from sentry_sdk import HttpTransport, get_current_scope
  9from sentry_sdk.integrations.argv import ArgvIntegration
 10from sentry_sdk.integrations.django import DjangoIntegration
 11from sentry_sdk.integrations.dramatiq import DramatiqIntegration
 12from sentry_sdk.integrations.socket import SocketIntegration
 13from sentry_sdk.integrations.stdlib import StdlibIntegration
 14from sentry_sdk.integrations.threading import ThreadingIntegration
 15from sentry_sdk.tracing import BAGGAGE_HEADER_NAME, SENTRY_TRACE_HEADER_NAME
 16from structlog.stdlib import get_logger
 17
 18from authentik import authentik_build_hash, authentik_version
 19from authentik.lib.config import CONFIG
 20from authentik.lib.tracing.common import Tracer
 21from authentik.lib.tracing.exceptions import should_ignore_exception
 22from authentik.lib.utils.http import authentik_user_agent
 23from authentik.lib.utils.reflection import get_env
 24
 25LOGGER = get_logger()
 26_root_path = CONFIG.get("web.path", "/")
 27
 28
 29class _SentryTransport(HttpTransport):
 30    """Custom sentry transport with custom user-agent"""
 31
 32    def __init__(self, options: dict[str, Any]) -> None:
 33        super().__init__(options)
 34        self._auth = self.parsed_dsn.to_auth(authentik_user_agent())
 35
 36
 37def _traces_sampler(sampling_context: dict) -> float:
 38    """Custom sampler to ignore certain routes"""
 39    path = sampling_context.get("asgi_scope", {}).get("path", "")
 40    _type = sampling_context.get("asgi_scope", {}).get("type", "")
 41    # Ignore all healthcheck routes
 42    if path.startswith(f"{_root_path}-/health") or path.startswith(f"{_root_path}-/metrics"):
 43        return 0
 44    if _type == "websocket":
 45        return 0
 46    if CONFIG.get_bool("debug"):
 47        return 1
 48    return float(CONFIG.get("error_reporting.sample_rate", 0.1))
 49
 50
 51def _before_send(event: dict, hint: dict) -> dict | None:
 52    """Check if error is one this branch of authentik ignores, and drop it if so"""
 53    exc_value = None
 54    if "exc_info" in hint:
 55        _, exc_value, _ = hint["exc_info"]
 56        if should_ignore_exception(exc_value):
 57            LOGGER.debug("dropping exception", exc=exc_value)
 58            return None
 59    if event.get("logger") in [
 60        "asyncio",
 61        "multiprocessing",
 62        "django.security.DisallowedHost",
 63        "paramiko.transport",
 64    ]:
 65        return None
 66    LOGGER.debug("sending event to sentry", exc=exc_value, source_logger=event.get("logger", None))
 67    if settings.DEBUG:
 68        return None
 69    return event
 70
 71
 72class SentryTracer(Tracer):
 73    """Tracer backed by the Sentry SDK, reporting crashes to error_reporting.sentry_dsn.
 74    With `tracing=False` Sentry only reports errors, leaving tracing to another backend"""
 75
 76    def __init__(self, tracing: bool = True) -> None:
 77        self.tracing = tracing
 78
 79    def setup_pre_fork(self) -> None:
 80        """Configure and initialize the Sentry SDK"""
 81        tracing_args: dict[str, Any] = {}
 82        if self.tracing:
 83            tracing_args = {
 84                "traces_sampler": _traces_sampler,
 85                "profiles_sample_rate": float(CONFIG.get("error_reporting.sample_rate", 0.1)),
 86            }
 87        sentry_sdk.init(
 88            dsn=CONFIG.get("error_reporting.sentry_dsn"),
 89            environment=CONFIG.get("error_reporting.environment", "customer"),
 90            send_default_pii=CONFIG.get_bool("error_reporting.send_pii", False),
 91            integrations=[
 92                ArgvIntegration(),
 93                DjangoIntegration(
 94                    transaction_style="url",
 95                    cache_spans=self.tracing,
 96                    middleware_spans=self.tracing,
 97                    signals_spans=self.tracing,
 98                ),
 99                DramatiqIntegration(),
100                SocketIntegration(),
101                StdlibIntegration(),
102                ThreadingIntegration(propagate_hub=True),
103            ],
104            before_send=_before_send,
105            release=f"authentik@{authentik_version()}",
106            transport=_SentryTransport,
107            **tracing_args,
108            **CONFIG.get_dict_from_b64_json("error_reporting.extra_args", {}),
109        )
110        sentry_sdk.set_tag("authentik.build_hash", authentik_build_hash("tagged"))
111        sentry_sdk.set_tag("authentik.env", get_env())
112        sentry_sdk.set_tag("authentik.component", "backend")
113
114    def record_exception(self, exc: Exception) -> None:
115        sentry_sdk.capture_exception(exc)
116
117    def get_http_meta(self) -> dict[str, str]:
118        scope = get_current_scope()
119        meta = {SENTRY_TRACE_HEADER_NAME: scope.get_traceparent() or ""}
120        if bag := scope.get_baggage():
121            meta[BAGGAGE_HEADER_NAME] = bag.serialize()
122        return meta
123
124    def set_tag(self, key: str, value: Any) -> None:
125        sentry_sdk.set_tag(key, value)
126
127    @contextmanager
128    def start_span(self, op: str, name: str | None = None):
129        with sentry_sdk.start_span(op=op, name=name) as span:
130            yield span
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
class SentryTracer(authentik.lib.tracing.common.Tracer):
 73class SentryTracer(Tracer):
 74    """Tracer backed by the Sentry SDK, reporting crashes to error_reporting.sentry_dsn.
 75    With `tracing=False` Sentry only reports errors, leaving tracing to another backend"""
 76
 77    def __init__(self, tracing: bool = True) -> None:
 78        self.tracing = tracing
 79
 80    def setup_pre_fork(self) -> None:
 81        """Configure and initialize the Sentry SDK"""
 82        tracing_args: dict[str, Any] = {}
 83        if self.tracing:
 84            tracing_args = {
 85                "traces_sampler": _traces_sampler,
 86                "profiles_sample_rate": float(CONFIG.get("error_reporting.sample_rate", 0.1)),
 87            }
 88        sentry_sdk.init(
 89            dsn=CONFIG.get("error_reporting.sentry_dsn"),
 90            environment=CONFIG.get("error_reporting.environment", "customer"),
 91            send_default_pii=CONFIG.get_bool("error_reporting.send_pii", False),
 92            integrations=[
 93                ArgvIntegration(),
 94                DjangoIntegration(
 95                    transaction_style="url",
 96                    cache_spans=self.tracing,
 97                    middleware_spans=self.tracing,
 98                    signals_spans=self.tracing,
 99                ),
100                DramatiqIntegration(),
101                SocketIntegration(),
102                StdlibIntegration(),
103                ThreadingIntegration(propagate_hub=True),
104            ],
105            before_send=_before_send,
106            release=f"authentik@{authentik_version()}",
107            transport=_SentryTransport,
108            **tracing_args,
109            **CONFIG.get_dict_from_b64_json("error_reporting.extra_args", {}),
110        )
111        sentry_sdk.set_tag("authentik.build_hash", authentik_build_hash("tagged"))
112        sentry_sdk.set_tag("authentik.env", get_env())
113        sentry_sdk.set_tag("authentik.component", "backend")
114
115    def record_exception(self, exc: Exception) -> None:
116        sentry_sdk.capture_exception(exc)
117
118    def get_http_meta(self) -> dict[str, str]:
119        scope = get_current_scope()
120        meta = {SENTRY_TRACE_HEADER_NAME: scope.get_traceparent() or ""}
121        if bag := scope.get_baggage():
122            meta[BAGGAGE_HEADER_NAME] = bag.serialize()
123        return meta
124
125    def set_tag(self, key: str, value: Any) -> None:
126        sentry_sdk.set_tag(key, value)
127
128    @contextmanager
129    def start_span(self, op: str, name: str | None = None):
130        with sentry_sdk.start_span(op=op, name=name) as span:
131            yield span

Tracer backed by the Sentry SDK, reporting crashes to error_reporting.sentry_dsn. With tracing=False Sentry only reports errors, leaving tracing to another backend

SentryTracer(tracing: bool = True)
77    def __init__(self, tracing: bool = True) -> None:
78        self.tracing = tracing
tracing
def setup_pre_fork(self) -> None:
 80    def setup_pre_fork(self) -> None:
 81        """Configure and initialize the Sentry SDK"""
 82        tracing_args: dict[str, Any] = {}
 83        if self.tracing:
 84            tracing_args = {
 85                "traces_sampler": _traces_sampler,
 86                "profiles_sample_rate": float(CONFIG.get("error_reporting.sample_rate", 0.1)),
 87            }
 88        sentry_sdk.init(
 89            dsn=CONFIG.get("error_reporting.sentry_dsn"),
 90            environment=CONFIG.get("error_reporting.environment", "customer"),
 91            send_default_pii=CONFIG.get_bool("error_reporting.send_pii", False),
 92            integrations=[
 93                ArgvIntegration(),
 94                DjangoIntegration(
 95                    transaction_style="url",
 96                    cache_spans=self.tracing,
 97                    middleware_spans=self.tracing,
 98                    signals_spans=self.tracing,
 99                ),
100                DramatiqIntegration(),
101                SocketIntegration(),
102                StdlibIntegration(),
103                ThreadingIntegration(propagate_hub=True),
104            ],
105            before_send=_before_send,
106            release=f"authentik@{authentik_version()}",
107            transport=_SentryTransport,
108            **tracing_args,
109            **CONFIG.get_dict_from_b64_json("error_reporting.extra_args", {}),
110        )
111        sentry_sdk.set_tag("authentik.build_hash", authentik_build_hash("tagged"))
112        sentry_sdk.set_tag("authentik.env", get_env())
113        sentry_sdk.set_tag("authentik.component", "backend")

Configure and initialize the Sentry SDK

def record_exception(self, exc: Exception) -> None:
115    def record_exception(self, exc: Exception) -> None:
116        sentry_sdk.capture_exception(exc)
def get_http_meta(self) -> dict[str, str]:
118    def get_http_meta(self) -> dict[str, str]:
119        scope = get_current_scope()
120        meta = {SENTRY_TRACE_HEADER_NAME: scope.get_traceparent() or ""}
121        if bag := scope.get_baggage():
122            meta[BAGGAGE_HEADER_NAME] = bag.serialize()
123        return meta
def set_tag(self, key: str, value: Any) -> None:
125    def set_tag(self, key: str, value: Any) -> None:
126        sentry_sdk.set_tag(key, value)
@contextmanager
def start_span(self, op: str, name: str | None = None):
128    @contextmanager
129    def start_span(self, op: str, name: str | None = None):
130        with sentry_sdk.start_span(op=op, name=name) as span:
131            yield span