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): allow native-app redirect URIs for CIMD clients (#65856)

Alex Lidera03a9cab9b6d
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.py
index d71d3e3fe8c8..00dd43b1c597 100644
--- a/posthog/models/oauth.py
+++ b/posthog/models/oauth.py
@@ -20,6 +20,8 @@ from oauth2_provider.models import (
AbstractIDToken,
AbstractRefreshToken,
)
+from oauth2_provider.settings import oauth2_settings
+from oauth2_provider.validators import AllowedURIValidator
from posthog.helpers.encrypted_fields import EncryptedCharField
from posthog.models.activity_logging.model_activity import ModelActivityMixin
@@ -285,64 +287,100 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignore
)
def clean(self):
- super().clean()
-
- if self.optional_scopes:
- if not self.scopes:
- raise ValidationError(
- {"optional_scopes": "Declaring optional scopes requires a non-empty required set in `scopes`."}
- )
- for field, values in (("scopes", self.scopes), ("optional_scopes", self.optional_scopes)):
- non_resource = [scope for scope in values if ":" not in scope]
- if non_resource:
- # `*` or identity scopes in a required set either brick /authorize
- # (explicit ceilings reject `*`) or 400 every consent the client
- # didn't request them on, with no UI recourse.
- raise ValidationError(
- {
- field: f"With optional scopes declared, every entry must be a resource scope "
- f"(object:action); invalid: {', '.join(non_resource)}"
- }
- )
-
- for uri in self.redirect_uris.split(" "):
- if not uri:
- continue
-
+ # Full override of AbstractApplication.clean(). We run django-oauth-toolkit's redirect_uri
+ # validator ourselves with a carve-out for authority-less native-app schemes (com.example.app:/oauth),
+ # and re-implement its remaining model checks in _validate_application_config — rather than
+ # calling super().clean(), which would re-run the redirect validation and reject those native schemes.
+ self._validate_redirect_uris()
+ self._validate_optional_scopes()
+ self._validate_application_config()
+
+ def _validate_redirect_uris(self):
+ validator = AllowedURIValidator(
+ {scheme.lower() for scheme in self.get_allowed_schemes()},
+ name="redirect uri",
+ allow_path=True,
+ allow_query=True,
+ allow_hostname_wildcard=oauth2_settings.ALLOW_URI_WILDCARDS,
+ )
+ for uri in self.redirect_uris.split():
parsed_uri = urlparse(uri)
- if parsed_uri.fragment:
- raise ValidationError({"redirect_uris": f"Redirect URI {uri} cannot contain fragments"})
-
- # Custom URL schemes for native apps (RFC 8252 Section 7.1)
- # These look like: myapp://callback, posthog-code://oauth
- is_custom_scheme = parsed_uri.scheme not in ["http", "https", ""]
-
- if is_custom_scheme:
- # Block dangerous schemes that could be used for attacks (XSS, data exfiltration, etc.)
- # Since we use DCR with pre-registration, clients can use any scheme not in this blocklist
+ # RFC 8252 Section 7.1 private-use scheme redirects (e.g. com.example.app:/oauth)
+ # are authority-less by design; django-oauth-toolkit validator rejects them solely for lacking a host.
+ # Everything else goes through validator unchanged.
+ if parsed_uri.scheme not in ("http", "https", "") and parsed_uri.hostname is None:
if parsed_uri.scheme in self.get_blocked_schemes():
raise ValidationError(
{
"redirect_uris": f"Redirect URI scheme '{parsed_uri.scheme}' is not allowed for security reasons"
}
)
- else:
- # Standard HTTP(S) validation
- if not parsed_uri.netloc:
- raise ValidationError({"redirect_uris": f"Redirect URI {uri} must contain a host"})
+ if parsed_uri.fragment:
+ raise ValidationError({"redirect_uris": f"Redirect URI {uri} cannot contain fragments"})
+ continue
- is_loopback = is_loopback_host(parsed_uri.hostname)
+ # django-oauth-toolkit validates scheme, fragment, and URL shape
+ validator(uri)
- # http is only allowed for loopback addresses (localhost, 127.x.x.x)
- allowed_schemes = ["http", "https"] if is_loopback else ["https"]
+ # django-oauth-toolkit permits any allowlisted scheme; we additionally require https except on loopback.
+ if parsed_uri.scheme == "http" and not is_loopback_host(parsed_uri.hostname):
+ raise ValidationError(
+ {
+ "redirect_uris": f"Redirect URI {uri} must use https (http is only allowed for loopback addresses)"
+ }
+ )
- if parsed_uri.scheme not in allowed_schemes:
- raise ValidationError(
- {
- "redirect_uris": f"Redirect URI {uri} must start with one of the following schemes: {', '.join(allowed_schemes)}"
- }
- )
+ def _validate_optional_scopes(self):
+ if not self.optional_scopes:
+ return
+ if not self.scopes:
+ raise ValidationError(
+ {"optional_scopes": "Declaring optional scopes requires a non-empty required set in `scopes`."}
+ )
+ for field, values in (("scopes", self.scopes), ("optional_scopes", self.optional_scopes)):
+ non_resource = [scope for scope in values if ":" not in scope]
+ if non_resource:
+ # `*` or identity scopes in a required set either brick /authorize
+ # (explicit ceilings reject `*`) or 400 every consent the client
+ # didn't request them on, with no UI recourse.
+ raise ValidationError(
+ {
+ field: f"With optional scopes declared, every entry must be a resource scope "
+ f"(object:action); invalid: {', '.join(non_resource)}"
+ }
+ )
+
+ def _validate_application_config(self):
+ # Mirror of AbstractApplication.clean()'s non-redirect checks (grant type, allowed origins,
+ # signing algorithm). Re-implemented here because clean() does not call super().clean()
+ code_grant_types = (
+ AbstractApplication.GRANT_AUTHORIZATION_CODE,
+ AbstractApplication.GRANT_IMPLICIT,
+ AbstractApplication.GRANT_OPENID_HYBRID,
+ )
+ if not self.redirect_uris.split() and self.authorization_grant_type in code_grant_types:
+ raise ValidationError(f"redirect_uris cannot be empty with grant_type {self.authorization_grant_type}")
+
+ allowed_origins = self.allowed_origins.split()
+ if allowed_origins:
+ origin_validator = AllowedURIValidator(
+ oauth2_settings.ALLOWED_SCHEMES,
+ name="allowed origin",
+ allow_hostname_wildcard=oauth2_settings.ALLOW_URI_WILDCARDS,
+ )
+ for origin in allowed_origins:
+ origin_validator(origin)
+
+ if self.algorithm == AbstractApplication.RS256_ALGORITHM and not oauth2_settings.OIDC_RSA_PRIVATE_KEY:
+ raise ValidationError("You must set OIDC_RSA_PRIVATE_KEY to use RSA algorithm")
+
+ if self.algorithm == AbstractApplication.HS256_ALGORITHM and (
+ self.authorization_grant_type
+ in (AbstractApplication.GRANT_IMPLICIT, AbstractApplication.GRANT_OPENID_HYBRID)
+ or self.client_type == AbstractApplication.CLIENT_PUBLIC
+ ):
+ raise ValidationError("You cannot use HS256 with public grants or clients")
def save(self, *args, **kwargs):
self.full_clean()
diff --git a/posthog/models/test/test_oauth.py b/posthog/models/test/test_oauth.py
index 2a20de02a9a3..29b95c424a2a 100644
--- a/posthog/models/test/test_oauth.py
+++ b/posthog/models/test/test_oauth.py
@@ -346,6 +346,7 @@ class TestOAuthModels(TestCase):
("reverse domain style", "com.posthog.code://oauth"),
("cursor scheme", "cursor://oauth"),
("vscode scheme", "vscode://oauth"),
+ ("authority-less native scheme", "com.example.app:/oauth"),
]
@parameterized.expand(valid_custom_scheme_uris)
@@ -363,7 +364,13 @@ class TestOAuthModels(TestCase):
)
self.assertEqual(app.redirect_uris, redirect_uri)
- def test_custom_scheme_with_fragment_still_rejected(self):
+ @parameterized.expand(
+ [
+ ("authority form", "myapp://callback#fragment"),
+ ("authority-less native", "com.example.app:/oauth#fragment"),
+ ]
+ )
+ def test_custom_scheme_with_fragment_still_rejected(self, _name, redirect_uri):
with self.assertRaises(ValidationError):
OAuthApplication.objects.create(
name="Invalid Custom Scheme App",
@@ -371,7 +378,7 @@ class TestOAuthModels(TestCase):
client_secret="invalid_custom_scheme_client_secret",
client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="myapp://callback#fragment",
+ redirect_uris=redirect_uri,
organization=self.organization,
algorithm="RS256",
)
@@ -427,6 +434,19 @@ class TestOAuthModels(TestCase):
algorithm="RS256",
)
+ def test_code_grant_application_requires_redirect_uri(self):
+ with self.assertRaises(ValidationError):
+ OAuthApplication.objects.create(
+ name="No Redirect App",
+ client_id="no_redirect_client_id",
+ client_secret="no_redirect_client_secret",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="",
+ organization=self.organization,
+ algorithm="RS256",
+ )
+
def test_invalid_redirect_uri_no_host(self):
with self.assertRaises(ValidationError):
OAuthApplication.objects.create(