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): accept sign-in-only cimd scopes and name cimd failures (#126473)

Rafael Audibert3c7655d86fe0
diff --git a/docs/published/handbook/engineering/oauth-development-guide.md b/docs/published/handbook/engineering/oauth-development-guide.md
index fb62647757a6..aa2a55757d04 100644
--- a/docs/published/handbook/engineering/oauth-development-guide.md
+++ b/docs/published/handbook/engineering/oauth-development-guide.md
@@ -328,7 +328,7 @@ print(tokens)
PostHog's own public clients (hogli, the Visual Review Chrome extension, and internal tools) authenticate with client ID metadata documents (CIMD) rather than a registered application or dynamic client registration. Their documents live in the [posthog.com repo](https://github.com/PostHog/posthog.com) at `static/.well-known/oauth/<app>/client-metadata.json`, served at `https://posthog.com/.well-known/oauth/<app>/client-metadata.json`. That URL is the `client_id`, so one ID works on US, EU, and self-hosted.
-To add one, create a JSON file there with `client_id` set to its own URL. The CIMD fetcher follows no redirects, so the URL has to answer with a 200 directly. Put the scope ceiling in `com.posthog.scopes`. A new document is an unverified, not-first-party client until someone sets `is_verified` or `is_first_party` on its application in Django admin, in each region.
+To add one, create a JSON file there with `client_id` set to its own URL. The CIMD fetcher follows no redirects, so the URL has to answer with a 200 directly. Put the scope ceiling in `com.posthog.scopes`. A client that only signs people in can list only `openid`, `profile`, and `email`, and gets no resource scope. A new document is an unverified, not-first-party client until someone sets `is_verified` or `is_first_party` on its application in Django admin, in each region.
## Self-registered client logos
diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.py
index 32b61c151419..549a14580ea8 100644
--- a/posthog/api/oauth/cimd.py
+++ b/posthog/api/oauth/cimd.py
@@ -25,6 +25,7 @@ import structlog
import posthoganalytics
from celery import shared_task
from oauth2_provider.models import AbstractApplication
+from rest_framework import serializers
from rest_framework.throttling import SimpleRateThrottle
from posthog.exceptions_capture import capture_exception
@@ -37,11 +38,11 @@ from posthog.models.oauth import (
)
from posthog.ph_client import ph_scoped_capture
from posthog.rate_limit import IPThrottle
-from posthog.scopes import filter_to_unprivileged_scopes
+from posthog.scopes import OIDC_SCOPES, filter_self_registered_ceiling, filter_to_unprivileged_scopes
from posthog.security.pinned_requests import PinnedIPAdapter, select_pinned_ip
-from posthog.security.url_validation import is_url_allowed, validate_url_and_pin_ips
+from posthog.security.url_validation import UNRESOLVED_HOST_REASON, is_url_allowed, validate_url_and_pin_ips
-from .client_name import sanitize_client_name, validate_client_name
+from .client_name import sanitize_client_name, validate_cimd_client_name
from .logo_uri import usable_logo_uri
if TYPE_CHECKING:
@@ -141,6 +142,17 @@ CIMDMetadataDocument = TypedDict(
)
+def _public_block_reason(what: str, reason: str | None) -> str:
+ """The client-facing reason an SSRF check refused a client-controlled URL.
+
+ Never the raw reason: it can name the address a host resolved to, which would make
+ these errors an oracle for DNS answers inside our network.
+ """
+ if reason == UNRESOLVED_HOST_REASON:
+ return f"{what} host name does not resolve"
+ return f"{what} host is not a public internet address"
+
+
def validate_fetchable_https_url(
url: str | None, *, perform_dns_check: bool = False, what: str = "URL"
) -> tuple[bool, str | None]:
@@ -171,7 +183,7 @@ def validate_fetchable_https_url(
if perform_dns_check:
allowed, reason = is_url_allowed(url)
if not allowed:
- return False, f"URL blocked: {reason}"
+ return False, _public_block_reason(what, reason)
return True, None
@@ -271,7 +283,7 @@ def fetch_client_json_document(
# PinnedIPAdapter keeps the original hostname for SNI and certificate verification.
verdict = validate_url_and_pin_ips(url)
if not verdict.allowed:
- raise CIMDValidationError(f"URL blocked: {verdict.reason}")
+ raise CIMDValidationError(_public_block_reason(what, verdict.reason))
adapter = PinnedIPAdapter()
hostname = (urlparse(url).hostname or "").lower()
@@ -296,15 +308,21 @@ def fetch_client_json_document(
)
except requests.RequestException as e:
session.close()
- raise CIMDFetchError(f"Failed to fetch {what}: {e}") from e
+ # The exception text can carry the pinned IP and connection internals, so the client
+ # gets the kind of failure and the full exception stays on the chained cause.
+ if isinstance(e, requests.Timeout):
+ raise CIMDFetchError(f"{what} fetch timed out after {CIMD_FETCH_TIMEOUT_SECONDS} seconds") from e
+ if isinstance(e, requests.exceptions.SSLError):
+ raise CIMDFetchError(f"{what} fetch failed: the TLS certificate could not be verified") from e
+ if isinstance(e, requests.ConnectionError):
+ raise CIMDFetchError(f"{what} fetch failed: could not connect") from e
+ raise CIMDFetchError(f"{what} fetch failed") from e
try:
if response.is_redirect or response.is_permanent_redirect:
- raise CIMDFetchError(
- f"{what} endpoint returned redirect (HTTP {response.status_code}), redirects are not allowed"
- )
+ raise CIMDFetchError(f"{what} endpoint returned a redirect, and redirects are not allowed")
if response.status_code != 200:
- raise CIMDFetchError(f"{what} endpoint returned HTTP {response.status_code}")
+ raise CIMDFetchError(f"{what} endpoint did not return HTTP 200")
# Early reject if Content-Length exceeds limit
content_length = response.headers.get("Content-Length")
@@ -337,7 +355,7 @@ def fetch_client_json_document(
try:
parsed = json.loads(body)
except Exception as e:
- raise CIMDValidationError(f"Invalid JSON in {what}: {e}") from e
+ raise CIMDValidationError(f"{what} is not valid JSON") from e
if not isinstance(parsed, dict):
raise CIMDValidationError(f"{what} must be a JSON object")
@@ -358,7 +376,7 @@ def fetch_cimd_metadata(url: str) -> tuple[CIMDMetadataDocument, int]:
# client_id MUST match the URL (simple string comparison per spec)
if metadata.get("client_id") != url:
- raise CIMDValidationError(f"client_id in metadata ({metadata.get('client_id')!r}) does not match URL ({url!r})")
+ raise CIMDValidationError("client_id in the metadata document does not match the URL it was fetched from")
# redirect_uris required
redirect_uris = metadata.get("redirect_uris")
@@ -379,7 +397,7 @@ def fetch_cimd_metadata(url: str) -> tuple[CIMDMetadataDocument, int]:
# itself, so nothing secret has to be delivered out of band.
auth_method = metadata.get("token_endpoint_auth_method", "none")
if auth_method not in CIMD_SUPPORTED_AUTH_METHODS:
- raise CIMDValidationError(f"CIMD clients cannot use token_endpoint_auth_method '{auth_method}'")
+ raise CIMDValidationError("token_endpoint_auth_method must be 'none' or 'private_key_jwt' for a CIMD client")
jwks_uri = metadata.get("jwks_uri")
if auth_method == TokenEndpointAuthMethod.PRIVATE_KEY_JWT.value:
@@ -391,7 +409,7 @@ def fetch_cimd_metadata(url: str) -> tuple[CIMDMetadataDocument, int]:
raise CIMDValidationError("jwks_uri must be an https URL")
# A second client-controlled URL we will dereference, so it gets the same SSRF
# screening as the metadata document itself.
- jwks_allowed, jwks_error = validate_cimd_url(jwks_uri, perform_dns_check=True)
+ jwks_allowed, jwks_error = validate_cimd_url(jwks_uri, perform_dns_check=True, what="jwks_uri")
if not jwks_allowed:
raise CIMDValidationError(f"jwks_uri is not allowed: {jwks_error}")
elif jwks_uri is not None:
@@ -511,7 +529,8 @@ def _capture_verification_rejected(
def _resolve_scopes(metadata: CIMDMetadataDocument) -> list[str] | None:
"""Resolve the allow-listed `com.posthog.scopes` for an app, or None when the field
is absent so callers leave existing scopes untouched. A present field returns a
- (possibly empty) list, capped to grantable scopes by `filter_to_unprivileged_scopes`.
+ (possibly empty) list, capped to grantable scopes by `filter_self_registered_ceiling`. A list of
+ only OIDC identity scopes is a sign-in-only client and keeps them as its ceiling.
Raises CIMDValidationError when the field is present and non-empty but every entry is
non-grantable. An empty ceiling falls back to the broad UNPRIVILEGED_SCOPES default
@@ -527,11 +546,12 @@ def _resolve_scopes(metadata: CIMDMetadataDocument) -> list[str] | None:
raw_scopes: object = com_posthog.get("scopes")
if not isinstance(raw_scopes, list):
return None
- filtered = filter_to_unprivileged_scopes(raw_scopes)
+ filtered = filter_self_registered_ceiling(raw_scopes)
if raw_scopes and not filtered:
raise CIMDValidationError(
- "None of the declared com.posthog.scopes are available to self-registered clients. "
- "Remove the field to register with the default scope set."
+ "com.posthog.scopes has no scope a CIMD client can be granted. "
+ f"Use scopes from scopes_supported in the authorization server metadata, list only "
+ f"{', '.join(OIDC_SCOPES)} for a sign-in-only client, or remove the field to use the default scope set"
)
return filtered
@@ -626,11 +646,14 @@ def _create_cimd_application(
``allow_confidential`` is the caller's only say in whether a declared private_key_jwt is
honored on creation; see ``_resolve_client_authentication``.
"""
- client_name = metadata.get("client_name", "CIMD Client")
- try:
- validate_client_name(client_name)
- except Exception:
+ client_name = metadata.get("client_name")
+ if not isinstance(client_name, str) or not client_name:
client_name = "CIMD Client"
+ else:
+ try:
+ validate_cimd_client_name(client_name, url)
+ except serializers.ValidationError as e:
+ raise CIMDValidationError(f"client_name is not allowed: {' '.join(str(d) for d in e.detail)}") from e
# Escape the partner-controlled name so the stored value is HTML-safe in any sink.
client_name = sanitize_client_name(client_name)
@@ -639,6 +662,10 @@ def _create_cimd_application(
verification = _resolve_verification_token(metadata, url, capture_ph_event=capture_ph_event)
resolved_scopes = _resolve_scopes(metadata)
resolved_optional_scopes = _resolve_optional_scopes(metadata)
+ if resolved_optional_scopes and not any(":" in scope for scope in resolved_scopes or []):
+ raise CIMDValidationError(
+ "com.posthog.optional_scopes requires at least one resource scope in com.posthog.scopes"
+ )
client_type, jwks_uri = _resolve_client_authentication(metadata, allow_confidential=allow_confidential)
@@ -719,7 +746,7 @@ def _update_cimd_application(
client_name = metadata.get("client_name")
if client_name:
try:
- validate_client_name(client_name)
+ validate_cimd_client_name(client_name, app.client_id)
app.name = sanitize_client_name(client_name)
except Exception:
pass # Keep existing name if new one is invalid
@@ -916,7 +943,7 @@ def fetch_and_upsert_cimd_application(
},
)
return new_app
- except (IntegrityError, ValidationError):
+ except (IntegrityError, ValidationError) as e:
app = OAuthApplication.objects.filter(client_id=url).first()
if app:
logger.debug("cimd_app_race_resolved", url=url, app_id=str(app.pk))
@@ -924,6 +951,11 @@ def fetch_and_upsert_cimd_application(
# document, so the declaration in it still speaks for this client.
_register_partner_if_declared(app, metadata, register_provisioning=register_provisioning)
return app
+ if isinstance(e, ValidationError):
+ # Field names only: the messages can echo document values, and whoever calls
+ # /authorize chooses which URL PostHog fetches.
+ fields = sorted(getattr(e, "message_dict", {}) or {"document": []})
+ raise CIMDValidationError(f"Metadata document was rejected: invalid {', '.join(fields)}") from e
raise
finally:
cache.delete(fetch_lock)
diff --git a/posthog/api/oauth/client_name.py b/posthog/api/oauth/client_name.py
index 9116cfee57cf..265684a1debf 100644
--- a/posthog/api/oauth/client_name.py
+++ b/posthog/api/oauth/client_name.py
@@ -7,6 +7,9 @@ consent screen. Both ingestion paths (`dcr.py`, `cimd.py`) share these helpers.
"""
import re
+import posixpath
+import unicodedata
+from urllib.parse import unquote, urlparse
from django.utils.html import escape
@@ -38,6 +41,84 @@ def validate_client_name(value: str) -> None:
raise serializers.ValidationError(f"Client name cannot contain '{word}'")
+POSTHOG_OWNED_DOMAINS = ("posthog.com", "posthog.net", "posthog.dev")
+
+# Where customers control the response body on those domains: CDP webhook hosts, and the
+# `/public/` routes CDP serves, which some environments expose on the app host itself.
+CUSTOMER_CONTENT_HOST_LABELS = ("webhooks", "hooks")
+CUSTOMER_CONTENT_PATH_PREFIXES = ("/public/",)
+
+_NON_ALPHANUMERIC_RE = re.compile(r"[^a-z0-9]")
+
+# Letters from other scripts that render like a letter of "posthog". NFKD already folds accents,
+# full-width and mathematical forms, but not these, so "PоstHog" with a Cyrillic "о" would pass.
+_POSTHOG_LOOKALIKES = str.maketrans(
+ {
+ "0": "o",
+ "о": "o",
+ "ο": "o",
+ "օ": "o",
+ "ᴏ": "o",
+ "р": "p",
+ "ρ": "p",
+ "ᴘ": "p",
+ "ѕ": "s",
+ "ꜱ": "s",
+ "т": "t",
+ "τ": "t",
+ "ᴛ": "t",
+ "һ": "h",
+ "н": "h",
+ "η": "h",
+ "ʜ": "h",
+ "ɡ": "g",
+ "ԍ": "g",
+ "ɢ": "g",
+ }
+)
+
+
+def is_posthog_controlled_url(url: str) -> bool:
+ """Whether PostHog, not a customer, controls the document at `url`.
+
+ A suffix match on our domains plus a denylist of customer-content hosts and paths. A new
+ endpoint that serves customer-defined JSON on one of these domains must be added here.
+ """
+ parsed = urlparse(url)
+ host = (parsed.hostname or "").lower().rstrip(".")
+ if not any(host == domain or host.endswith(f".{domain}") for domain in POSTHOG_OWNED_DOMAINS):
+ return False
+ if host.split(".")[0] in CUSTOMER_CONTENT_HOST_LABELS:
+ return False
+ # Routers match paths case-insensitively and after decoding, so compare the same way.
+ path = posixpath.normpath("/" + unquote(parsed.path).lower().lstrip("/"))
+ return not any(f"{path}/".startswith(prefix) for prefix in CUSTOMER_CONTENT_PATH_PREFIXES)
+
+
+def _mentions_posthog(value: str) -> bool:
+ folded = unicodedata.normalize("NFKD", value).casefold()
+ folded = "".join(char for char in folded if not unicodedata.combining(char)).translate(_POSTHOG_LOOKALIKES)
+ return "posthog" in _NON_ALPHANUMERIC_RE.sub("", folded)
+
+
+def validate_cimd_client_name(value: str, client_id: str) -> None:
+ """Stricter than `validate_client_name`, for CIMD clients.
+
+ "PostHog" is blocked anywhere in the name, including split forms like "Post Hog" and
+ look-alike letters from other scripts. DCR keeps
+ the starts-with rule, because MCP clients name themselves after the server (for example
+ "Claude Code (posthog)").
+ """
+ # PostHog's own documents may use the name. The client_id is the URL PostHog fetched the
+ # document from, so its location is proven. The error doesn't mention this exemption.
+ if not is_posthog_controlled_url(client_id) and _mentions_posthog(value):
+ raise serializers.ValidationError("Client name cannot contain 'PostHog'")
+ lower_value = value.lower()
+ for word in BLOCKED_CLIENT_NAME_WORDS:
+ if word in lower_value:
+ raise serializers.ValidationError(f"Client name cannot contain '{word}'")
+
+
def sanitize_client_name(value: str) -> str:
"""HTML-escape an untrusted client name so it is safe to render in any sink.
diff --git a/posthog/api/oauth/dcr.py b/posthog/api/oauth/dcr.py
index 6b15c06a53f5..e282f9e16e13 100644
--- a/posthog/api/oauth/dcr.py
+++ b/posthog/api/oauth/dcr.py
@@ -28,7 +28,7 @@ from rest_framework.views import APIView
from posthog.exceptions_capture import capture_exception
from posthog.models.oauth import OAuthApplication, TokenEndpointAuthMethod
from posthog.rate_limit import IPThrottle
-from posthog.scopes import filter_to_unprivileged_scopes
+from posthog.scopes import OIDC_SCOPES, filter_self_registered_ceiling
from .client_name import sanitize_client_name, validate_client_name
from .logo_uri import MAX_LOGO_URI_LENGTH, usable_logo_uri
@@ -38,8 +38,8 @@ logger = structlog.get_logger(__name__)
def filter_dcr_scopes(scope: str) -> list[str]:
"""Parse an RFC 7591 space-delimited `scope` string into the deduped, allow-listed
- scopes a DCR client may register. See `filter_to_unprivileged_scopes` for the rule."""
- return filter_to_unprivileged_scopes(scope.split())
+ scopes a DCR client may register. See `filter_self_registered_ceiling` for the rule."""
+ return filter_self_registered_ceiling(scope.split())
class DCRBurstThrottle(IPThrottle):
@@ -162,7 +162,11 @@ class DynamicClientRegistrationView(APIView):
return Response(
{
"error": "invalid_client_metadata",
- "error_description": "None of the requested scopes are available to self-registered clients. Omit `scope` to register with the default scope set.",
+ "error_description": (
+ "None of the requested scopes can be granted to a self-registered client. Use scopes "
+ f"from scopes_supported in the authorization server metadata, request only {' '.join(OIDC_SCOPES)} "
+ "for a sign-in-only client, or omit `scope` to register with the default scope set."
+ ),
},
status=status.HTTP_400_BAD_REQUEST,
)
diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.py
index 0eeac38256d3..8c9c7605386a 100644
--- a/posthog/api/oauth/test_cimd.py
+++ b/posthog/api/oauth/test_cimd.py
@@ -38,6 +38,7 @@ from posthog.models import Organization
from posthog.models.oauth import (
OAuthApplication,
OAuthApplicationAccessLevel,
+ OAuthGrant,
TokenEndpointAuthMethod,
create_cimd_verification_token,
)
@@ -160,14 +161,19 @@ def test_validate_cimd_url_accepts_valid(_mock):
"mock_return,url,expected_error",
[
(
- (False, "Private IP address not allowed"),
- "https://10.0.0.1/metadata.json",
- "URL blocked: Private IP address not allowed",
+ (False, "Disallowed target IP: 10.0.0.1"),
+ "https://internal.example.com/metadata.json",
+ "CIMD client_id host is not a public internet address",
),
(
(False, "Local/metadata host"),
"https://169.254.169.254/metadata.json",
- "URL blocked: Local/metadata host",
+ "CIMD client_id host is not a public internet address",
+ ),
+ (
+ (False, "Could not resolve host"),
+ "https://missing.example.com/metadata.json",
+ "CIMD client_id host name does not resolve",
),
],
)
@@ -190,6 +196,51 @@ class TestFetchCimdMetadata(SimpleTestCase):
self.assertEqual(result["client_name"], "Test MCP Client")
self.assertEqual(ttl, 3600)
+ @parameterized.expand(
+ [
+ ("timeout", requests.ConnectTimeout("HTTPSConnectionPool(host='10.1.2.3', port=443)"), "timed out"),
+ ("tls", requests.exceptions.SSLError("certificate verify failed for 10.1.2.3"), "TLS certificate"),
+ ("connection", requests.ConnectionError("Max retries exceeded with url (10.1.2.3)"), "could not connect"),
+ ]
+ )
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_fetch_failure_names_the_kind_without_connection_details(self, _name, exc, expected, mock_get, _url_mock):
+ mock_get.side_effect = exc
+ with self.assertRaises(CIMDFetchError) as ctx:
+ fetch_cimd_metadata(VALID_CIMD_URL)
+ self.assertIn(expected, str(ctx.exception))
+ self.assertNotIn("10.1.2.3", str(ctx.exception))
+
+ # Patched in the body: a method-level patch of the class-patched resolver would lose to it.
+ def test_unresolvable_host_says_so(self, _url_mock):
+ with patch("posthog.security.url_validation.resolve_host_ips", return_value=set()):
+ with self.assertRaisesRegex(CIMDValidationError, "host name does not resolve"):
+ fetch_cimd_metadata(VALID_CIMD_URL)
+
+ def test_internal_address_is_refused_without_naming_it(self, _url_mock):
+ with patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("10.0.0.5")}):
+ with self.assertRaises(CIMDValidationError) as ctx:
+ fetch_cimd_metadata(VALID_CIMD_URL)
+ self.assertIn("not a public internet address", str(ctx.exception))
+ self.assertNotIn("10.0.0.5", str(ctx.exception))
+
+ # Whoever calls /authorize picks the URL PostHog fetches, so errors must not read back the response.
+ @parameterized.expand(
+ [
+ ("client_id_value", _make_metadata(client_id="https://secret-value.example.com/x.json"), 200),
+ ("auth_method_value", _make_metadata(token_endpoint_auth_method="secret-value"), 200),
+ ("status_code", None, 418),
+ ("redirect_status", None, 307),
+ ]
+ )
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_errors_do_not_echo_the_fetched_response(self, _name, metadata, status_code, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(metadata, status_code=status_code)
+ with self.assertRaises((CIMDValidationError, CIMDFetchError)) as ctx:
+ fetch_cimd_metadata(VALID_CIMD_URL)
+ self.assertNotIn("secret-value", str(ctx.exception))
+ self.assertNotIn(str(status_code), str(ctx.exception))
+
@patch("posthog.api.oauth.cimd.requests.Session.get")
def test_client_id_mismatch(self, mock_get, _url_mock):
metadata = _make_metadata(client_id="https://wrong.example.com/other.json")
@@ -240,7 +291,7 @@ class TestFetchCimdMetadata(SimpleTestCase):
mock_get.return_value = _mock_response(status_code=404)
with self.assertRaises(CIMDFetchError) as ctx:
fetch_cimd_metadata(VALID_CIMD_URL)
- self.assertIn("404", str(ctx.exception))
+ self.assertIn("did not return HTTP 200", str(ctx.exception))
@patch("posthog.api.oauth.cimd.requests.Session.get")
def test_timeout(self, mock_get, _url_mock):
@@ -256,7 +307,17 @@ class TestFetchCimdMetadata(SimpleTestCase):
mock_get.return_value = _mock_response(_make_metadata(token_endpoint_auth_method=auth_method))
with self.assertRaises(CIMDValidationError) as ctx:
fetch_cimd_metadata(VALID_CIMD_URL)
- self.assertIn(auth_method, str(ctx.exception))
+ self.assertNotIn(auth_method, str(ctx.exception))
+ self.assertIn("token_endpoint_auth_method must be", str(ctx.exception))
+
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_internal_jwks_uri_is_refused_without_naming_its_address(self, mock_get, _url_mock):
+ metadata = _make_metadata(token_endpoint_auth_method="private_key_jwt", jwks_uri=CIMD_JWKS_URI)
+ mock_get.return_value = _mock_response(metadata)
+ with patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(False, "Disallowed target IP: 10.9.8.7")):
+ with self.assertRaises(CIMDValidationError) as ctx:
+ fetch_cimd_metadata(VALID_CIMD_URL)
+ self.assertEqual(str(ctx.exception), "jwks_uri is not allowed: jwks_uri host is not a public internet address")
@parameterized.expand([("missing_jwks_uri", None), ("non_https_jwks_uri", "http://app.example.com/jwks.json")])
@patch("posthog.api.oauth.cimd.requests.Session.get")
@@ -441,15 +502,88 @@ class TestFetchAndUpsertCimdApplication(APIBaseTest):
real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))
+ @parameterized.expand(
+ [
+ ("posthog_prefix", "PostHog Helper"),
+ ("posthog_anywhere", "Claude for PostHog"),
+ ("posthog_split_by_space", "Acme Post Hog Sync"),
+ ("posthog_split_by_punctuation", "Acme post-hog sync"),
+ ("blocked_word", "Acme Verified Client"),
+ ]
+ )
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_disallowed_name_rejects_new_client(self, _name, client_name, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata(client_name=client_name), headers={})
+
+ with self.assertRaisesRegex(CIMDValidationError, "client_name is not allowed"):
+ fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ self.assertFalse(OAuthApplication.objects.filter(client_id=VALID_CIMD_URL).exists())
+
+ @parameterized.expand(
+ [
+ ("posthog_com_subdomain", "https://artifacts.posthog.com/oauth/client-metadata.json"),
+ ("posthog_com_apex", "https://posthog.com/.well-known/oauth/hogli/client-metadata.json"),
+ ("posthog_net", "https://tools.posthog.net/client-metadata.json"),
+ ("posthog_dev", "https://posthog.dev/client-metadata.json"),
+ ]
+ )
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_posthog_owned_domain_may_use_posthog_in_name(self, _name, url, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata(url=url, client_name="PostHog Artifacts"), headers={})
+
+ app = fetch_and_upsert_cimd_application(url)
+
+ assert app is not None
+ self.assertEqual(app.name, "PostHog Artifacts")
+
+ @parameterized.expand(
+ [
+ ("lookalike_domain", "https://evilposthog.com/client-metadata.json"),
+ ("posthog_as_subdomain_label", "https://posthog.com.example.com/client-metadata.json"),
+ ("customer_webhook_host", "https://webhooks.us.posthog.com/public/webhooks/abc123"),
+ ("customer_webhook_path_on_app_host", "https://app.dev.posthog.dev/public/webhooks/abc123"),
+ ]
+ )
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_customer_controlled_url_may_not_use_posthog_in_name(self, _name, url, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata(url=url, client_name="PostHog Artifacts"), headers={})
+
+ with self.assertRaisesRegex(CIMDValidationError, "client_name is not allowed"):
+ fetch_and_upsert_cimd_application(url)
+
@patch("posthog.api.oauth.cimd.requests.Session.get")
- def test_blocked_name_uses_default(self, mock_get, _url_mock):
- metadata = _make_metadata(client_name="PostHog Official Client")
+ def test_posthog_owned_domain_still_blocks_other_words(self, mock_get, _url_mock):
+ url = "https://artifacts.posthog.com/oauth/client-metadata.json"
+ mock_get.return_value = _mock_response(_make_metadata(url=url, client_name="PostHog Official"), headers={})
+
+ with self.assertRaisesRegex(CIMDValidationError, "official"):
+ fetch_and_upsert_cimd_application(url)
+
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_missing_name_uses_default(self, mock_get, _url_mock):
+ metadata = _make_metadata()
+ del metadata["client_name"]
mock_get.return_value = _mock_response(metadata, headers={})
app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
assert app is not None
self.assertEqual(app.name, "CIMD Client")
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_refresh_with_disallowed_name_keeps_existing_name(self, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata(), headers={})
+ created = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+ assert created is not None
+
+ real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))
+ mock_get.return_value = _mock_response(_make_metadata(client_name="Claude for PostHog"), headers={})
+ refreshed = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ assert refreshed is not None
+ self.assertEqual(refreshed.name, "Test MCP Client")
+
@patch("posthog.api.oauth.cimd.requests.Session.get")
def test_fetch_failure_propagates(self, mock_get, _url_mock):
mock_get.side_effect = requests.ConnectionError("DNS resolution failed")
@@ -1131,6 +1265,56 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):
# must point at the metadata document instead of suggesting the other cloud region.
self.assertIn("client metadata document", response.json()["error_description"])
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_rejected_document_names_the_reason(self, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata(client_name="Claude for PostHog"))
+
+ response = self.client.get(self._authorize_url(VALID_CIMD_URL))
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn(
+ "PostHog could not use the client metadata document at this client_id: client_name is not allowed",
+ response.json()["error_description"],
+ )
+
+ @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')")
+
+ response = self.client.get(self._authorize_url(VALID_CIMD_URL))
+
+ self.assertEqual(response.status_code, 400)
+ description = response.json()["error_description"]
+ self.assertIn("could not connect", description)
+ self.assertNotIn("10.1.2.3", description)
+
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_sign_in_only_client_gets_identity_scopes_but_no_resource_scope(self, mock_get, _url_mock):
+ metadata = _make_metadata(com_posthog={"scopes": ["openid", "profile", "email"]})
+ mock_get.return_value = _mock_response(metadata)
+ get_or_create_cimd_application(VALID_CIMD_URL)
+
+ consent = self.client.post(
+ "/oauth/authorize/",
+ {
+ "client_id": VALID_CIMD_URL,
+ "redirect_uri": "http://127.0.0.1:3000/callback",
+ "response_type": "code",
+ "code_challenge": self.code_challenge,
+ "code_challenge_method": "S256",
+ "allow": True,
+ "access_level": OAuthApplicationAccessLevel.ALL.value,
+ "scoped_organizations": [],
+ "scoped_teams": [],
+ "scope": "openid profile email insight:read",
+ },
+ )
+
+ self.assertEqual(consent.status_code, 200)
+ code = consent.json()["redirect_to"].split("code=")[1].split("&")[0]
+ granted = set(OAuthGrant.objects.get(code=code).scope.split())
+ self.assertEqual(granted, {"openid", "profile", "email"})
+
@patch("posthog.api.oauth.cimd.requests.Session.get")
def test_cimd_mismatched_redirect_uri_rejected(self, mock_get, _url_mock):
metadata = _make_metadata()
@@ -1479,6 +1663,42 @@ class TestCIMDComPostHogNamespace(APIBaseTest):
# A present, non-empty com.posthog.scopes that strips to nothing is rejected, not
# stored as [] (which would widen the app to the broad UNPRIVILEGED default via the
# empty-ceiling fallback). Mirrors DCR's all-stripped rejection; no app is created.
+ @parameterized.expand(
+ [
+ ("all_three", ["openid", "profile", "email"], ["openid", "profile", "email"]),
+ ("openid_only", ["openid"], ["openid"]),
+ ("deduped", ["openid", "email", "openid"], ["openid", "email"]),
+ ]
+ )
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_oidc_only_scopes_create_a_sign_in_only_ceiling(self, _name, declared, expected, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata(com_posthog={"scopes": declared}), headers={})
+
+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ assert app is not None
+ self.assertEqual(app.scopes, expected)
+
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_oidc_scopes_next_to_resource_scopes_are_dropped(self, mock_get, _url_mock):
+ metadata = _make_metadata(com_posthog={"scopes": ["openid", "email", "insight:read"]})
+ mock_get.return_value = _mock_response(metadata, headers={})
+
+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ assert app is not None
+ self.assertEqual(app.scopes, ["insight:read"])
+
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_optional_scopes_on_a_sign_in_only_ceiling_is_rejected_with_the_reason(self, mock_get, _url_mock):
+ metadata = _make_metadata(com_posthog={"scopes": ["openid"], "optional_scopes": ["insight:read"]})
+ mock_get.return_value = _mock_response(metadata, headers={})
+
+ with self.assertRaisesRegex(CIMDValidationError, "optional_scopes requires at least one resource scope"):
+ fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ self.assertFalse(OAuthApplication.objects.filter(client_id=VALID_CIMD_URL).exists())
+
@patch("posthog.api.oauth.cimd.requests.Session.get")
def test_all_non_grantable_scopes_on_creation_rejected(self, mock_get, _url_mock):
only_non_grantable = [*sorted(PRIVILEGED_SCOPES), "not_a_real_scope:write"]
@@ -1526,5 +1746,11 @@ class TestResolveScopes(SimpleTestCase):
self.assertEqual(resolved, ["insight:read"])
def test_all_non_grantable_raises(self) -> None:
- with self.assertRaises(CIMDValidationError):
+ with self.assertRaises(CIMDValidationError) as ctx:
_resolve_scopes({"com.posthog": {"scopes": ["llm_gateway:read", "not_a_real_scope:write"]}})
+ self.assertNotIn("llm_gateway:read", str(ctx.exception))
+
+ def test_oidc_only_is_a_sign_in_only_ceiling(self) -> None:
+ self.assertEqual(
+ _resolve_scopes({"com.posthog": {"scopes": ["openid", "profile", "email"]}}), ["openid", "profile", "email"]
+ )
diff --git a/posthog/api/oauth/test_client_name.py b/posthog/api/oauth/test_client_name.py
index 66d6df83815a..e223c0f6ba37 100644
--- a/posthog/api/oauth/test_client_name.py
+++ b/posthog/api/oauth/test_client_name.py
@@ -3,7 +3,13 @@ from unittest import TestCase
from parameterized import parameterized
from rest_framework import serializers
-from posthog.api.oauth.client_name import CLIENT_NAME_MAX_LENGTH, sanitize_client_name, validate_client_name
+from posthog.api.oauth.client_name import (
+ CLIENT_NAME_MAX_LENGTH,
+ is_posthog_controlled_url,
+ sanitize_client_name,
+ validate_cimd_client_name,
+ validate_client_name,
+)
class TestSanitizeClientName(TestCase):
@@ -61,3 +67,66 @@ class TestValidateClientName(TestCase):
)
def test_accepts_valid_names(self, _name, value):
validate_client_name(value)
+
+
+class TestValidateCimdClientName(TestCase):
+ @parameterized.expand(
+ [
+ ("prefix", "PostHog Client"),
+ ("suffix", "Claude for PostHog"),
+ ("middle_lowercase", "acme posthog sync"),
+ ("split_by_space", "Acme Post Hog"),
+ ("split_by_punctuation", "Acme Post-Hog"),
+ ("cyrillic_o", "P\u043estHog Analytics"),
+ ("greek_omicron_and_cyrillic_es", "Po\u0455tH\u03bfg"),
+ ("cyrillic_capitals", "\u0420OST\u041dOG"),
+ ("digit_zero", "P0stHog"),
+ ("accented", "P\u00f6stH\u00f6g"),
+ ("full_width", "\uff30\uff4f\uff53\uff54\uff28\uff4f\uff47"),
+ ("zero_width_space", "Post\u200bHog"),
+ ("blocked_word", "Acme Trusted Client"),
+ ]
+ )
+ def test_rejects_on_other_domains(self, _name, value):
+ with self.assertRaises(serializers.ValidationError):
+ validate_cimd_client_name(value, "https://app.example.com/client.json")
+
+ def test_error_does_not_reveal_the_exemption(self):
+ with self.assertRaises(serializers.ValidationError) as ctx:
+ validate_cimd_client_name("Claude for PostHog", "https://app.example.com/client.json")
+ self.assertEqual(ctx.exception.detail, ["Client name cannot contain 'PostHog'"])
+
+ def test_allows_posthog_on_posthog_controlled_urls(self):
+ validate_cimd_client_name("PostHog Artifacts", "https://artifacts.posthog.com/oauth/client-metadata.json")
+
+ def test_blocked_words_apply_on_posthog_controlled_urls(self):
+ with self.assertRaises(serializers.ValidationError):
+ validate_cimd_client_name("PostHog Official", "https://posthog.com/client.json")
+
+ def test_accepts_unrelated_name(self):
+ validate_cimd_client_name("Acme Analytics", "https://app.example.com/client.json")
+
+
+class TestIsPosthogControlledUrl(TestCase):
+ @parameterized.expand(
+ [
+ ("apex", "https://posthog.com/.well-known/oauth/hogli/client-metadata.json", True),
+ ("subdomain", "https://artifacts.posthog.com/oauth/client-metadata.json", True),
+ ("uppercase_and_trailing_dot", "https://Artifacts.PostHog.com./client.json", True),
+ ("net", "https://tools.posthog.net/client.json", True),
+ ("dev", "https://posthog.dev/client.json", True),
+ ("webhooks_host", "https://webhooks.us.posthog.com/public/webhooks/abc", False),
+ ("webhooks_host_other_path", "https://webhooks.eu.posthog.com/client.json", False),
+ ("hooks_host", "https://hooks.posthog.com/client.json", False),
+ ("public_path_on_app_host", "https://app.dev.posthog.dev/public/webhooks/abc", False),
+ ("public_path_mixed_case", "https://us.posthog.com/Public/webhooks/abc", False),
+ ("public_path_percent_encoded", "https://us.posthog.com/%70ublic/webhooks/abc", False),
+ ("public_path_after_dot_segments", "https://us.posthog.com/a/../public/webhooks/abc", False),
+ ("public_path_double_slash", "https://us.posthog.com//public/webhooks/abc", False),
+ ("lookalike", "https://evilposthog.com/client.json", False),
+ ("posthog_label_on_other_domain", "https://posthog.com.example.com/client.json", False),
+ ("other_tld", "https://posthog.io/client.json", False),
+ ]
+ )
+ def test_url(self, _name, url, expected):
+ self.assertEqual(is_posthog_controlled_url(url), expected)
diff --git a/posthog/api/oauth/test_dcr.py b/posthog/api/oauth/test_dcr.py
index f6a6eda23661..84c308ce9ce6 100644
--- a/posthog/api/oauth/test_dcr.py
+++ b/posthog/api/oauth/test_dcr.py
@@ -432,6 +432,13 @@ class TestDynamicClientRegistration(APIBaseTest):
"experiment:read",
),
("strips_internal", "experiment:read signal_scout_internal:write", ["experiment:read"], "experiment:read"),
+ (
+ "oidc_only_keeps_identity_ceiling",
+ "openid profile email",
+ ["openid", "profile", "email"],
+ "openid profile email",
+ ),
+ ("oidc_next_to_resource_is_dropped", "openid experiment:read", ["experiment:read"], "experiment:read"),
(
"strips_hidden",
"experiment:read wizard_session:write",
@@ -541,6 +548,14 @@ class TestDynamicClientRegistration(APIBaseTest):
self.assertNotIn("error=invalid_scope", redirect_to)
self.assertIn("code=", redirect_to)
+ def test_sign_in_only_dcr_client_gets_no_resource_scope_at_authorize(self):
+ client_id = self._register_dcr_client(scope="openid profile email")
+ response = self._authorize_consent_post(client_id, "openid profile email experiment:read")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ code = parse_qs(urlparse(response.json()["redirect_to"]).query)["code"][0]
+ granted = set(OAuthGrant.objects.get(code=code).scope.split())
+ self.assertEqual(granted, {"openid", "profile", "email"})
+
def test_no_scope_dcr_client_does_not_obtain_privileged_scope_at_authorize(self):
"""The broad default excludes PRIVILEGED_SCOPES, so a no-ceiling DCR
client cannot obtain llm_gateway access at /authorize. It is dropped from
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index f95c009b5df3..a2be00da093f 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -3,6 +3,7 @@ import uuid
import hashlib
import calendar
from collections.abc import Iterable
+from contextvars import ContextVar
from datetime import datetime, timedelta
from functools import wraps
from typing import Any, TypedDict, cast
@@ -157,8 +158,14 @@ def get_region_info() -> dict | None:
# The host the other PostHog Cloud region answers on, so an unknown client_id can name it.
_OTHER_CLOUD_REGION_HOST = {"US": "https://eu.posthog.com", "EU": "https://us.posthog.com"}
+# Why the last CIMD client_id failed to resolve, as (client_id, reason). oauthlib's
+# 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)
-def unknown_client_id_description(client_id: str | None) -> str:
+
+def unknown_client_id_description(client_id: str | None, cimd_error: str | None = None) -> str:
"""Describe an unknown `client_id` so the client can act on the 400.
An OAuth application exists in one region only, and a request sent to the other
@@ -166,9 +173,15 @@ def unknown_client_id_description(client_id: str | None) -> str:
region is what makes that case recognizable.
A CIMD client_id is a metadata URL resolved on demand rather than a registration
- we hold, so it fails for a different reason and gets a different description.
+ we hold, so it fails for a different reason and gets a different description. When
+ /authorize knows why the document failed, `cimd_error` names it. CIMD errors are
+ written to be shown to the client: they describe the client's own public document.
"""
if is_cimd_client_id(client_id):
+ if cimd_error:
+ return (
+ f"PostHog could not use the client metadata document at this client_id: {cimd_error[:500].rstrip('.')}."
+ )
return (
"PostHog could not read the client metadata document at this client_id. "
"Check that the URL is reachable over HTTPS and returns valid client metadata."
@@ -722,13 +735,15 @@ class OAuthValidator(OAuth2Validator):
"""
# CIMD URLs always go through get_or_create to ensure metadata refresh
+ _cimd_resolution_error.set(None)
if is_cimd_client_id(client_id):
try:
app = get_or_create_cimd_application(client_id)
request.client = app
return True
except (CIMDFetchError, CIMDValidationError) as e:
- logger.warning("cimd_resolution_failed", client_id=client_id, error=str(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)))
return False
# Standard UUID lookup
@@ -1946,7 +1961,11 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
if isinstance(oauthlib_error, InvalidClientIdError):
# An unknown client_id is fatal, so DOT never redirects it and this description
# only ever reaches the JSON body.
- oauthlib_error.description = unknown_client_id_description(self.request.query_params.get("client_id"))
+ client_id = self.request.query_params.get("client_id")
+ failure = _cimd_resolution_error.get()
+ oauthlib_error.description = unknown_client_id_description(
+ client_id, cimd_error=failure[1] if failure and failure[0] == client_id else None
+ )
redirect, error_response = super().error_response(error, **kwargs)
diff --git a/posthog/scopes.py b/posthog/scopes.py
index aa63052355a7..806d308086be 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -400,6 +400,24 @@ def filter_to_unprivileged_scopes(scopes: Iterable[object]) -> list[str]:
return result
+def filter_self_registered_ceiling(scopes: Iterable[object]) -> list[str]:
+ """The scope ceiling a self-registering client (DCR or CIMD) gets from the scopes it declares.
+
+ Resource scopes go through `filter_to_unprivileged_scopes`. The OIDC identity scopes are
+ granted on top of every ceiling, so a list that also names resource scopes drops them. A list
+ of only identity scopes is a sign-in-only client and keeps them as its ceiling: a non-empty
+ ceiling is an exhaustive allow-list, so the client can't get any resource scope. Dropping them
+ would leave the ceiling empty, which callers reject or widen to the `UNPRIVILEGED_SCOPES` default.
+
+ Returns `[]` only when nothing in `scopes` is grantable.
+ """
+ declared = list(scopes)
+ resource_scopes = filter_to_unprivileged_scopes(declared)
+ if resource_scopes:
+ return resource_scopes
+ return list(dict.fromkeys(token for token in declared if isinstance(token, str) and token in OIDC_SCOPES))
+
+
# Sentinel element in `OAuthApplication.scopes` meaning "the `UNPRIVILEGED_SCOPES`
# default *plus* the other listed scopes" — lets an app ride the broad default and add
# a few explicit (e.g. privileged) extras without enumerating the whole set, and keeps
diff --git a/posthog/test/test_scopes.py b/posthog/test/test_scopes.py
index 8255de5921ac..9e4be24839a3 100644
--- a/posthog/test/test_scopes.py
+++ b/posthog/test/test_scopes.py
@@ -21,6 +21,7 @@ from posthog.scopes import (
clamp_scopes_to_ceiling,
downgrade_scopes_to_read_only,
effective_ceiling,
+ filter_self_registered_ceiling,
filter_to_unprivileged_scopes,
get_oauth_scopes_supported,
get_scope_descriptions,
@@ -513,6 +514,27 @@ class TestFilterToUnprivilegedScopes(SimpleTestCase):
]
+class TestFilterSelfRegisteredCeiling(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("oidc_only_kept", ["openid", "profile", "email"], ["openid", "profile", "email"]),
+ ("oidc_only_deduped", ["email", "openid", "email"], ["email", "openid"]),
+ ("oidc_dropped_next_to_resource", ["openid", "insight:read"], ["insight:read"]),
+ ("oidc_kept_when_resources_all_dropped", ["openid", "llm_gateway:read"], ["openid"]),
+ ("introspection_is_not_an_identity_scope", ["introspection"], []),
+ ("nothing_grantable", ["llm_gateway:read", "garbage"], []),
+ ("empty_in_empty_out", [], []),
+ ]
+ )
+ def test_resolution(self, _name: str, given: list[str], expected: list[str]) -> None:
+ assert filter_self_registered_ceiling(given) == expected
+
+ def test_oidc_only_ceiling_grants_no_resource_scope(self) -> None:
+ ceiling = filter_self_registered_ceiling(["openid", "profile", "email"])
+ assert effective_ceiling(ceiling) == frozenset({"openid", "profile", "email"})
+ assert clamp_scopes_to_ceiling({"openid", "email", "insight:read"}, ceiling) == ["email", "openid"]
+
+
class TestProjectSecretAPIKeyScopeParity(SimpleTestCase):
# The settings scope picker builds its checkboxes from the frontend copy of this list,
# so a scope added on the backend alone is allowed by the API but has no UI to grant it.