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): HTML-escape untrusted client names at ingestion (#66897)

Rafael Audibert10aed52d08aa
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4fc303c51128..e31574902440 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4845,9 +4845,9 @@ snapshots:
scenes-app-customer-analytics-accounts--row-expanded-empty--light:
hash: v1.k794b7964.904bd5b939f99d43408ae3a8a814a3c299bd57bf13a0fd1d98ff6033fd66e343.K1Z16ICEF6-O9kIej8kGnYyarloq2oZH5rdtmx-8Hu0
scenes-app-customer-analytics-accounts--row-expanded-links-disabled--dark:
- hash: v1.k794b7964.dbe806f797399ea2451bdf08b2a0bc1a413ea4d65e1a244e859a6f17a330005d.i8IfnQ9ONhYyodW5HPR_2GSN7q1dcVA3cPUtXyNi_ro
+ hash: v1.k794b7964.d2efe33a50fa0f2e076fdc40334333e45ec2344b58b9c4d3df6cc5cc0bb073f0.LRIIMBC3WY2eC_ZVjlb4n7UfX_XbsMH1lCn4pWnUOJE
scenes-app-customer-analytics-accounts--row-expanded-links-disabled--light:
- hash: v1.k794b7964.f82e5d3d3f153d31ba1ef5b668ebb5ab8aab000fe4acb42252f89e9f56a838bc.GkNSIp0tMmvNDlRasel6bRQBgice_VcLKHISDWHGnnU
+ hash: v1.k794b7964.5eb51441627289ebe42cecd9311d5a1f5b625a1d37ddd8daa3138e24f46ee90f.2YABFnnFmj-6o1atsqYxtPAru8WdKTRJZ8ubbnNzgU4
scenes-app-customer-analytics-accounts--row-expanded-usage-not-found--dark:
hash: v1.k794b7964.53af994a2a4dfb2f883e27ed73be8d55e1177b97f5c8b622708dfcdbe5f33d2a.A7AJRK9hY-yytJMNPghuLYtOJIoj0VBJidseMubwZWs
scenes-app-customer-analytics-accounts--row-expanded-usage-not-found--light:
diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.tsx
index 16c4794e9b9f..bff3d02bd4a2 100644
--- a/frontend/src/scenes/oauth/OAuthAuthorize.tsx
+++ b/frontend/src/scenes/oauth/OAuthAuthorize.tsx
@@ -1,3 +1,4 @@
+import { decode } from 'he'
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
import { useMemo, useState } from 'react'
@@ -226,12 +227,17 @@ export const OAuthAuthorize = (): JSX.Element => {
)
}
+ // The name is HTML-escaped at ingestion (see posthog/api/oauth/client_name.py). Decode it
+ // back to plain text so React's own output-escaping renders it correctly instead of showing
+ // literal entities like "&".
+ const appName = decode(oauthApplication.name)
+
if (authorizationComplete) {
- return <OAuthAuthorizeSuccess appName={oauthApplication.name} />
+ return <OAuthAuthorizeSuccess appName={appName} />
}
if (isRedirecting) {
- return <OAuthAuthorizeRedirecting appName={oauthApplication.name} redirectUrl={redirectUrl} />
+ return <OAuthAuthorizeRedirecting appName={appName} redirectUrl={redirectUrl} />
}
return (
@@ -242,7 +248,7 @@ export const OAuthAuthorize = (): JSX.Element => {
<div className="w-16 h-16 mx-auto mb-3 rounded-full border border-border bg-bg-light p-3 flex items-center justify-center">
<img
src={oauthApplication.logo_uri}
- alt={`${oauthApplication.name} logo`}
+ alt={`${appName} logo`}
className="w-full h-full object-contain"
referrerPolicy="no-referrer"
onError={(e) => {
@@ -257,11 +263,9 @@ export const OAuthAuthorize = (): JSX.Element => {
</div>
)}
<h2 className="text-xl sm:text-2xl font-semibold">
- Authorize <strong>{oauthApplication.name}</strong>
+ Authorize <strong>{appName}</strong>
</h2>
- <p className="text-muted mt-2 text-sm sm:text-base">
- {oauthApplication.name} is requesting access to your data.
- </p>
+ <p className="text-muted mt-2 text-sm sm:text-base">{appName} is requesting access to your data.</p>
</div>
{isImpersonated && (
@@ -424,9 +428,7 @@ export const OAuthAuthorize = (): JSX.Element => {
}
label={row.description}
disabledReason={
- row.required
- ? `Required by ${oauthApplication.name}`
- : undefined
+ row.required ? `Required by ${appName}` : undefined
}
/>
))}
@@ -442,8 +444,8 @@ export const OAuthAuthorize = (): JSX.Element => {
Once you authorize, you will be redirected to <strong>{redirectDomain}</strong>
</p>
<p>
- The developer of {oauthApplication.name}'s privacy policy and terms of service apply
- to this application
+ The developer of {appName}'s privacy policy and terms of service apply to this
+ application
</p>
</div>
)}
@@ -483,7 +485,7 @@ export const OAuthAuthorize = (): JSX.Element => {
}
onClick={() => submitOauthAuthorization()}
>
- Authorize {oauthApplication?.name}
+ Authorize {appName}
</LemonButton>
</div>
</div>
diff --git a/frontend/src/scenes/settings/organization/OAuthApps.tsx b/frontend/src/scenes/settings/organization/OAuthApps.tsx
index 3c12c91ba1c2..07202f6f496f 100644
--- a/frontend/src/scenes/settings/organization/OAuthApps.tsx
+++ b/frontend/src/scenes/settings/organization/OAuthApps.tsx
@@ -1,3 +1,4 @@
+import { decode } from 'he'
import { useValues } from 'kea'
import { IconCopy } from '@posthog/icons'
@@ -45,7 +46,7 @@ export function OAuthApps(): JSX.Element {
key: 'name',
render: (_, app: OrganizationOAuthApplicationApi) => (
<div className="flex items-center gap-2">
- <span className="font-semibold">{app.name}</span>
+ <span className="font-semibold">{decode(app.name ?? '')}</span>
{app.is_verified && (
<LemonTag type="success" size="small">
Verified
diff --git a/frontend/src/scenes/settings/user/ConnectedApps.tsx b/frontend/src/scenes/settings/user/ConnectedApps.tsx
index 51e39bd85413..9ee02f4a7e30 100644
--- a/frontend/src/scenes/settings/user/ConnectedApps.tsx
+++ b/frontend/src/scenes/settings/user/ConnectedApps.tsx
@@ -1,3 +1,4 @@
+import { decode } from 'he'
import { useActions, useValues } from 'kea'
import { useState } from 'react'
@@ -51,9 +52,12 @@ export function ConnectedApps(): JSX.Element {
const { revokeApp } = useActions(connectedAppsLogic)
const handleRevoke = (app: ConnectedApp): void => {
+ // Name is HTML-escaped at ingestion; decode for display (see posthog/api/oauth/client_name.py).
+ const name = decode(app.name)
+
LemonDialog.open({
- title: `Revoke access for ${app.name}?`,
- description: `This will revoke all tokens and permissions granted to ${app.name}. The app will no longer be able to access your PostHog account. You can re-authorize it at any time through the application's own interface.`,
+ title: `Revoke access for ${name}?`,
+ description: `This will revoke all tokens and permissions granted to ${name}. The app will no longer be able to access your PostHog account. You can re-authorize it at any time through the application's own interface.`,
primaryButton: {
children: 'Revoke',
status: 'danger',
@@ -79,16 +83,16 @@ export function ConnectedApps(): JSX.Element {
<div className="w-8 h-8 shrink-0 rounded bg-bg-light border flex items-center justify-center p-1">
<img
src={app.logo_uri}
- alt={`${app.name} logo`}
+ alt={`${decode(app.name)} logo`}
className="w-full h-full object-contain"
/>
</div>
) : (
<div className="w-8 h-8 shrink-0 rounded bg-border flex items-center justify-center text-sm font-bold text-muted">
- {app.name.charAt(0).toUpperCase()}
+ {decode(app.name).charAt(0).toUpperCase()}
</div>
)}
- <span className="font-medium">{app.name}</span>
+ <span className="font-medium">{decode(app.name)}</span>
{app.is_first_party ? (
<LemonTag type="highlight" size="small">
PostHog
diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.py
index e94c9a6f7f4b..7e1b87ee0438 100644
--- a/posthog/api/oauth/cimd.py
+++ b/posthog/api/oauth/cimd.py
@@ -38,7 +38,7 @@ from posthog.rate_limit import IPThrottle
from posthog.scopes import filter_to_unprivileged_scopes
from posthog.security.url_validation import is_url_allowed
-from .dcr import validate_client_name
+from .client_name import sanitize_client_name, validate_client_name
logger = structlog.get_logger(__name__)
@@ -395,6 +395,8 @@ def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthA
validate_client_name(client_name)
except Exception:
client_name = "CIMD Client"
+ # Escape the partner-controlled name so the stored value is HTML-safe in any sink.
+ client_name = sanitize_client_name(client_name)
redirect_uris = " ".join(metadata.get("redirect_uris", []))
logo_uri = metadata.get("logo_uri") or None
@@ -449,7 +451,7 @@ def _update_cimd_application(app: OAuthApplication, metadata: CIMDMetadataDocume
if client_name:
try:
validate_client_name(client_name)
- app.name = client_name
+ app.name = sanitize_client_name(client_name)
except Exception:
pass # Keep existing name if new one is invalid
diff --git a/posthog/api/oauth/client_name.py b/posthog/api/oauth/client_name.py
new file mode 100644
index 000000000000..9116cfee57cf
--- /dev/null
+++ b/posthog/api/oauth/client_name.py
@@ -0,0 +1,53 @@
+"""
+Shared validation and HTML-safety helpers for OAuth client names.
+
+Client names are untrusted input — they arrive from an unauthenticated DCR request body
+(RFC 7591) or a partner-controlled CIMD metadata document — and surface on the OAuth
+consent screen. Both ingestion paths (`dcr.py`, `cimd.py`) share these helpers.
+"""
+
+import re
+
+from django.utils.html import escape
+
+from rest_framework import serializers
+
+# Blocked words in client names to prevent confusion attacks
+# These prevent malicious apps from impersonating official PostHog applications
+BLOCKED_CLIENT_NAME_PREFIXES = ["posthog"] # Block names starting with these
+BLOCKED_CLIENT_NAME_WORDS = ["official", "verified", "trusted"] # Block names containing these
+
+# AbstractApplication.name is a CharField(max_length=255). HTML-escaping can lengthen the
+# value, so sanitize_client_name truncates the escaped result back to fit the column.
+CLIENT_NAME_MAX_LENGTH = 255
+
+# Matches a partial HTML entity left dangling at the end after truncation (e.g. "&am"
+# from "&amp;"). After escaping, every literal "&" becomes the start of an entity, so any
+# trailing "&" followed by entity-name characters without a closing ";" is a cut-off entity.
+_DANGLING_ENTITY_RE = re.compile(r"&[a-zA-Z0-9#]*$")
+
+
+def validate_client_name(value: str) -> None:
+ """Validate that client name doesn't impersonate official apps."""
+ lower_value = value.lower()
+ for prefix in BLOCKED_CLIENT_NAME_PREFIXES:
+ if lower_value.startswith(prefix):
+ raise serializers.ValidationError(f"Client name cannot start with '{prefix}'")
+ 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.
+
+ Escape at ingestion rather than trusting every downstream renderer to do it. The
+ escaped result is truncated to the model's column limit because escaping can push
+ it past 255 chars. Truncation can slice through an entity (e.g. leaving "&am" from
+ "&amp;"), so any dangling partial entity at the end is stripped to avoid rendering
+ a stray fragment.
+ """
+ truncated = escape(value)[:CLIENT_NAME_MAX_LENGTH]
+ undangled = _DANGLING_ENTITY_RE.sub("", truncated)
+
+ return undangled
diff --git a/posthog/api/oauth/dcr.py b/posthog/api/oauth/dcr.py
index b284912d0bec..ef5ba502515d 100644
--- a/posthog/api/oauth/dcr.py
+++ b/posthog/api/oauth/dcr.py
@@ -30,12 +30,9 @@ from posthog.models.oauth import OAuthApplication
from posthog.rate_limit import IPThrottle
from posthog.scopes import filter_to_unprivileged_scopes
-logger = structlog.get_logger(__name__)
+from .client_name import sanitize_client_name, validate_client_name
-# Blocked words in client names to prevent confusion attacks
-# These prevent malicious apps from impersonating official PostHog applications
-BLOCKED_CLIENT_NAME_PREFIXES = ["posthog"] # Block names starting with these
-BLOCKED_CLIENT_NAME_WORDS = ["official", "verified", "trusted"] # Block names containing these
+logger = structlog.get_logger(__name__)
def filter_dcr_scopes(scope: str) -> list[str]:
@@ -44,17 +41,6 @@ def filter_dcr_scopes(scope: str) -> list[str]:
return filter_to_unprivileged_scopes(scope.split())
-def validate_client_name(value: str) -> None:
- """Validate that client name doesn't impersonate official apps."""
- lower_value = value.lower()
- for prefix in BLOCKED_CLIENT_NAME_PREFIXES:
- if lower_value.startswith(prefix):
- raise serializers.ValidationError(f"Client name cannot start with '{prefix}'")
- for word in BLOCKED_CLIENT_NAME_WORDS:
- if word in lower_value:
- raise serializers.ValidationError(f"Client name cannot contain '{word}'")
-
-
class DCRBurstThrottle(IPThrottle):
"""Rate limit DCR by IP - burst limit."""
@@ -143,6 +129,7 @@ class DynamicClientRegistrationView(APIView):
data = serializer.validated_data
now = timezone.now()
+ client_name = sanitize_client_name(data["client_name"]) if data.get("client_name") else "MCP Client"
is_confidential = data.get("token_endpoint_auth_method") == "client_secret_post"
client_type = AbstractApplication.CLIENT_CONFIDENTIAL if is_confidential else AbstractApplication.CLIENT_PUBLIC
@@ -173,7 +160,7 @@ class DynamicClientRegistrationView(APIView):
try:
app = OAuthApplication.objects.create(
- name=data.get("client_name", "MCP Client"),
+ name=client_name,
redirect_uris=" ".join(data["redirect_uris"]),
client_type=client_type,
client_secret=plaintext_secret,
@@ -223,7 +210,7 @@ class DynamicClientRegistrationView(APIView):
distinct_id=str(app.client_id),
event="dcr_application_created",
properties={
- "client_name": data.get("client_name", "MCP Client"),
+ "client_name": client_name,
"app_id": str(app.pk),
"client_type": "confidential" if is_confidential else "public",
"redirect_uris_count": len(data["redirect_uris"]),
@@ -247,7 +234,7 @@ class DynamicClientRegistrationView(APIView):
response_data["client_secret_expires_at"] = 0 # 0 = never expires per RFC 7591
if data.get("client_name"):
- response_data["client_name"] = data["client_name"]
+ response_data["client_name"] = client_name
# RFC 7591 Section 3.2.1: when the server modifies requested scopes, it
# returns the registered `scope` so the client sees the privileged-strip.
diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.py
index ab5383c0db91..fee12fd9e575 100644
--- a/posthog/api/oauth/test_cimd.py
+++ b/posthog/api/oauth/test_cimd.py
@@ -10,6 +10,7 @@ from unittest.mock import MagicMock, patch
from django.core.cache import cache as real_cache
from django.test import SimpleTestCase
+from django.utils.html import escape
import requests
from parameterized import parameterized
@@ -33,6 +34,7 @@ from posthog.api.oauth.cimd import (
register_cimd_provisioning_application_task,
validate_cimd_url,
)
+from posthog.api.oauth.client_name import sanitize_client_name
from posthog.models.oauth import OAuthApplication, create_cimd_verification_token
from posthog.scopes import OAUTH_HIDDEN_SCOPES, PRIVILEGED_SCOPES
@@ -362,6 +364,43 @@ class TestGetOrCreateCimdApplication(APIBaseTest):
self.assertEqual(app.name, "Updated Name")
self.assertEqual(app.logo_uri, "https://example.com/new-logo.png")
+ @parameterized.expand(
+ [
+ ("script_tag", "<script>alert(1)</script>"),
+ ("attribute_breakout", '"><img src=x onerror=alert(1)>'),
+ ("ampersand_preserved", "Acme & Co"),
+ ("over_length_after_escape", "<" * 300),
+ ]
+ )
+ @patch("posthog.api.oauth.cimd.requests.get")
+ def test_client_name_from_metadata_is_html_escaped(self, _name, payload, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata(client_name=payload), headers={})
+
+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ assert app is not None
+ expected = sanitize_client_name(payload)
+ self.assertEqual(app.name, expected)
+ self.assertNotIn("<", app.name)
+ self.assertNotIn(">", app.name)
+
+ @patch("posthog.api.oauth.cimd.requests.get")
+ def test_refresh_escapes_client_name_idempotently(self, mock_get, _url_mock):
+ payload = "<script>alert(1)</script>"
+ mock_get.return_value = _mock_response(_make_metadata(client_name="Safe Name"), headers={})
+ fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ # Refresh twice with the same script payload — each call needs its own response because
+ # _mock_response's iter_content is a one-shot iterator. Re-escaping the raw metadata each
+ # time must not compound (it escapes the metadata value, not the already-escaped app.name).
+ for _ in range(2):
+ mock_get.return_value = _mock_response(_make_metadata(client_name=payload), headers={})
+ refresh_cimd_metadata_task(VALID_CIMD_URL)
+
+ app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)
+ self.assertEqual(app.name, escape(payload))
+ self.assertNotIn("<", app.name)
+
@patch("posthog.api.oauth.cimd.requests.get")
def test_refresh_task_handles_fetch_failure_gracefully(self, mock_get, _url_mock):
metadata = _make_metadata(client_name="Original Name")
diff --git a/posthog/api/oauth/test_client_name.py b/posthog/api/oauth/test_client_name.py
new file mode 100644
index 000000000000..66d6df83815a
--- /dev/null
+++ b/posthog/api/oauth/test_client_name.py
@@ -0,0 +1,63 @@
+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
+
+
+class TestSanitizeClientName(TestCase):
+ @parameterized.expand(
+ [
+ ("plain_name", "My Analytics App", "My Analytics App"),
+ ("script_tag", "<script>alert(1)</script>", "&lt;script&gt;alert(1)&lt;/script&gt;"),
+ ("ampersand_in_middle", "Tom & Jerry", "Tom &amp; Jerry"),
+ ("quote", "John's App", "John&#x27;s App"),
+ ]
+ )
+ def test_escapes_short_names_without_truncation(self, _name, value, expected):
+ self.assertEqual(sanitize_client_name(value), expected)
+
+ @parameterized.expand(
+ [
+ # "&" escapes to "&amp;" (5 chars). Pad so truncation slices through it, leaving a
+ # dangling fragment that must be stripped entirely rather than rendered.
+ ("amp_cut_to_bare_ampersand", "a" * 254 + "&", "a" * 254),
+ ("amp_cut_to_partial", "a" * 252 + "&", "a" * 252),
+ # "'" escapes to "&#x27;" (6 chars) — exercises the "#"/digits in the entity char class.
+ ("numeric_entity_cut", "a" * 250 + "'", "a" * 250),
+ # A complete entity sitting exactly on the boundary must be preserved, not over-stripped.
+ ("complete_entity_preserved_at_boundary", "a" * 250 + "&", "a" * 250 + "&amp;"),
+ # No special chars: plain truncation with nothing to strip.
+ ("plain_truncation", "a" * 300, "a" * 255),
+ ]
+ )
+ def test_strips_dangling_entity_after_truncation(self, _name, value, expected):
+ result = sanitize_client_name(value)
+
+ self.assertEqual(result, expected)
+ self.assertLessEqual(len(result), CLIENT_NAME_MAX_LENGTH)
+
+
+class TestValidateClientName(TestCase):
+ @parameterized.expand(
+ [
+ ("prefix_posthog", "PostHog Client"),
+ ("prefix_posthog_lowercase", "posthog-integration"),
+ ("word_official", "Official MCP Client"),
+ ("word_verified", "My Verified App"),
+ ("word_trusted_embedded", "MYTRUSTEDAPP"),
+ ]
+ )
+ def test_rejects_impersonating_names(self, _name, value):
+ with self.assertRaises(serializers.ValidationError):
+ validate_client_name(value)
+
+ @parameterized.expand(
+ [
+ ("contains_but_not_prefixed_by_posthog", "Claude Code (posthog-local)"),
+ ("unrelated_name", "My Analytics Dashboard"),
+ ]
+ )
+ def test_accepts_valid_names(self, _name, value):
+ validate_client_name(value)
diff --git a/posthog/api/oauth/test_dcr.py b/posthog/api/oauth/test_dcr.py
index 4770474fea1b..eea576ca7beb 100644
--- a/posthog/api/oauth/test_dcr.py
+++ b/posthog/api/oauth/test_dcr.py
@@ -7,6 +7,7 @@ from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIClient
+from posthog.api.oauth.client_name import sanitize_client_name
from posthog.models.oauth import OAuthApplication, OAuthApplicationAccessLevel
@@ -364,6 +365,30 @@ class TestDynamicClientRegistration(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.json()["client_name"], "My Analytics Dashboard")
+ @parameterized.expand(
+ [
+ ("script_tag", "<script>alert(1)</script>"),
+ ("attribute_breakout", '"><img src=x onerror=alert(1)>'),
+ ("ampersand_preserved", "Acme & Co"),
+ ("over_length_after_escape", "<" * 255),
+ ]
+ )
+ def test_client_name_is_html_escaped_when_stored(self, _name, payload):
+ response = self.client.post(
+ "/oauth/register/",
+ {"client_name": payload, "redirect_uris": ["https://example.com/callback"]},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+
+ # Escaped once at ingestion and capped to the model's name column.
+ expected = sanitize_client_name(payload)
+ app = OAuthApplication.objects.get(client_id=response.json()["client_id"])
+ self.assertEqual(app.name, expected)
+ self.assertNotIn("<", app.name)
+ self.assertNotIn(">", app.name)
+ self.assertEqual(response.json()["client_name"], expected)
+
@parameterized.expand(
[
# (name, requested scope, expected app.scopes ceiling, expected echoed `scope` in 201 — None means omitted)