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.

fix(oauth): name the missing oidc key instead of a 500 (#129826)

Rafael Audibertd4fa94bce74a
diff --git a/docs/published/handbook/engineering/oauth-development-guide.md b/docs/published/handbook/engineering/oauth-development-guide.md
index aa2a55757d04..b45df483b5a3 100644
--- a/docs/published/handbook/engineering/oauth-development-guide.md
+++ b/docs/published/handbook/engineering/oauth-development-guide.md
@@ -29,6 +29,10 @@ openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform PEM | \
# Add to .env as OIDC_RSA_PRIVATE_KEY="<generated_key>"
```
+Without this key, PostHog cannot create OAuth applications.
+Django's system checks print warning `posthog.W001` at startup.
+Client ID metadata document clients, dynamic client registration and toolbar sign-in get an OAuth `server_error` that names the missing setting.
+
### 2. Set Up Your Environment
First, generate demo data which includes a test OAuth application:
@@ -228,7 +232,7 @@ See [Client Types](#client-types) section for detailed explanation.
{
"access_token": "...",
"token_type": "Bearer",
- "expires_in": 36000,
+ "expires_in": 3600,
"refresh_token": "...",
"id_token": "...",
"scope": "openid experiment:read query:read",
@@ -237,6 +241,9 @@ See [Client Types](#client-types) section for detailed explanation.
}
```
+ An access token expires after 1 hour.
+ Before it expires, use the refresh token to get a new one.
+
## Available Scopes
OAuth supports all the same scopes as Personal API Keys. Each scope has a `read` and/or `write` action (e.g., `experiment:read`, `experiment:write`).
diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.py
index d078d92df9ad..22bf3ae5038f 100644
--- a/posthog/api/oauth/cimd.py
+++ b/posthog/api/oauth/cimd.py
@@ -37,6 +37,7 @@ from posthog.models.oauth import (
normalize_cimd_url,
revoke_application_sessions,
)
+from posthog.oauth_signing_key import OIDC_SIGNING_KEY_MISSING_MESSAGE, oidc_signing_key_configured
from posthog.ph_client import ph_scoped_capture
from posthog.rate_limit import IPThrottle
from posthog.scopes import OIDC_SCOPES, filter_self_registered_ceiling, filter_to_unprivileged_scopes
@@ -88,6 +89,17 @@ class CIMDValidationError(Exception):
pass
+class CIMDSigningKeyMissingError(CIMDValidationError):
+ """The instance cannot store any CIMD client, so the metadata document is not at fault.
+
+ Subclasses CIMDValidationError so every caller that already handles a rejected document also
+ handles this case without a 500. The /authorize path catches it first to answer server_error.
+ """
+
+ def __init__(self) -> None:
+ super().__init__(OIDC_SIGNING_KEY_MISSING_MESSAGE)
+
+
class CIMDBurstThrottle(IPThrottle):
"""Rate limit new CIMD application creation by IP - burst limit."""
@@ -1005,6 +1017,9 @@ def fetch_and_upsert_cimd_application(
that fails model validation a ``CIMDValidationError`` rather than a kept row, so nothing is
granted off metadata we could not store; see ``_update_cimd_application``.
"""
+ if not oidc_signing_key_configured():
+ raise CIMDSigningKeyMissingError()
+
# Refused before the fetch so that PostHog sends no request to the host.
if is_throwaway_host(url):
capture_ph_event(
diff --git a/posthog/api/oauth/dcr.py b/posthog/api/oauth/dcr.py
index e282f9e16e13..1bec2d04e82e 100644
--- a/posthog/api/oauth/dcr.py
+++ b/posthog/api/oauth/dcr.py
@@ -27,6 +27,7 @@ from rest_framework.views import APIView
from posthog.exceptions_capture import capture_exception
from posthog.models.oauth import OAuthApplication, TokenEndpointAuthMethod
+from posthog.oauth_signing_key import OIDC_SIGNING_KEY_MISSING_MESSAGE, oidc_signing_key_configured
from posthog.rate_limit import IPThrottle
from posthog.scopes import OIDC_SCOPES, filter_self_registered_ceiling
@@ -122,6 +123,12 @@ class DynamicClientRegistrationView(APIView):
throttle_classes = [DCRBurstThrottle, DCRSustainedThrottle]
def post(self, request: Request) -> Response:
+ if not oidc_signing_key_configured():
+ return Response(
+ {"error": "server_error", "error_description": OIDC_SIGNING_KEY_MISSING_MESSAGE},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
# Validate request
serializer = DCRRequestSerializer(data=request.data)
if not serializer.is_valid():
diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.py
index 7c3ddca12166..a7e7ebfdd427 100644
--- a/posthog/api/oauth/test_cimd.py
+++ b/posthog/api/oauth/test_cimd.py
@@ -1489,6 +1489,18 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):
response.json()["error_description"],
)
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_missing_signing_key_answers_server_error_naming_the_setting(self, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata())
+
+ with patch.object(oauth2_settings, "OIDC_RSA_PRIVATE_KEY", ""):
+ response = self.client.get(self._authorize_url(VALID_CIMD_URL))
+
+ self.assertEqual(response.status_code, 500)
+ self.assertEqual(response.json()["error"], "server_error")
+ self.assertIn("OIDC_RSA_PRIVATE_KEY", response.json()["error_description"])
+ self.assertFalse(OAuthApplication.objects.filter(client_id=VALID_CIMD_URL).exists())
+
@patch("posthog.api.oauth.cimd.requests.Session.get")
def test_fetch_failure_reason_hides_connection_details(self, mock_get, _url_mock):
mock_get.side_effect = requests.ConnectionError("Max retries exceeded (host='10.1.2.3')")
diff --git a/posthog/api/oauth/test_dcr.py b/posthog/api/oauth/test_dcr.py
index 3b9bfc429893..ee58b9703a40 100644
--- a/posthog/api/oauth/test_dcr.py
+++ b/posthog/api/oauth/test_dcr.py
@@ -5,6 +5,7 @@ from urllib.parse import parse_qs, urlparse
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from oauth2_provider.settings import oauth2_settings
from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIClient
@@ -43,6 +44,17 @@ class TestDynamicClientRegistration(APIBaseTest):
self.assertIsNone(app.organization)
self.assertIsNone(app.user)
+ def test_register_without_signing_key_answers_server_error_naming_the_setting(self):
+ with patch.object(oauth2_settings, "OIDC_RSA_PRIVATE_KEY", ""):
+ response = self.client.post(
+ "/oauth/register/", {"redirect_uris": ["https://example.com/callback"]}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
+ self.assertEqual(response.json()["error"], "server_error")
+ self.assertIn("OIDC_RSA_PRIVATE_KEY", response.json()["error_description"])
+ self.assertFalse(OAuthApplication.objects.filter(is_dcr_client=True).exists())
+
@mock_anti_ssrf_dns_lookup()
def test_register_full_client(self, _resolve):
response = self.client.post(
diff --git a/posthog/api/oauth/toolbar_service.py b/posthog/api/oauth/toolbar_service.py
index 8b15e835747a..0b9097131359 100644
--- a/posthog/api/oauth/toolbar_service.py
+++ b/posthog/api/oauth/toolbar_service.py
@@ -26,6 +26,7 @@ from posthog.api.utils import canonicalize_encoded_url, strip_url_userinfo, unpa
from posthog.models import Team, User
from posthog.models.oauth import OAuthApplication, is_loopback_host
from posthog.models.organization import Organization
+from posthog.oauth_signing_key import OIDC_SIGNING_KEY_MISSING_MESSAGE, oidc_signing_key_configured
logger = structlog.get_logger(__name__)
@@ -142,6 +143,11 @@ def normalize_and_validate_app_url(team: Team, app_url: str) -> str:
return app_url
+def _require_oidc_signing_key() -> None:
+ if not oidc_signing_key_configured():
+ raise ToolbarOAuthError("server_error", OIDC_SIGNING_KEY_MISSING_MESSAGE, 500)
+
+
def get_or_create_toolbar_oauth_application(user: User) -> OAuthApplication:
"""
Return the toolbar OAuth app for the user's organization.
@@ -169,6 +175,7 @@ def get_or_create_toolbar_oauth_application(user: User) -> OAuthApplication:
if existing:
if existing.redirect_uris != redirect_uri:
+ _require_oidc_signing_key()
existing.redirect_uris = redirect_uri
existing.save(update_fields=["redirect_uris"])
logger.info(
@@ -178,6 +185,7 @@ def get_or_create_toolbar_oauth_application(user: User) -> OAuthApplication:
)
return existing
+ _require_oidc_signing_key()
app = OAuthApplication.objects.create(
name=app_name,
user=user,
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 3654b41ac346..abd6ee699fe5 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -47,6 +47,7 @@ from posthog.api import id_jag
from posthog.api.oauth.cimd import (
CIMD_THROTTLE_CLASSES,
CIMDFetchError,
+ CIMDSigningKeyMissingError,
CIMDValidationError,
enqueue_cimd_refresh_if_stale,
get_or_create_cimd_application,
@@ -172,7 +173,9 @@ _OTHER_CLOUD_REGION_HOST = {"US": "https://eu.posthog.com", "EU": "https://us.po
# InvalidClientIdError doesn't carry the request, so this is how error_response learns the
# reason. validate_client_id resets it on every call, and error_response only uses it for the
# same client_id.
-_cimd_resolution_error: ContextVar[tuple[str, str] | None] = ContextVar("cimd_resolution_error", default=None)
+_cimd_resolution_error: ContextVar[tuple[str, CIMDFetchError | CIMDValidationError] | None] = ContextVar(
+ "cimd_resolution_error", default=None
+)
def unknown_client_id_description(client_id: str | None, cimd_error: str | None = None) -> str:
@@ -764,7 +767,7 @@ class OAuthValidator(OAuth2Validator):
return True
except (CIMDFetchError, CIMDValidationError) as e:
logger.warning("cimd_resolution_failed", client_id=client_id, error=str(e), cause=repr(e.__cause__))
- _cimd_resolution_error.set((client_id, str(e)))
+ _cimd_resolution_error.set((client_id, e))
return False
# Standard UUID lookup
@@ -2026,8 +2029,14 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
# only ever reaches the JSON body.
client_id = self.request.query_params.get("client_id")
failure = _cimd_resolution_error.get()
+ cimd_error = failure[1] if failure and failure[0] == client_id else None
+ if isinstance(cimd_error, CIMDSigningKeyMissingError):
+ return Response(
+ {"error": "server_error", "error_description": str(cimd_error)},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
oauthlib_error.description = unknown_client_id_description(
- client_id, cimd_error=failure[1] if failure and failure[0] == client_id else None
+ client_id, cimd_error=str(cimd_error) if cimd_error else None
)
redirect, error_response = super().error_response(error, **kwargs)
diff --git a/posthog/api/test/test_toolbar_oauth_primitives.py b/posthog/api/test/test_toolbar_oauth_primitives.py
index 2d23f56da054..2aab89c5b45d 100644
--- a/posthog/api/test/test_toolbar_oauth_primitives.py
+++ b/posthog/api/test/test_toolbar_oauth_primitives.py
@@ -10,6 +10,7 @@ from django.core.cache import cache
from django.test import SimpleTestCase, override_settings
import requests
+from oauth2_provider.settings import oauth2_settings
from parameterized import parameterized
from posthog.api.oauth.toolbar_service import (
@@ -85,6 +86,14 @@ class TestToolbarOAuthPrimitives(APIBaseTest):
get_or_create_toolbar_oauth_application(user=orphan)
assert cm.exception.code == "no_organization"
+ def test_get_or_create_without_signing_key_raises_server_error_naming_the_setting(self):
+ with patch.object(oauth2_settings, "OIDC_RSA_PRIVATE_KEY", ""):
+ with self.assertRaises(ToolbarOAuthError) as cm:
+ get_or_create_toolbar_oauth_application(user=self.user)
+ assert cm.exception.code == "server_error"
+ assert cm.exception.status_code == 500
+ assert "OIDC_RSA_PRIVATE_KEY" in cm.exception.detail
+
def test_callback_with_invalid_state_returns_error(self):
response = self.client.get("/toolbar_oauth/callback?code=test_code&state=invalid_state")
assert response.status_code >= 400
diff --git a/posthog/apps.py b/posthog/apps.py
index 214247cb798a..3f13298322a3 100644
--- a/posthog/apps.py
+++ b/posthog/apps.py
@@ -53,6 +53,7 @@ class PostHogConfig(AppConfig):
# shell) would lose them. They live in dedicated import-light modules — never wire
# ready() through an API module, even one that looks light today.
import posthog.storage.checks # noqa: F401, PLC0415
+ import posthog.oauth_signing_key # noqa: F401, PLC0415
import posthog.models.file_system.signal_handlers # noqa: F401, PLC0415
import posthog.caching.organization_serializer_cache # noqa: F401, PLC0415
import posthog.models.activity_logging.signal_handlers # noqa: F401, PLC0415
diff --git a/posthog/oauth_signing_key.py b/posthog/oauth_signing_key.py
new file mode 100644
index 000000000000..2ed16895159d
--- /dev/null
+++ b/posthog/oauth_signing_key.py
@@ -0,0 +1,31 @@
+from typing import Any
+
+from django.core.checks import CheckMessage, Warning, register
+
+from oauth2_provider.settings import oauth2_settings
+
+OIDC_SIGNING_KEY_MISSING_MESSAGE = (
+ "OAuth is not set up on this PostHog instance. "
+ "Ask the instance admin to set the OIDC_RSA_PRIVATE_KEY environment variable to an RSA private key in PEM format."
+)
+
+
+def oidc_signing_key_configured() -> bool:
+ # Every OAuth client PostHog creates (CIMD, DCR, toolbar) uses RS256, and OAuthApplication.clean()
+ # rejects RS256 without this key, so no client can be created or updated while it is unset.
+ return bool(oauth2_settings.OIDC_RSA_PRIVATE_KEY)
+
+
+@register()
+def check_oidc_signing_key(app_configs: Any, **kwargs: Any) -> list[CheckMessage]:
+ if oidc_signing_key_configured():
+ return []
+ return [
+ Warning(
+ "OIDC_RSA_PRIVATE_KEY is not set, so OAuth clients cannot be created. "
+ "MCP clients, dynamic client registration and toolbar sign-in fail with an OAuth server_error.",
+ hint="Set OIDC_RSA_PRIVATE_KEY to an RSA private key in PEM format, for example the output of "
+ "`openssl genrsa 2048`.",
+ id="posthog.W001",
+ )
+ ]