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): only promote registered partners to confidential CIMD clients (#80748)

Matt Brookercb634256d3d0
diff --git a/ee/api/agentic_provisioning/test/test_client_registration.py b/ee/api/agentic_provisioning/test/test_client_registration.py
index a1a82cfea685..caf3909d7d0c 100644
--- a/ee/api/agentic_provisioning/test/test_client_registration.py
+++ b/ee/api/agentic_provisioning/test/test_client_registration.py
@@ -11,7 +11,7 @@ import jwt
from cryptography.hazmat.primitives.asymmetric import rsa
from parameterized import parameterized
-from posthog.api.oauth.cimd import CIMDFetchError
+from posthog.api.oauth.cimd import CIMDFetchError, apply_provisioning_defaults
from posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER, ClientAssertionError
from posthog.models.oauth import OAuthApplication
@@ -148,6 +148,58 @@ class TestClientRegistration(ProvisioningTestBase):
assert checks["jwks"]["ok"] is True
assert KID in checks["jwks"]["detail"]
+ def test_brand_new_partner_is_confidential_on_its_first_registration(self):
+ # No pre-existing row: this is the client_id's first ever contact with PostHog, so the
+ # promotion has to happen inline with _create_cimd_application, not wait for the next
+ # hourly refresh to notice is_provisioning_partner has since flipped.
+ assert not OAuthApplication.objects.filter(cimd_metadata_url=CIMD_URL).exists()
+
+ res = self._register({"client_id": CIMD_URL})
+
+ assert res.status_code == 200, res.json()
+ body = res.json()
+ assert body["registered"] is True
+ assert body["token_endpoint_auth_method"] == "private_key_jwt"
+ app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_URL)
+ assert app.client_type == OAuthApplication.CLIENT_CONFIDENTIAL
+ assert app.is_provisioning_partner
+
+ def test_partner_enablement_and_confidential_promotion_land_together(self):
+ # A partner that is enabled while still public would accept the bare-client_id path,
+ # so an unauthenticated caller could act as that partner until the promotion landed.
+ # apply_provisioning_defaults therefore has to write both in one go, which this pins by
+ # calling it directly: splitting the promotion back out leaves this app public.
+ app = self._make_partner(
+ is_provisioning_partner=False,
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ jwks_uri=JWKS_URI,
+ _provisioning_config=provisioning_config(active=False, can_create_accounts=False),
+ )
+
+ apply_provisioning_defaults(app)
+
+ app.refresh_from_db()
+ assert app.is_provisioning_partner
+ assert app.client_type == OAuthApplication.CLIENT_CONFIDENTIAL
+
+ def test_kill_switched_client_is_not_promoted_to_confidential(self):
+ # An admin can disable a client before it ever becomes a partner. The kill switch stops
+ # apply_provisioning_defaults from enabling the partner, and the promotion rides on that
+ # same write, so the client stays public rather than ending up confidential with a
+ # self-declared jwks_uri and no partner status behind it.
+ self._make_partner(
+ is_provisioning_partner=False,
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ jwks_uri=None,
+ _provisioning_config=provisioning_config(disabled=True, active=False, can_create_accounts=False),
+ )
+
+ self._register({"client_id": CIMD_URL})
+
+ app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_URL)
+ assert app.client_type == OAuthApplication.CLIENT_PUBLIC
+ assert app.is_provisioning_partner is False
+
def test_partner_registered_by_an_admin_can_use_github_grants(self):
self._make_partner(_provisioning_config=provisioning_config(can_use_github_grants=True))
diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.py
index 05c02eadefcf..7ff17650ada1 100644
--- a/posthog/api/oauth/cimd.py
+++ b/posthog/api/oauth/cimd.py
@@ -593,26 +593,46 @@ def _resolve_optional_scopes(metadata: CIMDMetadataDocument) -> list[str] | None
return filter_to_unprivileged_scopes(raw_optional)
-def _resolve_client_authentication(metadata: CIMDMetadataDocument) -> tuple[str, str | None]:
+def _resolve_client_authentication(
+ metadata: CIMDMetadataDocument, *, allow_confidential: bool
+) -> tuple[str, str | None]:
"""Map a validated CIMD document's declared auth method onto ``(client_type, jwks_uri)``.
A client advertising private_key_jwt is confidential in the RFC 6749 sense even though it
holds no secret, because it can authenticate; everything else is public and relies on PKCE.
Those two stored fields are what OAuthApplication.token_endpoint_auth_method reads back.
- This is what lets a client upgrade in place: it edits its own metadata document, and the
- next refresh promotes it without the client_id changing or an operator being involved.
+ ``allow_confidential`` gates the promotion to a registered provisioning partner: the
+ document alone is not proof of anything, since the client that publishes it also controls
+ it, so an unregistered CIMD client declaring private_key_jwt stays public and keeps relying
+ on PKCE as its enforced baseline, rather than being upgraded into an auth method it may
+ never actually send. A partner, once registered, keeps upgrading and downgrading in place
+ as it edits its document, with no client_id change or operator involved.
+
+ A self-controlled declaration can only ever lower what we require, never raise it — that
+ takes partner registration. But the jwks_uri is stored either way, so a client that starts
+ signing later (a runtime change PostHog does not control) can still be verified and
+ accepted; see ``verify_client_assertion``. The declaration is a menu, not a mandate.
"""
auth_method = metadata.get("token_endpoint_auth_method", TokenEndpointAuthMethod.NONE.value)
- if auth_method == TokenEndpointAuthMethod.PRIVATE_KEY_JWT.value:
+ if auth_method == TokenEndpointAuthMethod.PRIVATE_KEY_JWT.value and allow_confidential:
return AbstractApplication.CLIENT_CONFIDENTIAL, metadata.get("jwks_uri")
- return AbstractApplication.CLIENT_PUBLIC, None
+ return AbstractApplication.CLIENT_PUBLIC, metadata.get("jwks_uri")
def _create_cimd_application(
- url: str, metadata: CIMDMetadataDocument, *, capture_ph_event: CapturePhEvent = posthoganalytics.capture
+ url: str,
+ metadata: CIMDMetadataDocument,
+ *,
+ allow_confidential: bool = False,
+ capture_ph_event: CapturePhEvent = posthoganalytics.capture,
) -> OAuthApplication:
- """Create a new OAuthApplication from CIMD metadata."""
+ """Create a new OAuthApplication from CIMD metadata.
+
+ A brand new row has no ``is_provisioning_partner`` state of its own yet, so
+ ``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)
@@ -627,7 +647,7 @@ def _create_cimd_application(
resolved_scopes = _resolve_scopes(metadata)
resolved_optional_scopes = _resolve_optional_scopes(metadata)
- client_type, jwks_uri = _resolve_client_authentication(metadata)
+ client_type, jwks_uri = _resolve_client_authentication(metadata, allow_confidential=allow_confidential)
app = OAuthApplication(
name=client_name,
@@ -703,6 +723,7 @@ def _update_cimd_application(
app: OAuthApplication,
metadata: CIMDMetadataDocument,
*,
+ allow_confidential: bool = False,
capture_ph_event: CapturePhEvent = posthoganalytics.capture,
) -> OAuthApplication:
"""
@@ -723,10 +744,14 @@ def _update_cimd_application(
app.logo_uri = new_uri if (new_uri := metadata.get("logo_uri")) is not None else app.logo_uri
app.cimd_metadata_last_fetched = timezone.now()
- # Re-derived on every refresh, in both directions: a client that starts publishing a
- # jwks_uri is promoted to confidential here, and one that stops is demoted back to public
- # rather than being left as a confidential client whose key source has gone away.
- app.client_type, app.jwks_uri = _resolve_client_authentication(metadata)
+ # Re-derived on every refresh, in both directions: a registered partner that starts
+ # publishing a jwks_uri is promoted to confidential here, and one that stops is demoted
+ # back to public rather than being left as a confidential client whose key source has gone
+ # away. A non-partner's document never promotes client_type this way, but its jwks_uri is
+ # still stored — see _resolve_client_authentication.
+ app.client_type, app.jwks_uri = _resolve_client_authentication(
+ metadata, allow_confidential=allow_confidential or app.is_provisioning_partner
+ )
# Re-evaluate verification on every refresh so a rotated/removed token
# unlinks the app on the next fetch.
@@ -794,7 +819,10 @@ def _update_cimd_application(
def fetch_and_upsert_cimd_application(
- url: str, capture_ph_event: CapturePhEvent = posthoganalytics.capture
+ url: str,
+ capture_ph_event: CapturePhEvent = posthoganalytics.capture,
+ *,
+ allow_confidential: bool = False,
) -> OAuthApplication | None:
"""
Fetch CIMD metadata and create or update the application.
@@ -804,6 +832,13 @@ def fetch_and_upsert_cimd_application(
(meaning another caller is already handling it).
Used by both synchronous (new client) and asynchronous (stale refresh) paths.
+
+ ``allow_confidential=True`` is for the explicit provisioning client-registration endpoint
+ only: a client hitting that endpoint is opting in to being a provisioning partner in the
+ same request, so its declared private_key_jwt is honored immediately rather than waiting
+ for the next hourly refresh to notice ``is_provisioning_partner`` has since flipped. Every
+ other caller leaves this False; an already-registered partner still promotes on refresh via
+ its persisted ``is_provisioning_partner``, independent of this flag.
"""
if is_cimd_url_blocked(url):
logger.warning("cimd_blocked_url_fetch_attempt", url=url)
@@ -819,7 +854,9 @@ def fetch_and_upsert_cimd_application(
app = OAuthApplication.objects.filter(cimd_metadata_url=url).first()
if app:
- updated = _update_cimd_application(app, metadata, capture_ph_event=capture_ph_event)
+ updated = _update_cimd_application(
+ app, metadata, allow_confidential=allow_confidential, capture_ph_event=capture_ph_event
+ )
logger.debug("cimd_app_updated", url=url, app_id=str(updated.pk))
capture_ph_event(
distinct_id=url,
@@ -836,7 +873,9 @@ def fetch_and_upsert_cimd_application(
return updated
try:
- new_app = _create_cimd_application(url, metadata, capture_ph_event=capture_ph_event)
+ new_app = _create_cimd_application(
+ url, metadata, allow_confidential=allow_confidential, capture_ph_event=capture_ph_event
+ )
logger.debug("cimd_app_created", url=url, app_id=str(new_app.pk), client_name=new_app.name)
capture_ph_event(
distinct_id=url,
@@ -999,6 +1038,12 @@ def apply_provisioning_defaults(app: OAuthApplication) -> OAuthApplication:
document, so the caller's copy of the app can be seconds or minutes old, and layering the
defaults over that copy would write back a capability - or a cleared kill switch - that an
admin revoked while the fetch was in flight.
+
+ Promotion to confidential happens in the same write. A partner that publishes a key set has
+ to present an assertion, and the bare-client_id path stays open to a public app, so an app
+ that is a partner but still public would accept an unauthenticated caller acting as that
+ partner. The locked row supplies the key set, since a stale in-memory copy could promote an
+ app whose document no longer publishes one.
"""
with transaction.atomic():
current = OAuthApplication.objects.select_for_update().get(pk=app.pk)
@@ -1008,7 +1053,12 @@ def apply_provisioning_defaults(app: OAuthApplication) -> OAuthApplication:
became_partner = not current.is_provisioning_partner
app.is_provisioning_partner = True
app.provisioning = _cimd_provisioning_defaults_for(app)
- app.save(update_fields=["is_provisioning_partner", "_provisioning_config"])
+ updated_fields = ["is_provisioning_partner", "_provisioning_config"]
+ if current.jwks_uri:
+ app.jwks_uri = current.jwks_uri
+ app.client_type = AbstractApplication.CLIENT_CONFIDENTIAL
+ updated_fields.append("client_type")
+ app.save(update_fields=updated_fields)
# A partner appearing without an admin creating it is the event worth watching for abuse,
# so it fires on the transition only - re-running the defaults over an existing partner is
diff --git a/posthog/api/oauth/client_assertion.py b/posthog/api/oauth/client_assertion.py
index 041d2490b782..9a1859c61fa7 100644
--- a/posthog/api/oauth/client_assertion.py
+++ b/posthog/api/oauth/client_assertion.py
@@ -258,12 +258,13 @@ def _consume_jti(client_id: str, jti: str, expires_at: int) -> None:
def verify_client_assertion(app: OAuthApplication, assertion: str, *, audiences: list[str] | None = None) -> None:
"""Verify a ``private_key_jwt`` assertion presented by ``app``, or raise.
- Checks, in order: the app is registered for this method and has a key source; the
+ Checks, in order: the app has a published key source to verify against — confidential
+ partners always have one, and a public CIMD client may too, once it starts signing; the
signature verifies against that key under an asymmetric algorithm; the audience is us;
``iss`` and ``sub`` both identify this client (RFC 7523 section 3); the lifetime is
bounded; and the ``jti`` has not been seen before.
"""
- if not app.uses_private_key_jwt_auth or not app.jwks_uri:
+ if not app.jwks_uri:
raise ClientAssertionError("This client is not registered for private_key_jwt authentication")
key = _select_key_allowing_rotation(app.jwks_uri, assertion)
diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.py
index dbdf1ea52175..7677550cf915 100644
--- a/posthog/api/oauth/test_cimd.py
+++ b/posthog/api/oauth/test_cimd.py
@@ -39,7 +39,12 @@ from posthog.api.oauth.cimd import (
)
from posthog.api.oauth.client_name import sanitize_client_name
from posthog.models import Organization
-from posthog.models.oauth import OAuthApplication, TokenEndpointAuthMethod, create_cimd_verification_token
+from posthog.models.oauth import (
+ OAuthApplication,
+ OAuthApplicationAccessLevel,
+ TokenEndpointAuthMethod,
+ create_cimd_verification_token,
+)
from posthog.scopes import OAUTH_SCOPES_HIDDEN, PRIVILEGED_SCOPES
VALID_CIMD_URL = "https://app.example.com/.well-known/oauth-client-metadata.json"
@@ -330,21 +335,51 @@ class TestFetchAndUpsertCimdApplication(APIBaseTest):
@parameterized.expand(
[
- # Publishing a key set is the upgrade path with no re-onboarding: the client edits
- # its own metadata document and the next refresh promotes it in place.
- ("promoted_when_a_jwks_uri_appears", False, True, TokenEndpointAuthMethod.PRIVATE_KEY_JWT),
- # A confidential client whose key source disappeared could never authenticate again,
- # so it must fall back to public rather than becoming permanently unusable.
- ("demoted_when_the_jwks_uri_disappears", True, False, TokenEndpointAuthMethod.NONE),
+ # A registered partner publishing a key set is the upgrade path with no
+ # re-onboarding: it edits its own metadata document and the next refresh promotes
+ # it in place.
+ (
+ "partner_promoted_when_a_jwks_uri_appears",
+ True,
+ False,
+ True,
+ TokenEndpointAuthMethod.PRIVATE_KEY_JWT,
+ CIMD_JWKS_URI,
+ ),
+ # A confidential partner whose key source disappeared could never authenticate
+ # again, so it must fall back to public rather than becoming permanently unusable.
+ ("partner_demoted_when_the_jwks_uri_disappears", True, True, False, TokenEndpointAuthMethod.NONE, None),
+ # A client that never registered as a partner cannot promote its client_type by
+ # editing a document it controls: it stays on the PKCE it was already relying on.
+ # But the jwks_uri is still stored, so a presented assertion can be verified —
+ # the declaration only ever raises what we accept, never what we require.
+ (
+ "non_partner_stores_jwks_uri_without_promotion",
+ False,
+ False,
+ True,
+ TokenEndpointAuthMethod.NONE,
+ CIMD_JWKS_URI,
+ ),
]
)
@patch("posthog.api.oauth.cimd.requests.Session.get")
def test_client_authentication_is_re_derived_on_every_refresh(
- self, _name, starts_with_jwks, ends_with_jwks, expected_method, mock_get, _url_mock
+ self,
+ _name,
+ is_partner,
+ starts_with_jwks,
+ ends_with_jwks,
+ expected_method,
+ expected_jwks_uri,
+ mock_get,
+ _url_mock,
):
mock_get.return_value = _mock_response(_metadata_for_auth(starts_with_jwks), headers={})
- app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL, allow_confidential=is_partner)
assert app is not None
+ if is_partner:
+ app = apply_provisioning_defaults(app)
mock_get.return_value = _mock_response(_metadata_for_auth(ends_with_jwks), headers={})
refreshed = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
@@ -354,12 +389,11 @@ class TestFetchAndUpsertCimdApplication(APIBaseTest):
self.assertEqual(refreshed.pk, app.pk)
self.assertEqual(refreshed.client_id, app.client_id)
self.assertIs(refreshed.token_endpoint_auth_method, expected_method)
- if ends_with_jwks:
- self.assertEqual(refreshed.jwks_uri, CIMD_JWKS_URI)
+ self.assertEqual(refreshed.jwks_uri, expected_jwks_uri)
+ if expected_method is TokenEndpointAuthMethod.PRIVATE_KEY_JWT:
# It holds no secret, but it can authenticate, so it is confidential per RFC 6749.
self.assertEqual(refreshed.client_type, OAuthApplication.CLIENT_CONFIDENTIAL)
else:
- self.assertIsNone(refreshed.jwks_uri)
self.assertEqual(refreshed.client_type, OAuthApplication.CLIENT_PUBLIC)
@patch("posthog.api.oauth.cimd.requests.Session.get")
@@ -1145,6 +1179,74 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):
self.assertEqual(response.status_code, 302)
self.assertIn("/login", response["Location"])
+ def _complete_pkce_flow(self, client_id: str):
+ """Register the CIMD client (bypassing the consent-screen render, which needs a built
+ frontend bundle this test has no reason to depend on), then drive /oauth/authorize/ to
+ consent and /oauth/token/ to exchange the code, with no client credential."""
+ get_or_create_cimd_application(client_id)
+ consent = self.client.post(
+ "/oauth/authorize/",
+ {
+ "client_id": client_id,
+ "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",
+ },
+ )
+ code = consent.json()["redirect_to"].split("code=")[1].split("&")[0]
+ return self.client.post(
+ "/oauth/token/",
+ {
+ "grant_type": "authorization_code",
+ "code": code,
+ "client_id": client_id,
+ "redirect_uri": "http://127.0.0.1:3000/callback",
+ "code_verifier": self.code_verifier,
+ },
+ )
+
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_non_partner_cimd_client_declaring_private_key_jwt_authenticates_via_pkce(self, mock_get, _url_mock):
+ # A CIMD client that has never registered as a provisioning partner cannot make itself
+ # confidential just by declaring private_key_jwt in the document it controls, so it
+ # must still be able to complete the ordinary public-client PKCE exchange.
+ mock_get.return_value = _mock_response(_metadata_for_auth(with_jwks=True))
+
+ token_response = self._complete_pkce_flow(VALID_CIMD_URL)
+
+ self.assertEqual(token_response.status_code, 200, token_response.json())
+ self.assertIn("access_token", token_response.json())
+ app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)
+ self.assertEqual(app.client_type, OAuthApplication.CLIENT_PUBLIC)
+ # The jwks_uri is still stored, even though it did not promote client_type: if this
+ # client starts signing, the token endpoint can verify it.
+ self.assertEqual(app.jwks_uri, CIMD_JWKS_URI)
+
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_existing_non_partner_cimd_client_keeps_authenticating_after_document_flips(self, mock_get, _url_mock):
+ # Reproduces the failure this gate exists to prevent: a working public client edits its
+ # own metadata document after the fact, an unrelated background refresh picks that up,
+ # and the client must still be able to authenticate afterwards.
+ mock_get.return_value = _mock_response(_make_metadata())
+ app = get_or_create_cimd_application(VALID_CIMD_URL)
+ self.assertEqual(app.client_type, OAuthApplication.CLIENT_PUBLIC)
+
+ mock_get.return_value = _mock_response(_metadata_for_auth(with_jwks=True))
+ fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ token_response = self._complete_pkce_flow(VALID_CIMD_URL)
+
+ self.assertEqual(token_response.status_code, 200, token_response.json())
+ self.assertIn("access_token", token_response.json())
+ app.refresh_from_db()
+ self.assertEqual(app.client_type, OAuthApplication.CLIENT_PUBLIC)
+
@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})
class TestCIMDComPostHogNamespace(APIBaseTest):
diff --git a/posthog/api/oauth/test_client_assertion.py b/posthog/api/oauth/test_client_assertion.py
index 22cbb0f7b1c8..94afe4d11071 100644
--- a/posthog/api/oauth/test_client_assertion.py
+++ b/posthog/api/oauth/test_client_assertion.py
@@ -213,6 +213,15 @@ class TestClientAssertion(BaseTest):
with self.assertRaises(ClientAssertionError):
self._verify(self._assertion())
+ def test_public_client_with_a_jwks_uri_verifies(self):
+ # A public CIMD client can publish keys and sign without ever being promoted to
+ # confidential (that takes partner registration) — verification only needs a key
+ # source, not client_type.
+ self.app.client_type = OAuthApplication.CLIENT_PUBLIC
+ self.app.save(update_fields=["client_type"])
+ assert not self.app.uses_private_key_jwt_auth
+ self._verify(self._assertion())
+
def test_jwks_is_cached_across_verifications(self):
with patch(
"posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=(self.jwks, None)
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 6c84477efe53..48adc680bfa9 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -642,6 +642,7 @@ class TestOAuthAPI(APIBaseTest):
def _create_private_key_jwt_app_and_grant(
self,
is_cimd_client: bool = True,
+ client_type: str = OAuthApplication.CLIENT_CONFIDENTIAL,
) -> tuple[OAuthApplication, OAuthGrant, rsa.RSAPrivateKey]:
cimd_url = "https://partner.example.com/oauth/client-metadata"
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
@@ -649,7 +650,7 @@ class TestOAuthAPI(APIBaseTest):
name="Private Key JWT CIMD Client",
client_id="cimd-pkjwt-client-id",
client_secret="",
- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ client_type=client_type,
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
redirect_uris="https://partner.example.com/callback",
user=self.user,
@@ -835,6 +836,61 @@ class TestOAuthAPI(APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED, response.content)
+ @freeze_time("2025-01-01 00:00:00")
+ @override_settings(SITE_URL="https://us.posthog.com")
+ def test_public_cimd_client_with_stored_jwks_completes_assertion_exchange(self):
+ # A public CIMD client (never partner-registered) can start signing at any time — a
+ # runtime change on the client's side PostHog doesn't control — and must be verified
+ # and accepted rather than rejected for presenting more proof than required.
+ app, grant, private_key = self._create_private_key_jwt_app_and_grant(client_type=OAuthApplication.CLIENT_PUBLIC)
+ assertion, jwks = self._signed_assertion_and_jwks(app, private_key)
+
+ with patch(
+ "posthog.api.oauth.client_assertion.fetch_client_json_document",
+ return_value=(jwks, None),
+ ):
+ response = self._post_assertion_exchange(app, grant, assertion)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertIn("access_token", response.json())
+
+ @freeze_time("2025-01-01 00:00:00")
+ @override_settings(SITE_URL="https://us.posthog.com")
+ def test_public_cimd_client_with_forged_assertion_is_rejected(self):
+ # The menu-semantics widening must not weaken verification: a public client's forged
+ # signature still 401s instead of silently downgrading to the PKCE it could have used
+ # by presenting nothing at all.
+ app, grant, private_key = self._create_private_key_jwt_app_and_grant(client_type=OAuthApplication.CLIENT_PUBLIC)
+ _, jwks = self._signed_assertion_and_jwks(app, private_key)
+ attacker_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ forged_assertion, _attacker_jwks = self._signed_assertion_and_jwks(app, attacker_key)
+
+ with patch(
+ "posthog.api.oauth.client_assertion.fetch_client_json_document",
+ return_value=(jwks, None),
+ ):
+ response = self._post_assertion_exchange(app, grant, forged_assertion)
+
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED, response.content)
+
+ @override_settings(SITE_URL="https://us.posthog.com")
+ def test_public_cimd_client_with_stored_jwks_still_completes_plain_pkce(self):
+ # A stored jwks_uri must not, by itself, force authentication: a public CIMD client
+ # presenting no credential at all still completes the ordinary PKCE exchange.
+ app, grant, _ = self._create_private_key_jwt_app_and_grant(client_type=OAuthApplication.CLIENT_PUBLIC)
+ response = self.post(
+ "/oauth/token/",
+ {
+ "grant_type": "authorization_code",
+ "client_id": app.client_id,
+ "redirect_uri": "https://partner.example.com/callback",
+ "code_verifier": self.code_verifier,
+ "code": grant.code,
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertIn("access_token", response.json())
+
@freeze_time("2025-01-01 00:00:00")
@override_settings(SITE_URL="https://us.posthog.com")
def test_invalid_assertion_is_not_downgraded_to_the_credentialless_fallback(self):
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 4bb60dc7de5a..41518ca49a8a 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -477,12 +477,15 @@ class OAuthValidator(OAuth2Validator):
return None
def authenticate_client(self, request, *args, **kwargs):
- """Authenticate a confidential client, adding ``private_key_jwt`` (RFC 7523).
-
- CIMD clients register as confidential with a ``jwks_uri`` and never receive a secret,
- so the library's secret-based paths cannot authenticate them. A client presenting a
- signed assertion is verified here against the keys it publishes; every other client
- falls through to the library's HTTP Basic and request-body secret checks.
+ """Authenticate a client presenting ``private_key_jwt`` (RFC 7523).
+
+ CIMD clients that hold a jwks_uri never receive a secret, so the library's
+ secret-based paths cannot authenticate them — confidential partners, whose signature
+ is required, and public CIMD clients that publish keys and sign opportunistically,
+ whose signature is only ever a bonus (see ``_authenticate_client_assertion``). A
+ client presenting a signed assertion is verified here against the keys it publishes;
+ every other client falls through to the library's HTTP Basic and request-body secret
+ checks.
"""
if self._authenticate_client_assertion(request):
return True
@@ -519,7 +522,10 @@ class OAuthValidator(OAuth2Validator):
assertion_value, client_id = assertion
app = self._load_application(client_id, request)
- if app is None or not app.uses_private_key_jwt_auth:
+ # jwks_uri alone gates this, not client_type: a public CIMD client may publish keys
+ # and start signing before any partner registration. What's REQUIRED is a separate
+ # question, decided by client_type via client_authentication_required.
+ if app is None or not app.jwks_uri:
return False
if app.is_cimd_client and app.cimd_metadata_url:
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.py
index fed75b26e6c8..94021d7f1e71 100644
--- a/posthog/models/oauth.py
+++ b/posthog/models/oauth.py
@@ -379,10 +379,10 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignore
if self.jwks_uri and not self.jwks_uri.startswith("https://"):
raise ValidationError("jwks_uri must be an https URL")
- # A public client cannot authenticate, so a key set would never be consulted
- # Rejecting the combination keeps token_endpoint_auth_method unambiguous.
- if self.jwks_uri and not self.requires_client_authentication:
- raise ValidationError("jwks_uri is only meaningful for a confidential client")
+ # A stored key set on a public client enables optional assertion authentication
+ # (verify_client_assertion) without requiring it: token_endpoint_auth_method reads
+ # requires_client_authentication first, so a public client derives NONE regardless
+ # of jwks_uri.
def _validate_redirect_uris(self):
validator = AllowedURIValidator(