: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(oauth): accept logo_uri when a client registers itself (#98775)
Rafael Audibert883465343575
diff --git a/docs/published/handbook/engineering/oauth-development-guide.md b/docs/published/handbook/engineering/oauth-development-guide.mdindex 29f6606b091d..d20daee90e84 100644--- a/docs/published/handbook/engineering/oauth-development-guide.md+++ b/docs/published/handbook/engineering/oauth-development-guide.md@@ -322,6 +322,17 @@ tokens = token_response.json()print(tokens)```+## Self-registered client logos++Both self-registration paths accept a `logo_uri`, and PostHog shows it on the consent screen and on the login, signup, and email verification screens. A client that sends none gets the first letter of its name instead.++- Dynamic client registration (`POST /oauth/register/`, RFC 7591): send `logo_uri` alongside `redirect_uris`. The response echoes it back.+- Client ID metadata documents: put `logo_uri` in the document.++The URI must be `https` and must pass `is_url_allowed`, the same SSRF guard the rest of the codebase uses. That rejects a loopback, private, metadata or internal-domain host, and it resolves the name, so a public hostname pointing at a private address is rejected too. A URI that fails either check is dropped and left out of the registration response. It never fails the registration, since a client can complete every OAuth flow without a logo.++The host check protects the visitor rather than PostHog. PostHog never fetches a logo: the browser does, and a self-hosted deployment renders these pages to people inside a trusted network. An unchecked logo would make each of those browsers probe its own network from a PostHog page.+## Signed-out visitors`/oauth/authorize/` needs a session. A visitor without one is redirected to `/login?next=<the authorize URL>`. The login, signup, and email verification screens keep `next`, so the visitor lands on the consent screen once they have a session, and `/oauth` paths are exempt from the onboarding redirect.diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.pyindex 1db491dab469..b1453e23650e 100644--- a/posthog/api/oauth/cimd.py+++ b/posthog/api/oauth/cimd.py@@ -42,6 +42,7 @@ from posthog.security.pinned_requests import PinnedIPAdapter, select_pinned_ipfrom posthog.security.url_validation import is_url_allowed, validate_url_and_pin_ipsfrom .client_name import sanitize_client_name, validate_client_name+from .logo_uri import usable_logo_uriif TYPE_CHECKING:from posthog.models.oauth_provisioning import ProvisioningConfig@@ -398,15 +399,9 @@ def fetch_cimd_metadata(url: str) -> tuple[CIMDMetadataDocument, int]:# storing a URL we would never fetch.metadata.pop("jwks_uri", None)- # Validate logo_uri if present: must be HTTPS and pass SSRF checkslogo_uri = metadata.get("logo_uri")- if logo_uri:- if not isinstance(logo_uri, str) or not logo_uri.startswith("https://"):- metadata.pop("logo_uri", None)- else:- logo_allowed, _ = is_url_allowed(logo_uri)- if not logo_allowed:- metadata.pop("logo_uri", None)+ if logo_uri is not None and usable_logo_uri(logo_uri) is None:+ metadata.pop("logo_uri", None)cache_ttl = _parse_cache_ttl(response)return metadata, cache_ttldiff --git a/posthog/api/oauth/dcr.py b/posthog/api/oauth/dcr.pyindex a4ac03dd3917..6b15c06a53f5 100644--- a/posthog/api/oauth/dcr.py+++ b/posthog/api/oauth/dcr.py@@ -31,6 +31,7 @@ from posthog.rate_limit import IPThrottlefrom posthog.scopes import filter_to_unprivileged_scopesfrom .client_name import sanitize_client_name, validate_client_name+from .logo_uri import MAX_LOGO_URI_LENGTH, usable_logo_urilogger = structlog.get_logger(__name__)@@ -100,6 +101,12 @@ class DCRRequestSerializer(serializers.Serializer):allow_blank=True,help_text="Space-delimited OAuth scopes (RFC 7591). Sets the client's scope ceiling; privileged scopes are stripped, and a set that strips to nothing is rejected. Omit to use the default scope set.",)+ logo_uri = serializers.CharField(+ max_length=MAX_LOGO_URI_LENGTH,+ required=False,+ allow_blank=True,+ help_text="HTTPS URL of the client's logo, shown on the consent screen and on the login and signup screens. A URL that is not HTTPS, or whose host resolves to a loopback, private, metadata or internal address, is dropped and left out of the response.",+ )class DynamicClientRegistrationView(APIView):@@ -140,6 +147,8 @@ class DynamicClientRegistrationView(APIView):# the create() call simple -- we just don't return it in the response.plaintext_secret = generate_client_secret()+ logo_uri = usable_logo_uri(data.get("logo_uri"))+requested_scope = data.get("scope")app_scopes = filter_dcr_scopes(requested_scope) if requested_scope else []@@ -161,6 +170,7 @@ class DynamicClientRegistrationView(APIView):try:app = OAuthApplication.objects.create(name=client_name,+ logo_uri=logo_uri,redirect_uris=" ".join(data["redirect_uris"]),client_type=client_type,client_secret=plaintext_secret,@@ -237,6 +247,11 @@ class DynamicClientRegistrationView(APIView):if data.get("client_name"):response_data["client_name"] = client_name+ # RFC 7591 Section 3.2.1: the response carries the metadata as registered, so a client+ # whose logo was dropped sees `logo_uri` absent rather than echoed back.+ if logo_uri:+ response_data["logo_uri"] = logo_uri+# RFC 7591 Section 3.2.1: when the server modifies requested scopes, it# returns the registered `scope` so the client sees the privileged-strip.if app_scopes:diff --git a/posthog/api/oauth/logo_uri.py b/posthog/api/oauth/logo_uri.pynew file mode 100644index 000000000000..b213ddaf16c8--- /dev/null+++ b/posthog/api/oauth/logo_uri.py@@ -0,0 +1,29 @@+"""Shared guard for the `logo_uri` an OAuth client supplies about itself.++Both self-registration paths accept the value from the client, and PostHog renders it as an+`<img src>` on the consent screen and on the auth screens.++PostHog never fetches a logo, so this does not protect PostHog's own egress. It protects the+visitor: the browser makes that request, and a self-hosted deployment renders these pages to+people inside a trusted network. A logo pointing at a loopback, metadata or internal address+would make each of those browsers probe its own network from a PostHog page.+"""++from posthog.security.url_validation import is_url_allowed++# Column limit of `OAuthApplication.logo_uri`.+MAX_LOGO_URI_LENGTH = 2048+++def usable_logo_uri(value: object) -> str | None:+ """The logo URI if a browser can load it from a PostHog page, else None.++ Only https survives, because a PostHog page is https and a browser blocks the rest.++ A rejected logo does not fail the registration, because the logo is decorative and the+ client can still complete every OAuth flow without it.+ """+ if not isinstance(value, str) or not value.startswith("https://") or len(value) > MAX_LOGO_URI_LENGTH:+ return None+ allowed, _ = is_url_allowed(value)+ return value if allowed else Nonediff --git a/posthog/api/oauth/test_dcr.py b/posthog/api/oauth/test_dcr.pyindex 33d731b8dfba..f6a6eda23661 100644--- a/posthog/api/oauth/test_dcr.py+++ b/posthog/api/oauth/test_dcr.py@@ -1,8 +1,10 @@import base64import hashlib+import ipaddressfrom urllib.parse import parse_qs, urlparsefrom posthog.test.base import APIBaseTest+from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import status@@ -11,6 +13,8 @@ from rest_framework.test import APIClientfrom posthog.api.oauth.client_name import sanitize_client_namefrom posthog.models.oauth import OAuthApplication, OAuthApplicationAccessLevel, OAuthGrant+PUBLIC_IPS = {ipaddress.ip_address("93.184.216.34")}+class TestDynamicClientRegistration(APIBaseTest):def setUp(self):@@ -41,7 +45,8 @@ class TestDynamicClientRegistration(APIBaseTest):self.assertIsNone(app.organization)self.assertIsNone(app.user)- def test_register_full_client(self):+ @patch("posthog.security.url_validation.resolve_host_ips", return_value=PUBLIC_IPS)+ def test_register_full_client(self, _resolve):response = self.client.post("/oauth/register/",{@@ -50,6 +55,7 @@ class TestDynamicClientRegistration(APIBaseTest):"grant_types": ["authorization_code", "refresh_token"],"response_types": ["code"],"token_endpoint_auth_method": "none",+ "logo_uri": "https://example.com/logo.png",},format="json",)@@ -58,10 +64,29 @@ class TestDynamicClientRegistration(APIBaseTest):data = response.json()self.assertEqual(data["client_name"], "Test MCP Client")self.assertEqual(len(data["redirect_uris"]), 2)+ self.assertEqual(data["logo_uri"], "https://example.com/logo.png")# Verify name storedapp = OAuthApplication.objects.get(client_id=data["client_id"])self.assertEqual(app.name, "Test MCP Client")+ self.assertEqual(app.logo_uri, "https://example.com/logo.png")++ def test_register_drops_an_unusable_logo_without_failing(self):+ response = self.client.post(+ "/oauth/register/",+ {+ "redirect_uris": ["https://example.com/callback"],+ "logo_uri": "http://example.com/logo.png",+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ data = response.json()+ self.assertNotIn("logo_uri", data)++ app = OAuthApplication.objects.get(client_id=data["client_id"])+ self.assertIsNone(app.logo_uri)def test_register_localhost_http_allowed(self):response = self.client.post(diff --git a/posthog/api/oauth/test_logo_uri.py b/posthog/api/oauth/test_logo_uri.pynew file mode 100644index 000000000000..5ad37793884c--- /dev/null+++ b/posthog/api/oauth/test_logo_uri.py@@ -0,0 +1,51 @@+import ipaddress++from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized++from .logo_uri import MAX_LOGO_URI_LENGTH, usable_logo_uri++PUBLIC_IPS = {ipaddress.ip_address("93.184.216.34")}+PRIVATE_IPS = {ipaddress.ip_address("10.1.2.3")}+++class TestUsableLogoUri(SimpleTestCase):+ @parameterized.expand(+ [+ ("https url", "https://example.com/logo.png"),+ ("https url with query", "https://example.com/logo.png?v=2"),+ ]+ )+ def test_keeps(self, _name: str, value: str) -> None:+ with patch("posthog.security.url_validation.resolve_host_ips", return_value=PUBLIC_IPS):+ self.assertEqual(usable_logo_uri(value), value)++ @parameterized.expand(+ [+ ("http", "http://example.com/logo.png"),+ ("protocol relative", "//example.com/logo.png"),+ ("data uri", "data:image/png;base64,AAAA"),+ ("javascript uri", "javascript:alert(1)"),+ ("loopback host", "https://localhost/logo.png"),+ ("loopback address", "https://127.0.0.1/logo.png"),+ ("private address", "https://10.0.0.5/logo.png"),+ ("link local metadata address", "https://169.254.169.254/logo.png"),+ ("internal domain suffix", "https://billing.svc.cluster.local/logo.png"),+ ("empty", ""),+ ("not a string", 12),+ ("missing", None),+ ]+ )+ def test_drops(self, _name: str, value: object) -> None:+ with patch("posthog.security.url_validation.resolve_host_ips", return_value=PUBLIC_IPS):+ self.assertIsNone(usable_logo_uri(value))++ def test_drops_a_public_name_that_resolves_to_a_private_address(self) -> None:+ with patch("posthog.security.url_validation.resolve_host_ips", return_value=PRIVATE_IPS):+ self.assertIsNone(usable_logo_uri("https://logo.example.com/logo.png"))++ def test_drops_a_uri_past_the_column_limit(self) -> None:+ self.assertIsNone(usable_logo_uri("https://example.com/" + "a" * MAX_LOGO_URI_LENGTH))