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.

chore(frontend): log why a page with a session cookie renders signed out (#124670)

Paul D'Ambra279c17c8f017
diff --git a/posthog/settings/logs.py b/posthog/settings/logs.py
index fc76f2bacb56..859088a3756a 100644
--- a/posthog/settings/logs.py
+++ b/posthog/settings/logs.py
@@ -190,6 +190,8 @@ LOGGING: dict[str, Any] = {
"posthog.warehouse_source_prewarm": {"level": "INFO", "handlers": ["console"], "propagate": False},
# Same clamp: the api query budget logs the team and balance behind every would-be 429 at INFO.
"posthog.api_queries_budget": {"level": "INFO", "handlers": ["console"], "propagate": False},
+ # Same clamp: the signed-out-with-session-cookie diagnostic in posthog/utils.py logs at INFO.
+ "posthog.utils": {"level": "INFO", "handlers": ["console"], "propagate": False},
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load": {
"level": "DEBUG",
"handlers": ["console"],
diff --git a/posthog/test/test_get_context_for_template.py b/posthog/test/test_get_context_for_template.py
index fa76880bbc81..14d21a049a9a 100644
--- a/posthog/test/test_get_context_for_template.py
+++ b/posthog/test/test_get_context_for_template.py
@@ -6,6 +6,7 @@ from unittest import mock
from unittest.mock import MagicMock
from django.conf import settings
+from django.contrib.auth import get_user
from django.contrib.auth.models import AnonymousUser
from django.contrib.sessions.middleware import SessionMiddleware
from django.http import HttpRequest, HttpResponse
@@ -18,6 +19,8 @@ from parameterized import parameterized
from posthog.api.tagged_item import set_tags_on_object
from posthog.frontend_views import app_context
from posthog.models import Team, User, UserHomeSettings
+from posthog.session.backend import SessionStore
+from posthog.session.models import Session
from posthog.stable_chunks import StableChunks
from posthog.templatetags.posthog_filters import TolerantJSONEncoder
from posthog.utils import (
@@ -27,6 +30,7 @@ from posthog.utils import (
feature_flag_bootstrap,
get_context_for_template,
get_persisted_feature_flags_for_app_context,
+ signed_out_session_reason,
)
from products.conversations.backend.services.identity import IDENTITY_CLAIM_MAX_AGE_SECONDS
@@ -153,6 +157,35 @@ class TestFeatureFlagBootstrap(SimpleTestCase):
get_all_flags.assert_not_called()
+class TestSignedOutSessionReason(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("no session cookie", False, False, {}, None),
+ ("a session the store did not return", True, False, {}, "session_not_found"),
+ ("a stored session that auth flushed", True, True, {}, "session_without_user"),
+ (
+ "a session that names a user who did not authenticate",
+ True,
+ True,
+ {"_auth_user_id": "1"},
+ "user_not_resolved",
+ ),
+ ]
+ )
+ def test_names_why_a_request_with_a_session_cookie_is_signed_out(
+ self, _name, has_cookie, store_found_row, session_data, expected
+ ):
+ request = RequestFactory().get("/login")
+ if has_cookie:
+ request.COOKIES[settings.SESSION_COOKIE_NAME] = "a-session-key"
+ session = SessionStore()
+ session.__dict__["_session_cache"] = session_data
+ session.loaded_row = Session() if store_found_row else None
+ request.session = session
+
+ assert signed_out_session_reason(request) == expected
+
+
class TestShouldDeferAppContext(SimpleTestCase):
@parameterized.expand(
[
@@ -184,6 +217,19 @@ class TestShouldDeferAppContext(SimpleTestCase):
class TestGetContextForTemplate(APIBaseTest):
+ def test_signed_out_session_reason_survives_auth_flushing_a_stale_session(self):
+ self.client.force_login(self.user)
+ session_key = self.client.session.session_key
+ assert session_key is not None
+ self.user.set_password("a-different-password-1234")
+ self.user.save()
+ request = RequestFactory().get("/")
+ request.COOKIES[settings.SESSION_COOKIE_NAME] = session_key
+ request.session = SessionStore(session_key)
+
+ assert get_user(request).is_anonymous
+ assert signed_out_session_reason(request) == "session_without_user"
+
def test_get_context_for_template(self):
with (
self.settings(STRIPE_PUBLIC_KEY=None, PERSISTED_FEATURE_FLAGS=["the_persisted_flags"]),
diff --git a/posthog/utils.py b/posthog/utils.py
index 77feb7a92425..7811f8518ec3 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -25,6 +25,7 @@ from zoneinfo import ZoneInfo
from django.apps import apps
from django.conf import settings
+from django.contrib.auth import SESSION_KEY
from django.core.cache import cache
from django.db import ProgrammingError, models
from django.db.models.functions import Coalesce
@@ -599,6 +600,21 @@ def flag_identity(
)
+def signed_out_session_reason(request: HttpRequest) -> Optional[str]:
+ """
+ Why a request that carries a session cookie is still signed out, or None without the cookie.
+ The app can find a user through the API straight after such a page renders, and nobody knows why yet.
+ """
+ if settings.SESSION_COOKIE_NAME not in request.COOKIES:
+ return None
+ if SESSION_KEY in request.session:
+ return "user_not_resolved"
+ # Auth flushes a session whose hash fails before this runs, so only the loaded row tells it apart from a miss.
+ if getattr(request.session, "loaded_row", None) is None:
+ return "session_not_found"
+ return "session_without_user"
+
+
@tracer.start_as_current_span("template.context")
def get_context_for_template(
template_name: str,
@@ -775,6 +791,9 @@ def _build_template_context(
# Only the SPA shell references these; other templates (exporter, layout, ...) load different bundles
if template_name == "index.html":
is_authenticated = bool(request.user and request.user.is_authenticated)
+ if not is_authenticated and (reason := signed_out_session_reason(request)):
+ # Never log the path or the cookie: both can carry a credential.
+ logger.info("signed_out_page_with_session_cookie", reason=reason)
context["preload_css_url"], context["preload_js_urls"], context["preload_font_url"] = _resolve_entry_assets(
is_authenticated
)