Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(api): add OpenTelemetry spans to DRF auth classes (#58226)

Paul D'Ambracc846f21dc77
diff --git a/posthog/api/query.py b/posthog/api/query.py
index 26e043ba87c1..e203454df98b 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -8,6 +8,7 @@ import orjson
import structlog
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse
+from opentelemetry import trace
from prometheus_client import Counter
from pydantic import BaseModel
from rest_framework import status, viewsets
@@ -70,6 +71,8 @@ from common.hogvm.python.utils import HogVMException
logger = structlog.get_logger(__name__)
+tracer = trace.get_tracer(__name__)
+
QUERY_VALIDATION_ERROR_TOTAL = Counter(
"posthog_query_validation_error_total",
"Query validation failures returned from the query API.",
@@ -168,7 +171,8 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMi
def create(self, request: Request, *args, **kwargs) -> Response:
self._validate_query_kind(request, kwargs.get("query_kind"))
start_time = perf_counter()
- upgraded_query = upgrade(request.data)
+ with tracer.start_as_current_span("posthog.query.upgrade"):
+ upgraded_query = upgrade(request.data)
data = self.get_model(upgraded_query, QueryRequest)
query = None
@@ -193,22 +197,31 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMi
else:
limit_context = None
- result = process_query_model(
- self.team,
- query,
- execution_mode=execution_mode,
- query_id=client_query_id,
- user=request.user, # type: ignore[arg-type]
- is_query_service=(get_query_tag_value("access_method") == "personal_api_key"),
- limit_context=limit_context,
- analytics_props=analytics_props,
- )
- if isinstance(result, BaseModel):
- result = result.model_dump(by_alias=True)
+ with tracer.start_as_current_span("posthog.query.process_query_model") as process_span:
+ process_span.set_attribute("query.kind", getattr(query, "kind", "Other"))
+ process_span.set_attribute(
+ "query.is_query_service", get_query_tag_value("access_method") == "personal_api_key"
+ )
+ if limit_context is not None:
+ process_span.set_attribute("query.limit_context", limit_context.value)
+ result = process_query_model(
+ self.team,
+ query,
+ execution_mode=execution_mode,
+ query_id=client_query_id,
+ user=request.user, # type: ignore[arg-type]
+ is_query_service=(get_query_tag_value("access_method") == "personal_api_key"),
+ limit_context=limit_context,
+ analytics_props=analytics_props,
+ )
+ if isinstance(result, BaseModel):
+ result = result.model_dump(by_alias=True)
total_time_ms = round((perf_counter() - start_time) * 1000, 2)
try:
- response_bytes = len(orjson.dumps(result))
+ with tracer.start_as_current_span("posthog.query.serialize_response") as serialize_span:
+ response_bytes = len(orjson.dumps(result))
+ serialize_span.set_attribute("response.bytes", response_bytes)
report_user_or_team_action(
"query api response",
{
@@ -234,9 +247,11 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMi
)
if request.headers.get("x-posthog-client") == "mcp":
- formatted = self._try_format_for_llm(query, result)
- if formatted is not None:
- result["formatted_results"] = formatted
+ with tracer.start_as_current_span("posthog.query.format_for_llm") as llm_span:
+ formatted = self._try_format_for_llm(query, result)
+ llm_span.set_attribute("query.formatted", formatted is not None)
+ if formatted is not None:
+ result["formatted_results"] = formatted
return Response(result, status=response_status)
except (ExposedHogQLError, ExposedCHQueryError, HogVMException) as e:
diff --git a/posthog/auth.py b/posthog/auth.py
index 1ac74324dfd8..81e35d97d5f2 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -20,6 +20,7 @@ from django.utils import timezone
import jwt
import structlog
+from opentelemetry import trace
from prometheus_client import Counter
from rest_framework import authentication
from rest_framework.exceptions import AuthenticationFailed
@@ -61,6 +62,8 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
structlog_logger = structlog.get_logger(__name__)
+tracer = trace.get_tracer(__name__)
+
_SECRET_API_KEY_RE = re.compile(r"^phs_[a-zA-Z0-9]+$")
SECRET_API_KEY_BODY_COUNTER = Counter(
@@ -158,15 +161,16 @@ class SessionAuthentication(authentication.SessionAuthentication):
"""
def authenticate(self, request):
- auth_result = super().authenticate(request)
+ with tracer.start_as_current_span("posthog.auth.session"):
+ auth_result = super().authenticate(request)
- if not auth_result:
- return None
+ if not auth_result:
+ return None
- user, auth = auth_result
- enforce_two_factor(request, user)
+ user, auth = auth_result
+ enforce_two_factor(request, user)
- return (user, auth)
+ return (user, auth)
def authenticate_header(self, request):
return "Session"
@@ -242,22 +246,29 @@ class PersonalAPIKeyAuthentication(authentication.BaseAuthentication):
personal_api_key, source = personal_api_key_with_source
personal_api_key_object = None
mode_used = None
+ modes_tried = 0
- for mode, iterations in PERSONAL_API_KEY_MODES_TO_TRY:
- secure_value = hash_key_value(
- personal_api_key, mode=mode, legacy_salt=LEGACY_PERSONAL_API_KEY_SALT, iterations=iterations
- )
- try:
- personal_api_key_object = (
- PersonalAPIKey.objects.select_related("user")
- .filter(user__is_active=True)
- .get(secure_value=secure_value)
+ with tracer.start_as_current_span("posthog.auth.personal_api_key.db_lookup") as db_span:
+ for mode, iterations in PERSONAL_API_KEY_MODES_TO_TRY:
+ modes_tried += 1
+ secure_value = hash_key_value(
+ personal_api_key, mode=mode, legacy_salt=LEGACY_PERSONAL_API_KEY_SALT, iterations=iterations
)
- mode_used = mode
- PERSONAL_API_KEY_AUTH_COUNTER.labels(hash_mode=mode).inc()
- break
- except PersonalAPIKey.DoesNotExist:
- pass
+ try:
+ personal_api_key_object = (
+ PersonalAPIKey.objects.select_related("user")
+ .filter(user__is_active=True)
+ .get(secure_value=secure_value)
+ )
+ mode_used = mode
+ PERSONAL_API_KEY_AUTH_COUNTER.labels(hash_mode=mode).inc()
+ break
+ except PersonalAPIKey.DoesNotExist:
+ pass
+
+ db_span.set_attribute("auth.modes_tried", modes_tried)
+ if mode_used:
+ db_span.set_attribute("auth.hash_mode_used", mode_used)
if not personal_api_key_object:
source_display = cls._SOURCE_DISPLAY.get(source, source)
@@ -266,9 +277,11 @@ class PersonalAPIKeyAuthentication(authentication.BaseAuthentication):
# Upgrade the key if it's not in the latest mode. We can do this since above we've already checked
# that the key is valid in some mode, and we do check for all modes one by one.
if mode_used != "sha256":
- key_to_update = PersonalAPIKey.objects.select_for_update().get(id=personal_api_key_object.id)
- key_to_update.secure_value = hash_key_value(personal_api_key)
- key_to_update.save(update_fields=["secure_value"])
+ with tracer.start_as_current_span("posthog.auth.personal_api_key.mode_upgrade") as upgrade_span:
+ upgrade_span.set_attribute("auth.hash_mode_used", mode_used or "")
+ key_to_update = PersonalAPIKey.objects.select_for_update().get(id=personal_api_key_object.id)
+ key_to_update.secure_value = hash_key_value(personal_api_key)
+ key_to_update.save(update_fields=["secure_value"])
if source == cls.SOURCE_QUERY_STRING:
PERSONAL_API_KEY_QUERY_PARAM_COUNTER.labels(personal_api_key_object.user.uuid).inc()
@@ -276,35 +289,38 @@ class PersonalAPIKeyAuthentication(authentication.BaseAuthentication):
return personal_api_key_object
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
- personal_api_key_with_source = self.find_key_with_source(request)
- if not personal_api_key_with_source:
- return None
+ with tracer.start_as_current_span("posthog.auth.personal_api_key") as span:
+ personal_api_key_with_source = self.find_key_with_source(request)
+ if not personal_api_key_with_source:
+ return None
- _, source = personal_api_key_with_source
- personal_api_key_object = self.validate_key(personal_api_key_with_source)
-
- now = timezone.now()
- key_last_used_at = personal_api_key_object.last_used_at
- # Only updating last_used_at if the hour's changed
- # This is to avoid excessive UPDATE queries, while still presenting accurate (down to the hour) info in the UI
- if key_last_used_at is None or (now - key_last_used_at > timedelta(hours=1)):
- personal_api_key_object.last_used_at = now
- personal_api_key_object.save(update_fields=["last_used_at"])
- assert personal_api_key_object.user is not None
-
- # :KLUDGE: CHMiddleware does not receive the correct user when authenticating by api key.
- tag_queries(
- user_id=personal_api_key_object.user.pk,
- team_id=personal_api_key_object.user.current_team_id,
- access_method="personal_api_key",
- api_key_mask=personal_api_key_object.mask_value,
- api_key_label=personal_api_key_object.label,
- )
+ _, source = personal_api_key_with_source
+ span.set_attribute("auth.source", source)
- self.personal_api_key = personal_api_key_object
- self.personal_api_key_source = source
+ personal_api_key_object = self.validate_key(personal_api_key_with_source)
- return personal_api_key_object.user, None
+ now = timezone.now()
+ key_last_used_at = personal_api_key_object.last_used_at
+ # Only updating last_used_at if the hour's changed
+ # This is to avoid excessive UPDATE queries, while still presenting accurate (down to the hour) info in the UI
+ if key_last_used_at is None or (now - key_last_used_at > timedelta(hours=1)):
+ personal_api_key_object.last_used_at = now
+ personal_api_key_object.save(update_fields=["last_used_at"])
+ assert personal_api_key_object.user is not None
+
+ # :KLUDGE: CHMiddleware does not receive the correct user when authenticating by api key.
+ tag_queries(
+ user_id=personal_api_key_object.user.pk,
+ team_id=personal_api_key_object.user.current_team_id,
+ access_method="personal_api_key",
+ api_key_mask=personal_api_key_object.mask_value,
+ api_key_label=personal_api_key_object.label,
+ )
+
+ self.personal_api_key = personal_api_key_object
+ self.personal_api_key_source = source
+
+ return personal_api_key_object.user, None
@classmethod
def authenticate_header(cls, request) -> str:
@@ -405,24 +421,25 @@ class JwtAuthentication(authentication.BaseAuthentication):
@classmethod
def authenticate(cls, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
- if "authorization" in request.headers:
- authorization_match = re.match(rf"^Bearer\s+(\S.+)$", request.headers["authorization"])
- if authorization_match:
- try:
- token = authorization_match.group(1).strip()
- info = decode_jwt(token, PosthogJwtAudience.IMPERSONATED_USER)
- user = User.objects.get(pk=info["id"])
- return (user, None)
- except jwt.DecodeError:
- # If it doesn't look like a JWT then we allow the PersonalAPIKeyAuthentication to have a go
+ with tracer.start_as_current_span("posthog.auth.jwt"):
+ if "authorization" in request.headers:
+ authorization_match = re.match(rf"^Bearer\s+(\S.+)$", request.headers["authorization"])
+ if authorization_match:
+ try:
+ token = authorization_match.group(1).strip()
+ info = decode_jwt(token, PosthogJwtAudience.IMPERSONATED_USER)
+ user = User.objects.get(pk=info["id"])
+ return (user, None)
+ except jwt.DecodeError:
+ # If it doesn't look like a JWT then we allow the PersonalAPIKeyAuthentication to have a go
+ return None
+ except Exception:
+ raise AuthenticationFailed(detail=f"Token invalid.")
+ else:
+ # We don't throw so that the PersonalAPIKeyAuthentication can have a go
return None
- except Exception:
- raise AuthenticationFailed(detail=f"Token invalid.")
- else:
- # We don't throw so that the PersonalAPIKeyAuthentication can have a go
- return None
- return None
+ return None
@classmethod
def authenticate_header(cls, request) -> str:
@@ -590,31 +607,32 @@ class OAuthAccessTokenAuthentication(authentication.BaseAuthentication):
access_token: OAuthAccessToken
def authenticate(self, request: Union[HttpRequest, Request]) -> Optional[tuple[Any, None]]:
- authorization_token = self._extract_token(request)
+ with tracer.start_as_current_span("posthog.auth.oauth"):
+ authorization_token = self._extract_token(request)
- if not authorization_token:
- return None
+ if not authorization_token:
+ return None
- try:
- access_token = self._validate_token(authorization_token)
+ try:
+ access_token = self._validate_token(authorization_token)
- if not access_token:
- raise AuthenticationFailed(detail="Invalid access token.")
+ if not access_token:
+ raise AuthenticationFailed(detail="Invalid access token.")
- self.access_token = access_token
+ self.access_token = access_token
- tag_queries(
- user_id=access_token.user.pk,
- team_id=access_token.user.current_team_id,
- access_method="oauth",
- )
+ tag_queries(
+ user_id=access_token.user.pk,
+ team_id=access_token.user.current_team_id,
+ access_method="oauth",
+ )
- return access_token.user, None
+ return access_token.user, None
- except AuthenticationFailed:
- raise
- except Exception:
- raise AuthenticationFailed(detail="Invalid access token.")
+ except AuthenticationFailed:
+ raise
+ except Exception:
+ raise AuthenticationFailed(detail="Invalid access token.")
def _extract_token(self, request: Union[HttpRequest, Request]) -> Optional[str]:
if "authorization" in request.headers:
diff --git a/posthog/test/test_auth_spans.py b/posthog/test/test_auth_spans.py
new file mode 100644
index 000000000000..3fd25f3b58d1
--- /dev/null
+++ b/posthog/test/test_auth_spans.py
@@ -0,0 +1,118 @@
+from posthog.test.base import BaseTest
+
+from opentelemetry import trace
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+from parameterized import parameterized
+from rest_framework.request import Request
+from rest_framework.test import APIRequestFactory
+
+from posthog.auth import JwtAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.models import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+
+def _install_in_memory_tracer(exporter: InMemorySpanExporter) -> trace.Tracer:
+ """Wire up an in-memory span exporter and rebind `posthog.auth.tracer` to use it.
+
+ Returns the prior module-level tracer so the caller can restore it.
+
+ The tracer is taken directly from a fresh `TracerProvider` rather than the global
+ one. We can't swap the global with `trace.set_tracer_provider()` because OTel's SDK
+ is "set once": when production code calls `initialize_otel()` at startup, any later
+ `set_tracer_provider` calls are silently dropped with a warning, so spans created via
+ `trace.get_tracer(...)` would still go to the production provider and our exporter
+ would see nothing. Going through the provider object directly bypasses the global.
+ """
+ import posthog.auth as auth_module
+
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+
+ previous_module_tracer = auth_module.tracer
+ auth_module.tracer = provider.get_tracer(auth_module.__name__)
+
+ return previous_module_tracer
+
+
+def _restore_tracer(previous_module_tracer: trace.Tracer) -> None:
+ import posthog.auth as auth_module
+
+ auth_module.tracer = previous_module_tracer
+
+
+class TestAuthSpans(BaseTest):
+ _exporter: InMemorySpanExporter
+ _previous_module_tracer: trace.Tracer
+
+ @classmethod
+ def setUpClass(cls):
+ super().setUpClass()
+ cls._exporter = InMemorySpanExporter()
+ cls._previous_module_tracer = _install_in_memory_tracer(cls._exporter)
+
+ @classmethod
+ def tearDownClass(cls):
+ _restore_tracer(cls._previous_module_tracer)
+ super().tearDownClass()
+
+ def setUp(self):
+ super().setUp()
+ self._exporter.clear()
+ self.factory = APIRequestFactory()
+
+ def _spans_named(self, name):
+ return [s for s in self._exporter.get_finished_spans() if s.name == name]
+
+ @parameterized.expand(
+ [
+ (
+ "personal_api_key_no_key",
+ lambda factory: factory.get("/api/users/@me/"),
+ lambda req: PersonalAPIKeyAuthentication().authenticate(req),
+ "posthog.auth.personal_api_key",
+ ),
+ (
+ "jwt_no_authorization_header",
+ lambda factory: factory.get("/api/users/@me/"),
+ lambda req: JwtAuthentication.authenticate(req),
+ "posthog.auth.jwt",
+ ),
+ (
+ "session_no_session",
+ lambda factory: Request(factory.get("/api/users/@me/")),
+ lambda req: SessionAuthentication().authenticate(req),
+ "posthog.auth.session",
+ ),
+ ]
+ )
+ def test_authenticate_emits_span(self, _name, build_request, call_authenticate, expected_span_name):
+ request = build_request(self.factory)
+ call_authenticate(request)
+
+ spans = self._spans_named(expected_span_name)
+ assert len(spans) == 1
+
+ def test_personal_api_key_span_records_source_and_hash_mode_on_match(self):
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user,
+ label="test",
+ secure_value=hash_key_value(token),
+ )
+ request = self.factory.get("/api/users/@me/", HTTP_AUTHORIZATION=f"Bearer {token}")
+
+ result = PersonalAPIKeyAuthentication().authenticate(request)
+ assert result is not None
+ user, _ = result
+ assert user == self.user
+
+ parent = self._spans_named("posthog.auth.personal_api_key")
+ assert len(parent) == 1
+ assert parent[0].attributes["auth.source"] == "header"
+
+ db_lookup = self._spans_named("posthog.auth.personal_api_key.db_lookup")
+ assert len(db_lookup) == 1
+ assert db_lookup[0].attributes["auth.hash_mode_used"] == "sha256"
+ assert db_lookup[0].attributes["auth.modes_tried"] == 1