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.

chore(oauth): make client_id the canonical CIMD identifier (#86101)

Rafael Audibertb4f6ec819ea7
diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.py
index ec4f533647f2..f0da89b8db8a 100644
--- a/ee/api/agentic_provisioning/authentication.py
+++ b/ee/api/agentic_provisioning/authentication.py
@@ -10,12 +10,7 @@ from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.request import Request
-from posthog.api.oauth.cimd import (
- enqueue_cimd_refresh_if_stale,
- get_application_by_client_id,
- is_cimd_client_id,
- is_cimd_url_blocked,
-)
+from posthog.api.oauth.cimd import enqueue_cimd_refresh_if_stale, is_cimd_client_id, is_cimd_url_blocked
from posthog.api.oauth.client_assertion import (
ClientAssertionError,
ResolvedClientAssertion,
@@ -166,7 +161,7 @@ class ProvisioningAuthentication(BaseAuthentication):
brought its own proof has to already exist for that proof to mean anything.
"""
try:
- app = get_application_by_client_id(client_id)
+ app = OAuthApplication.objects.get(client_id=client_id)
except OAuthApplication.DoesNotExist:
return None
@@ -179,7 +174,7 @@ class ProvisioningAuthentication(BaseAuthentication):
# again: scope ceiling and jwks_uri edits would freeze at whatever the app was
# promoted with. Async, so this request still serves the app we already have.
try:
- enqueue_cimd_refresh_if_stale(app.cimd_metadata_url or client_id)
+ enqueue_cimd_refresh_if_stale(app.client_id)
except Exception as e:
logger.warning(
"provisioning_cimd_refresh_enqueue_error",
diff --git a/ee/api/agentic_provisioning/test/test_client_registration.py b/ee/api/agentic_provisioning/test/test_client_registration.py
index d98c9c5bfe58..9e517e95e350 100644
--- a/ee/api/agentic_provisioning/test/test_client_registration.py
+++ b/ee/api/agentic_provisioning/test/test_client_registration.py
@@ -101,9 +101,8 @@ class TestClientRegistration(ProvisioningTestBase):
def _make_partner(self, **overrides) -> OAuthApplication:
defaults = {
"name": "Registered Partner",
- "client_id": "opaque-registered-client-id",
+ "client_id": CIMD_URL,
"is_cimd_client": True,
- "cimd_metadata_url": CIMD_URL,
"client_secret": "",
"client_type": OAuthApplication.CLIENT_CONFIDENTIAL,
"jwks_uri": JWKS_URI,
@@ -170,7 +169,7 @@ class TestClientRegistration(ProvisioningTestBase):
# 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()
+ assert not OAuthApplication.objects.filter(client_id=CIMD_URL).exists()
res = self._register({"client_id": CIMD_URL})
@@ -178,7 +177,7 @@ class TestClientRegistration(ProvisioningTestBase):
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)
+ app = OAuthApplication.objects.get(client_id=CIMD_URL)
assert app.client_type == OAuthApplication.CLIENT_CONFIDENTIAL
assert app.is_provisioning_partner
@@ -214,7 +213,7 @@ class TestClientRegistration(ProvisioningTestBase):
self._register({"client_id": CIMD_URL})
- app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_URL)
+ app = OAuthApplication.objects.get(client_id=CIMD_URL)
assert app.client_type == OAuthApplication.CLIENT_PUBLIC
assert app.is_provisioning_partner is False
@@ -248,7 +247,7 @@ class TestClientRegistration(ProvisioningTestBase):
res = self._register({"client_id": CIMD_URL})
assert res.status_code == 200, res.json()
- app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_URL)
+ app = OAuthApplication.objects.get(client_id=CIMD_URL)
assert app.is_provisioning_partner
assert app.provisioning.active
@@ -279,7 +278,7 @@ class TestClientRegistration(ProvisioningTestBase):
checks = {check["name"]: check for check in res.json()["checks"]}
assert checks["provisioning_enabled"]["ok"] is False
assert '"com.posthog": {"provisioning": true}' in checks["provisioning_enabled"]["detail"]
- app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_URL)
+ app = OAuthApplication.objects.get(client_id=CIMD_URL)
assert app.is_provisioning_partner is False
assert app.provisioning.can_create_accounts is False
assert app.client_type == OAuthApplication.CLIENT_PUBLIC
@@ -309,7 +308,7 @@ class TestClientRegistration(ProvisioningTestBase):
# rejection rather than sending the client's owner after a key they already published.
assert '"com.posthog"' not in checks["provisioning_enabled"]["detail"]
assert "metadata_document" in checks["provisioning_enabled"]["detail"]
- app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_URL)
+ app = OAuthApplication.objects.get(client_id=CIMD_URL)
assert app.is_provisioning_partner is False
assert app.provisioning.can_create_accounts is False
assert app.client_type == OAuthApplication.CLIENT_PUBLIC
@@ -325,7 +324,7 @@ class TestClientRegistration(ProvisioningTestBase):
assert res.status_code == 400, res.json()
assert res.json()["error"]["code"] == "registration_failed"
- app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_URL)
+ app = OAuthApplication.objects.get(client_id=CIMD_URL)
assert app.provisioning.active is False
def test_unreachable_jwks_is_reported_as_a_failed_check(self):
diff --git a/ee/api/agentic_provisioning/test/test_private_key_jwt_partner.py b/ee/api/agentic_provisioning/test/test_private_key_jwt_partner.py
index b6f1b33c4950..72cb7b77e275 100644
--- a/ee/api/agentic_provisioning/test/test_private_key_jwt_partner.py
+++ b/ee/api/agentic_provisioning/test/test_private_key_jwt_partner.py
@@ -38,13 +38,10 @@ class TestPrivateKeyJwtPartner(ProvisioningTestBase):
public_jwk.update({"kid": KID, "use": "sig", "alg": "RS256"})
self.jwks = {"keys": [public_jwk]}
- # Mirrors a real CIMD registration: the client knows itself by its metadata URL, while
- # the client_id column holds the opaque value generated at registration.
self.jwt_partner = OAuthApplication.objects.create(
name="JWT Partner",
- client_id="opaque-jwt-partner-client-id",
+ client_id=PARTNER_CLIENT_ID,
is_cimd_client=True,
- cimd_metadata_url=PARTNER_CLIENT_ID,
client_secret="",
client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
jwks_uri=PARTNER_JWKS_URI,
diff --git a/ee/api/agentic_provisioning/test/test_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
index 96aaf447c282..500757fdf639 100644
--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py
+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
@@ -295,8 +295,8 @@ class TestProvisioningAuthentication(ProvisioningTestBase):
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
redirect_uris="http://localhost:8239/callback",
algorithm="RS256",
+ client_id=cimd_url,
is_cimd_client=True,
- cimd_metadata_url=cimd_url,
is_provisioning_partner=True,
_provisioning_config=provisioning_config(
active=True, can_create_accounts=True, can_provision_resources=True
@@ -327,8 +327,8 @@ class TestProvisioningAuthentication(ProvisioningTestBase):
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
redirect_uris="http://localhost:8239/callback",
algorithm="RS256",
+ client_id=cimd_url,
is_cimd_client=True,
- cimd_metadata_url=cimd_url,
is_provisioning_partner=True,
_provisioning_config=provisioning_config(active=False, can_create_accounts=True),
)
@@ -364,8 +364,8 @@ class TestProvisioningAuthentication(ProvisioningTestBase):
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
redirect_uris="http://localhost:8239/callback",
algorithm="RS256",
+ client_id=cimd_url,
is_cimd_client=True,
- cimd_metadata_url=cimd_url,
is_provisioning_partner=True,
_provisioning_config=provisioning_config(
active=True, can_create_accounts=True, can_provision_resources=True
@@ -437,7 +437,7 @@ def _cimd_mock_response(metadata: dict | None, status_code: int = 200):
class TestCimdProvisioningRegistration(ProvisioningTestBase):
def setUp(self):
super().setUp()
- OAuthApplication.objects.filter(cimd_metadata_url=CIMD_PROV_URL).delete()
+ OAuthApplication.objects.filter(client_id=CIMD_PROV_URL).delete()
real_cache.clear()
def _register(self) -> OAuthApplication:
@@ -480,7 +480,7 @@ class TestCimdProvisioningRegistration(ProvisioningTestBase):
mock_get.return_value = _cimd_mock_response(initial)
self._register()
- app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_PROV_URL)
+ app = OAuthApplication.objects.get(client_id=CIMD_PROV_URL)
assert app.scopes == ["insight:read"]
# Partner edits the live metadata to widen the ceiling; the cached doc goes stale.
@@ -517,8 +517,8 @@ class TestCimdProvisioningRegistration(ProvisioningTestBase):
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
redirect_uris="http://127.0.0.1:3000/callback",
algorithm="RS256",
+ client_id=CIMD_PROV_URL,
is_cimd_client=True,
- cimd_metadata_url=CIMD_PROV_URL,
is_provisioning_partner=True,
_provisioning_config=provisioning_config(
active=True,
@@ -545,7 +545,7 @@ class TestCimdProvisioningRegistration(ProvisioningTestBase):
assert post_account_request("[email protected]").status_code == 200
- partner = OAuthApplication.objects.get(cimd_metadata_url=CIMD_PROV_URL)
+ partner = OAuthApplication.objects.get(client_id=CIMD_PROV_URL)
partner.update_provisioning_rate_limits(account_requests=2)
assert post_account_request("[email protected]").status_code == 200
@@ -628,8 +628,8 @@ class TestCimdProvisioningRegistration(ProvisioningTestBase):
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
redirect_uris="http://127.0.0.1:3000/callback",
algorithm="RS256",
+ client_id=url,
is_cimd_client=True,
- cimd_metadata_url=url,
is_provisioning_partner=True,
_provisioning_config=provisioning_config(
active=True, can_create_accounts=True, can_provision_resources=True
@@ -659,8 +659,8 @@ class TestCimdProvisioningRegistration(ProvisioningTestBase):
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
redirect_uris="http://127.0.0.1:3000/callback",
algorithm="RS256",
+ client_id=CIMD_PROV_URL,
is_cimd_client=True,
- cimd_metadata_url=CIMD_PROV_URL,
is_provisioning_partner=True,
_provisioning_config=provisioning_config(
active=True, can_create_accounts=True, can_provision_resources=True
@@ -715,8 +715,8 @@ class TestCimdProvisioningRegistration(ProvisioningTestBase):
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
redirect_uris="http://127.0.0.1:3000/callback",
algorithm="RS256",
+ client_id=CIMD_PROV_URL,
is_cimd_client=True,
- cimd_metadata_url=CIMD_PROV_URL,
is_provisioning_partner=True,
_provisioning_config=provisioning_config(
active=True, can_create_accounts=True, can_provision_resources=True
diff --git a/ee/api/agentic_provisioning/throttling.py b/ee/api/agentic_provisioning/throttling.py
index 0d4ca169103b..24e11c2fe2d8 100644
--- a/ee/api/agentic_provisioning/throttling.py
+++ b/ee/api/agentic_provisioning/throttling.py
@@ -33,6 +33,7 @@ from rest_framework.throttling import BaseThrottle
from rest_framework.views import APIView
from posthog.api.oauth import cimd
+from posthog.models.oauth import OAuthApplication
from posthog.rate_limit import IPThrottle
from ee.api.agentic_provisioning.analytics import capture_provisioning_event
@@ -183,7 +184,7 @@ class CIMDRegistrationThrottle(BaseThrottle):
client_id = request.data.get("client_id") or request.query_params.get("client_id")
if not client_id or not cimd.is_cimd_client_id(client_id):
return True
- if cimd.find_cimd_application(client_id) is not None:
+ if OAuthApplication.objects.filter(client_id=client_id).exists():
return True
# Attribute access (not a from-import) so tests patching
diff --git a/ee/api/agentic_provisioning/views/client_registration.py b/ee/api/agentic_provisioning/views/client_registration.py
index 07d0ab691310..875ae7788ce5 100644
--- a/ee/api/agentic_provisioning/views/client_registration.py
+++ b/ee/api/agentic_provisioning/views/client_registration.py
@@ -29,8 +29,6 @@ from posthog.api.oauth.cimd import (
CIMDFetchError,
CIMDValidationError,
fetch_and_upsert_cimd_application,
- find_cimd_application,
- get_application_by_client_id,
is_cimd_client_id,
is_cimd_url_blocked,
)
@@ -76,7 +74,7 @@ class ClientRegistrationView(ProvisioningAPIView):
)
return Response(
{
- "client_id": app.effective_client_id,
+ "client_id": app.client_id,
"registered": True,
"client_type": app.client_type,
"token_endpoint_auth_method": app.token_endpoint_auth_method.value,
@@ -111,7 +109,7 @@ class ClientRegistrationView(ProvisioningAPIView):
# A non-CIMD client_id has no document to fetch, so it can only have been
# registered by a PostHog admin.
try:
- admin_registered = get_application_by_client_id(client_id)
+ admin_registered = OAuthApplication.objects.get(client_id=client_id)
except OAuthApplication.DoesNotExist:
_record(checks, "client_exists", False, "No client is registered with this client_id")
return None
@@ -125,7 +123,7 @@ class ClientRegistrationView(ProvisioningAPIView):
# An already-registered client keeps working when its document is momentarily
# unreachable, so a failed re-fetch is reported as one failed check rather than
# suppressing every other diagnostic the caller came for.
- existing = find_cimd_application(client_id)
+ existing = OAuthApplication.objects.filter(client_id=client_id).first()
try:
# A CIMD client that has never been used for provisioning carries no provisioning
# config yet, and this is the call that gives it one, so the rest of the namespace
diff --git a/ee/api/agentic_provisioning/views/oauth_token.py b/ee/api/agentic_provisioning/views/oauth_token.py
index 3434ab2501c2..1d5f277f9bde 100644
--- a/ee/api/agentic_provisioning/views/oauth_token.py
+++ b/ee/api/agentic_provisioning/views/oauth_token.py
@@ -68,7 +68,7 @@ def _require_client_authentication(request: Request, oauth_app: OAuthApplication
)
raise ProvisioningError("invalid_client", "client_id and client_secret are required", status=401)
- if not constant_time_compare(credentials.client_id, oauth_app.effective_client_id) or not verify_client_secret(
+ if not constant_time_compare(credentials.client_id, oauth_app.client_id) or not verify_client_secret(
credentials.client_secret, oauth_app.client_secret or ""
):
capture_provisioning_event(
@@ -87,7 +87,7 @@ def _verify_assertion_or_fail(request: Request, oauth_app: OAuthApplication, gra
# The assertion is verified against the app the grant names, so an assertion validly
# signed by a different client cannot be used to redeem this one's grant.
- if not constant_time_compare(assertion.client_id, oauth_app.effective_client_id):
+ if not constant_time_compare(assertion.client_id, oauth_app.client_id):
capture_provisioning_event(
"token_exchange", "client_assertion_mismatch", partner=oauth_app, grant_type=grant_type
)
diff --git a/posthog/admin/admins/oauth_admin.py b/posthog/admin/admins/oauth_admin.py
index b63517792053..7a91a55ba882 100644
--- a/posthog/admin/admins/oauth_admin.py
+++ b/posthog/admin/admins/oauth_admin.py
@@ -402,12 +402,12 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne
@admin.display(description="CIMD URL")
def cimd_url(self, obj: OAuthApplication):
- if not obj.cimd_metadata_url:
+ if not obj.is_cimd_client:
return "–"
return format_html(
'<a href="{}" target="_blank" rel="noopener noreferrer">{}</a>',
- obj.cimd_metadata_url,
- obj.cimd_metadata_url,
+ obj.client_id,
+ obj.client_id,
)
@admin.display(description="Verified", boolean=True, ordering="is_verified")
diff --git a/posthog/api/cimd_verification_token.py b/posthog/api/cimd_verification_token.py
index 1228d712c797..34e116b22c2c 100644
--- a/posthog/api/cimd_verification_token.py
+++ b/posthog/api/cimd_verification_token.py
@@ -276,13 +276,11 @@ class CIMDVerificationTokenViewSet(
# revoke-confirm UX ("partners using this token will no longer be
# recognized") without touching apps that have a different linking
# token.
- for url in OAuthApplication.objects.filter(
+ for client_id in OAuthApplication.objects.filter(
is_cimd_client=True,
organization_id=org_id,
- cimd_metadata_url__isnull=False,
- ).values_list("cimd_metadata_url", flat=True):
- if url:
- cache.delete(_cache_key(url))
+ ).values_list("client_id", flat=True):
+ cache.delete(_cache_key(client_id))
request = self.request
log_activity(
diff --git a/posthog/api/oauth/__init__.py b/posthog/api/oauth/__init__.py
index 5432d9eb687a..919f842db91a 100644
--- a/posthog/api/oauth/__init__.py
+++ b/posthog/api/oauth/__init__.py
@@ -1,6 +1,6 @@
# Re-export for backwards compatibility
from posthog.api.oauth.application import OrganizationOAuthApplicationSerializer, OrganizationOAuthApplicationViewSet
-from posthog.api.oauth.cimd import get_application_by_client_id, is_cimd_client_id
+from posthog.api.oauth.cimd import is_cimd_client_id
from posthog.api.oauth.dcr import (
DCRBurstThrottle,
DCRRequestSerializer,
@@ -43,7 +43,6 @@ __all__ = [
"DynamicClientRegistrationView",
# cimd
"is_cimd_client_id",
- "get_application_by_client_id",
# application
"OrganizationOAuthApplicationSerializer",
"OrganizationOAuthApplicationViewSet",
diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.py
index 929320c3efb6..31721fb15a15 100644
--- a/posthog/api/oauth/cimd.py
+++ b/posthog/api/oauth/cimd.py
@@ -769,7 +769,7 @@ def _update_cimd_application(
# Re-evaluate verification on every refresh so a rotated/removed token
# unlinks the app on the next fetch.
- verification = _resolve_verification_token(metadata, app.cimd_metadata_url or "", capture_ph_event=capture_ph_event)
+ verification = _resolve_verification_token(metadata, app.client_id, capture_ph_event=capture_ph_event)
new_org = verification.organization if verification else None
update_fields = [
"name",
@@ -800,7 +800,7 @@ def _update_cimd_application(
app.full_clean()
app.save(update_fields=update_fields)
except ValidationError as e:
- logger.warning("cimd_update_validation_failed", url=app.cimd_metadata_url, error=str(e))
+ logger.warning("cimd_update_validation_failed", url=app.client_id, error=str(e))
capture_exception(e)
# Refresh from DB so we don't return a mutated-but-unsaved object
app.refresh_from_db()
@@ -817,10 +817,10 @@ def _update_cimd_application(
# just buried in the generic refresh event.
if old_org_id != new_org_id:
capture_ph_event(
- distinct_id=app.cimd_metadata_url or str(app.pk),
+ distinct_id=app.client_id,
event="cimd_application_org_changed",
properties={
- "cimd_url": app.cimd_metadata_url,
+ "cimd_url": app.client_id,
"app_id": str(app.pk),
"old_organization_id": str(old_org_id) if old_org_id else None,
"new_organization_id": str(new_org_id) if new_org_id else None,
@@ -898,7 +898,7 @@ def fetch_and_upsert_cimd_application(
metadata, cache_ttl = fetch_cimd_metadata(url)
cache.set(_cache_key(url), True, timeout=cache_ttl)
- app = find_cimd_application(url)
+ app = OAuthApplication.objects.filter(client_id=url).first()
if app:
updated = _update_cimd_application(
app,
@@ -949,7 +949,7 @@ def fetch_and_upsert_cimd_application(
)
return new_app
except (IntegrityError, ValidationError):
- app = find_cimd_application(url)
+ app = OAuthApplication.objects.filter(client_id=url).first()
if app:
logger.debug("cimd_app_race_resolved", url=url, app_id=str(app.pk))
# The row a concurrent caller won the race with was written from this same
@@ -984,7 +984,7 @@ def get_or_create_cimd_application(url: str) -> OAuthApplication:
- No app: fetch synchronously (must have the app before proceeding)
"""
# Existing client: check cache freshness and if not fresh, fire refresh in the background, returning existing app immediately
- if app := find_cimd_application(url):
+ if app := OAuthApplication.objects.filter(client_id=url).first():
enqueue_cimd_refresh_if_stale(url)
return app
@@ -996,7 +996,7 @@ def get_or_create_cimd_application(url: str) -> OAuthApplication:
# Poll the DB until it appears or we give up.
for _ in range(CIMD_FETCH_TIMEOUT_SECONDS + 1):
time.sleep(1)
- app = find_cimd_application(url)
+ app = OAuthApplication.objects.filter(client_id=url).first()
if app:
return app
@@ -1021,33 +1021,6 @@ def enqueue_cimd_refresh_if_stale(url: str) -> None:
refresh_cimd_metadata_task.delay(url)
-def find_cimd_application(url: str) -> OAuthApplication | None:
- """Resolve a CIMD URL-form client_id to its application, or None.
-
- Reads ``client_id``, which is where a CIMD client's URL now lands on registration,
- and falls back to ``cimd_metadata_url`` for the rows registered before that. Both
- columns are written on create, so the fallback only ever serves older rows, until
- the backfill moves them over."""
- return (
- OAuthApplication.objects.filter(client_id=url).first()
- or OAuthApplication.objects.filter(cimd_metadata_url=url).first()
- )
-
-
-def get_application_by_client_id(client_id: str) -> OAuthApplication:
- """
- Look up an OAuthApplication by client_id, supporting CIMD URL-form client_ids.
-
- Raises OAuthApplication.DoesNotExist if not found.
- """
- if is_cimd_client_id(client_id):
- app = find_cimd_application(client_id)
- if app is None:
- raise OAuthApplication.DoesNotExist
- return app
- return OAuthApplication.objects.get(client_id=client_id)
-
-
def _cimd_provisioning_defaults_for(app: OAuthApplication) -> "ProvisioningConfig":
"""The config a CIMD app gets when it registers itself, layered over whatever it already has.
@@ -1116,10 +1089,10 @@ def apply_provisioning_defaults(app: OAuthApplication) -> OAuthApplication:
# A partner appearing without an admin creating it is the event worth watching for abuse.
# Only the promotion reaches here, so it fires on the transition and nowhere else.
posthoganalytics.capture(
- distinct_id=app.cimd_metadata_url or str(app.pk),
+ distinct_id=app.client_id,
event="cimd_provisioning_partner_registered",
properties={
- "cimd_url": app.cimd_metadata_url,
+ "cimd_url": app.client_id,
"client_name": app.name,
"app_id": str(app.pk),
"partner_tier": app.partner_tier,
diff --git a/posthog/api/oauth/client_assertion.py b/posthog/api/oauth/client_assertion.py
index 1dcb49084182..0c64218b7bed 100644
--- a/posthog/api/oauth/client_assertion.py
+++ b/posthog/api/oauth/client_assertion.py
@@ -278,9 +278,7 @@ def verify_client_assertion(app: OAuthApplication, assertion: str, *, audiences:
raise ClientAssertionError("This client is not registered for private_key_jwt authentication")
key = _select_key_allowing_rotation(app.jwks_uri, assertion)
- # A CIMD client names itself by its metadata URL, not by the opaque client_id column, so
- # that is the identity its assertion carries.
- client_identifier = app.effective_client_id
+ client_identifier = app.client_id
try:
claims = jwt.decode(
diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.py
index d7aa19305116..32d2cc6b2675 100644
--- a/posthog/api/oauth/test_cimd.py
+++ b/posthog/api/oauth/test_cimd.py
@@ -23,12 +23,11 @@ from posthog.api.oauth.cimd import (
CIMDValidationError,
_fetch_lock_key,
_resolve_scopes,
- _update_cimd_application,
+ _resolve_verification_token,
apply_provisioning_defaults,
enqueue_cimd_refresh_if_stale,
fetch_and_upsert_cimd_application,
fetch_cimd_metadata,
- get_application_by_client_id,
get_or_create_cimd_application,
is_cimd_client_id,
refresh_cimd_metadata_task,
@@ -516,7 +515,7 @@ class TestGetOrCreateCimdApplication(APIBaseTest):
mock_get.return_value = _mock_response(metadata2, headers={})
refresh_cimd_metadata_task(VALID_CIMD_URL)
- app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)
+ app = OAuthApplication.objects.get(client_id=VALID_CIMD_URL)
self.assertEqual(app.name, "Updated Name")
self.assertEqual(app.logo_uri, "https://example.com/new-logo.png")
@@ -553,7 +552,7 @@ class TestGetOrCreateCimdApplication(APIBaseTest):
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)
+ app = OAuthApplication.objects.get(client_id=VALID_CIMD_URL)
self.assertEqual(app.name, escape(payload))
self.assertNotIn("<", app.name)
@@ -566,7 +565,7 @@ class TestGetOrCreateCimdApplication(APIBaseTest):
mock_get.side_effect = requests.ConnectionError("DNS failed")
refresh_cimd_metadata_task(VALID_CIMD_URL)
- app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)
+ app = OAuthApplication.objects.get(client_id=VALID_CIMD_URL)
self.assertEqual(app.name, "Original Name")
@patch("posthog.api.oauth.cimd.capture_exception")
@@ -586,46 +585,6 @@ class TestGetOrCreateCimdApplication(APIBaseTest):
mock_capture.assert_called_once_with(error)
-class TestGetApplicationByClientId(APIBaseTest):
- def setUp(self):
- super().setUp()
- self.standard_app = OAuthApplication.objects.create(
- name="Standard App",
- client_id="standard-uuid-id",
- client_secret="secret",
- client_type=OAuthApplication.CLIENT_PUBLIC,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://example.com/callback",
- algorithm="RS256",
- )
- self.cimd_app = OAuthApplication.objects.create(
- name="CIMD App",
- client_secret="secret",
- client_type=OAuthApplication.CLIENT_PUBLIC,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="http://127.0.0.1:3000/callback",
- algorithm="RS256",
- is_cimd_client=True,
- cimd_metadata_url=VALID_CIMD_URL,
- )
-
- def test_standard_uuid_lookup(self):
- result = get_application_by_client_id("standard-uuid-id")
- self.assertEqual(result.pk, self.standard_app.pk)
-
- def test_cimd_url_lookup(self):
- result = get_application_by_client_id(VALID_CIMD_URL)
- self.assertEqual(result.pk, self.cimd_app.pk)
-
- def test_standard_uuid_not_found(self):
- with self.assertRaises(OAuthApplication.DoesNotExist):
- get_application_by_client_id("nonexistent-uuid")
-
- def test_cimd_url_not_found(self):
- with self.assertRaises(OAuthApplication.DoesNotExist):
- get_application_by_client_id("https://unknown.example.com/.well-known/oauth-client-metadata.json")
-
-
@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})
class TestApplyProvisioningDefaults(APIBaseTest):
@patch("posthog.api.oauth.cimd.requests.Session.get")
@@ -847,7 +806,7 @@ class TestCIMDVerificationToken(APIBaseTest):
def test_refresh_moves_the_tier_when_token_added_post_registration(self, mock_get, _url_mock):
mock_get.return_value = _mock_response(_make_metadata(), headers={})
_register_provisioning_partner()
- app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)
+ app = OAuthApplication.objects.get(client_id=VALID_CIMD_URL)
self.assertIsNone(app.organization_id)
self.assertEqual(app.partner_tier, PartnerTier.PUBLIC)
@@ -873,7 +832,7 @@ class TestCIMDVerificationToken(APIBaseTest):
)
mock_get.return_value = _mock_response(_make_metadata(posthog_verification_token=plaintext), headers={})
_register_provisioning_partner()
- app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)
+ app = OAuthApplication.objects.get(client_id=VALID_CIMD_URL)
self.assertEqual(app.organization_id, self.organization.id)
self.assertEqual(app.partner_tier, PartnerTier.PUBLIC_ATTESTED)
@@ -889,7 +848,7 @@ class TestCIMDVerificationToken(APIBaseTest):
def test_refresh_preserves_admin_custom_rate_limit(self, mock_get, _url_mock):
mock_get.return_value = _mock_response(_make_metadata(), headers={})
_register_provisioning_partner()
- app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)
+ app = OAuthApplication.objects.get(client_id=VALID_CIMD_URL)
app.update_provisioning_rate_limits(account_requests=250)
_, plaintext = create_cimd_verification_token(
organization=self.organization, label="Post-admin-override", cimd_url=VALID_CIMD_URL, created_by=self.user
@@ -1058,28 +1017,21 @@ class TestCIMDVerificationRejectedCaptureEvent(APIBaseTest):
]
self.assertEqual(len(rejected), 1)
- def test_empty_app_metadata_url_rejects_as_app_url_missing_not_mismatch(self, _url_mock):
+ def test_missing_app_url_rejects_as_app_url_missing_not_mismatch(self, _url_mock):
+ # url_mismatch is the copied-token signal, so a resolution with no URL to compare
+ # against has to report its own reason instead of landing in that metric.
_, plaintext = create_cimd_verification_token(
organization=self.organization, label="Bound", cimd_url=VALID_CIMD_URL, created_by=self.user
)
- app = OAuthApplication.objects.create(
- name="CIMD App",
- client_secret="",
- client_type=OAuthApplication.CLIENT_PUBLIC,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="http://127.0.0.1:3000/callback",
- algorithm="RS256",
- is_cimd_client=True,
- cimd_metadata_url=None,
- )
mock_capture = MagicMock()
- _update_cimd_application(
- app,
+ resolved = _resolve_verification_token(
cast(CIMDMetadataDocument, _make_metadata(posthog_verification_token=plaintext)),
+ "",
capture_ph_event=mock_capture,
)
+ self.assertIsNone(resolved)
rejected = [
call
for call in mock_capture.call_args_list
@@ -1133,7 +1085,7 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
- app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)
+ app = OAuthApplication.objects.get(client_id=VALID_CIMD_URL)
self.assertTrue(app.is_cimd_client)
self.assertEqual(app.name, "Test MCP Client")
self.assertEqual(len(_document_fetches(mock_get)), 1)
@@ -1152,7 +1104,7 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):
self.assertEqual(response.status_code, 200)
self.assertEqual(_document_fetches(mock_get), [])
- self.assertEqual(OAuthApplication.objects.filter(cimd_metadata_url=VALID_CIMD_URL).count(), 1)
+ self.assertEqual(OAuthApplication.objects.filter(client_id=VALID_CIMD_URL).count(), 1)
@patch("posthog.api.oauth.cimd.requests.Session.get")
def test_cimd_fetch_failure_rejects_new_client(self, mock_get, _url_mock):
@@ -1246,7 +1198,7 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):
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)
+ app = OAuthApplication.objects.get(client_id=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.
@@ -1520,7 +1472,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):
with self.assertRaises(CIMDValidationError):
fetch_and_upsert_cimd_application(VALID_CIMD_URL)
- self.assertFalse(OAuthApplication.objects.filter(cimd_metadata_url=VALID_CIMD_URL).exists())
+ self.assertFalse(OAuthApplication.objects.filter(client_id=VALID_CIMD_URL).exists())
# On refresh, a doc whose scopes all strip out is rejected and the existing ceiling is
# left untouched (fail-closed) rather than widened to the default.
diff --git a/posthog/api/oauth/test_hogli_metadata.py b/posthog/api/oauth/test_hogli_metadata.py
index b7801bdcdc53..8bf88a5c4000 100644
--- a/posthog/api/oauth/test_hogli_metadata.py
+++ b/posthog/api/oauth/test_hogli_metadata.py
@@ -10,7 +10,7 @@ from django.test import SimpleTestCase, override_settings
from oauth2_provider.models import AbstractApplication
from parameterized import parameterized
-from posthog.api.oauth.cimd import fetch_and_upsert_cimd_application, get_application_by_client_id
+from posthog.api.oauth.cimd import fetch_and_upsert_cimd_application
from posthog.api.oauth.hogli_metadata import HOGLI_LOGO_URI, HOGLI_SCOPES
from posthog.models.oauth import is_loopback_host
from posthog.scopes import UNPRIVILEGED_SCOPES
@@ -99,7 +99,7 @@ class TestHogliClientMetadataRegistration(APIBaseTest):
assert app is not None
assert app.is_cimd_client
- assert app.cimd_metadata_url == client_id
+ assert app.client_id == client_id
assert app.name == "hogli CLI for PostHog"
assert app.client_type == AbstractApplication.CLIENT_PUBLIC
assert app.authorization_grant_type == AbstractApplication.GRANT_AUTHORIZATION_CODE
@@ -107,8 +107,6 @@ class TestHogliClientMetadataRegistration(APIBaseTest):
assert set(app.scopes) == set(HOGLI_SCOPES)
assert app.logo_uri == HOGLI_LOGO_URI
- assert get_application_by_client_id(client_id).pk == app.pk
-
@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})
@patch("posthog.api.oauth.cimd.requests.Session.get")
def test_registration_leaves_verification_to_a_human(self, mock_get, _url_mock):
diff --git a/posthog/api/oauth/test_raycast_metadata.py b/posthog/api/oauth/test_raycast_metadata.py
index 7ad7b83ae7be..b86fc637c3f2 100644
--- a/posthog/api/oauth/test_raycast_metadata.py
+++ b/posthog/api/oauth/test_raycast_metadata.py
@@ -9,7 +9,7 @@ from django.test import SimpleTestCase, override_settings
from oauth2_provider.models import AbstractApplication
from parameterized import parameterized
-from posthog.api.oauth.cimd import fetch_and_upsert_cimd_application, get_application_by_client_id
+from posthog.api.oauth.cimd import fetch_and_upsert_cimd_application
from posthog.api.oauth.raycast_metadata import RAYCAST_SCOPES
from posthog.scopes import UNPRIVILEGED_SCOPES
@@ -83,13 +83,10 @@ class TestRaycastClientMetadataRegistration(APIBaseTest):
assert app is not None
assert app.is_cimd_client
- assert app.cimd_metadata_url == client_id
+ assert app.client_id == client_id
assert app.name == "Raycast extension for PostHog"
assert app.client_type == AbstractApplication.CLIENT_PUBLIC
assert app.authorization_grant_type == AbstractApplication.GRANT_AUTHORIZATION_CODE
assert app.redirect_uris == " ".join(document["redirect_uris"])
assert set(app.scopes) == set(RAYCAST_SCOPES)
assert app.organization is None
-
- # The authorize-time lookup resolves the URL-form client_id back to this app.
- assert get_application_by_client_id(client_id).pk == app.pk
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index db6b37a422e3..9fab40b24df6 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -555,12 +555,12 @@ class TestOAuthAPI(APIBaseTest):
self,
*,
slug: str,
- cimd_metadata_url: str,
+ cimd_url: str,
name: str,
) -> tuple[OAuthApplication, OAuthGrant]:
app = OAuthApplication.objects.create(
name=name,
- client_id=f"cimd-client-id-{slug}",
+ client_id=cimd_url,
client_secret="",
client_type=OAuthApplication.CLIENT_PUBLIC,
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
@@ -568,7 +568,6 @@ class TestOAuthAPI(APIBaseTest):
user=self.user,
algorithm="RS256",
is_cimd_client=True,
- cimd_metadata_url=cimd_metadata_url,
)
grant = OAuthGrant.objects.create(
application=app,
@@ -585,10 +584,6 @@ class TestOAuthAPI(APIBaseTest):
return app, grant
def _exchange_code_for_token(self, app: OAuthApplication, grant: OAuthGrant):
- # Uses the internal UUID client_id rather than cimd_metadata_url so we
- # exercise the validator-level suppression in _should_skip_refresh_token
- # without also invoking the CIMD fetch/validate path (which would require
- # HTTP mocks). Both entry paths converge on the same in-memory client.
return self.post(
"/oauth/token/",
{
@@ -609,7 +604,7 @@ class TestOAuthAPI(APIBaseTest):
def test_wizard_cimd_client_does_not_issue_refresh_token(self, region: str, wizard_cimd_url: str):
wizard_app, grant = self._create_cimd_app_and_grant(
slug=f"wizard-{region}",
- cimd_metadata_url=wizard_cimd_url,
+ cimd_url=wizard_cimd_url,
name="PostHog Wizard",
)
@@ -627,7 +622,7 @@ class TestOAuthAPI(APIBaseTest):
# keep the default refresh-token behavior.
other_app, grant = self._create_cimd_app_and_grant(
slug="other-cimd",
- cimd_metadata_url="https://example.com/oauth/client-metadata",
+ cimd_url="https://example.com/oauth/client-metadata",
name="Third-Party CIMD Client",
)
@@ -649,7 +644,7 @@ class TestOAuthAPI(APIBaseTest):
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
app = OAuthApplication.objects.create(
name="Private Key JWT CIMD Client",
- client_id="cimd-pkjwt-client-id",
+ client_id=cimd_url if is_cimd_client else "pkjwt-non-cimd-client-id",
client_secret="",
client_type=client_type,
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
@@ -657,7 +652,6 @@ class TestOAuthAPI(APIBaseTest):
user=self.user,
algorithm="RS256",
is_cimd_client=is_cimd_client,
- cimd_metadata_url=cimd_url if is_cimd_client else None,
jwks_uri="https://partner.example.com/.well-known/jwks.json",
)
grant = OAuthGrant.objects.create(
@@ -678,8 +672,8 @@ class TestOAuthAPI(APIBaseTest):
now = int(timezone.now().timestamp())
assertion = jwt.encode(
{
- "iss": app.cimd_metadata_url,
- "sub": app.cimd_metadata_url,
+ "iss": app.client_id,
+ "sub": app.client_id,
"aud": "https://us.posthog.com/oauth/token/",
"jti": "pkjwt-assertion-1",
"iat": now,
@@ -728,7 +722,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertIn("access_token", response.json())
# Token exchanges are the only traffic a refresh-grant-only client sends, so the
# assertion path has to be what keeps its CIMD registration fresh.
- refresh.assert_called_once_with(app.cimd_metadata_url)
+ refresh.assert_called_once_with(app.client_id)
@freeze_time("2025-01-01 00:00:00")
@override_settings(SITE_URL="https://us.posthog.com")
@@ -796,7 +790,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(issued[0].kwargs["properties"]["client_auth_method"], "none")
# Fallback exchanges are the only requests a client living on `none` sends, so
# they must keep the CIMD document fresh the same way the assertion path does.
- mock_refresh.assert_called_once_with(app.cimd_metadata_url)
+ mock_refresh.assert_called_once_with(app.client_id)
@override_settings(SITE_URL="https://us.posthog.com")
def test_non_cimd_confidential_client_rejected_without_assertion(self):
@@ -3696,9 +3690,6 @@ class TestOAuthAPI(APIBaseTest):
@parameterized.expand(["access_token", "refresh_token"])
@override_settings(SITE_URL="https://us.posthog.com")
def test_introspection_with_client_assertion_allows_own_token(self, token_type):
- # A CIMD client's wire identity is its cimd_metadata_url (effective_client_id), not
- # the opaque client_id PostHog assigns at registration. Comparing against the opaque
- # value would reject a CIMD client introspecting even its own token.
app, _grant, private_key = self._create_private_key_jwt_app_and_grant()
access_token, refresh_token = self._create_token_pair_for_app(app)
token = access_token if token_type == "access_token" else refresh_token
@@ -3716,7 +3707,7 @@ class TestOAuthAPI(APIBaseTest):
"/oauth/introspect/",
{
"token": token.token,
- "client_id": app.cimd_metadata_url,
+ "client_id": app.client_id,
"client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER,
"client_assertion": assertion,
},
@@ -5011,7 +5002,7 @@ class TestOAuthFunnelInstrumentation(APIBaseTest):
side_effect=OperationalError("query_wait_timeout"),
),
patch(
- "posthog.api.oauth.views.get_application_by_client_id",
+ "posthog.api.oauth.views.OAuthApplication.objects.get",
side_effect=OperationalError("connection failed"),
),
patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture,
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 29da33ab25be..b8d1efa367c1 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -47,8 +47,6 @@ from posthog.api.oauth.cimd import (
CIMDFetchError,
CIMDValidationError,
enqueue_cimd_refresh_if_stale,
- find_cimd_application,
- get_application_by_client_id,
get_or_create_cimd_application,
is_cimd_client_id,
)
@@ -103,7 +101,7 @@ EXTENDED_ACCESS_TOKEN_EXPIRE_SECONDS = 60 * 60 * 24 * 7 # 7 days
# Clients for which we must NOT issue refresh tokens. The token response will omit
# "refresh_token" and no OAuthRefreshToken row will be created. Entries are matched
-# against the app's cimd_metadata_url for CIMD clients, and against client_id otherwise.
+# against the app's client_id, which for a CIMD client is its metadata-document URL.
CLIENT_IDS_WITHOUT_REFRESH_TOKEN: frozenset[str] = frozenset(
{
# PostHog Wizard CLI (CIMD) — short-lived auth, no persistent session needed.
@@ -194,7 +192,7 @@ def _oauth_app_event_properties(application: OAuthApplication) -> dict:
"registration_type": _registration_type(application),
"is_verified": application.is_verified,
"is_first_party": application.is_first_party,
- **({"cimd_url": application.cimd_metadata_url} if application.is_cimd_client else {}),
+ **({"cimd_url": application.client_id} if application.is_cimd_client else {}),
}
@@ -372,21 +370,14 @@ class OAuthValidator(OAuth2Validator):
if self._get_impersonator_id(request) is not None:
return True
- # CIMD clients expose their canonical id via cimd_metadata_url (the model's
- # client_id is an auto-generated UUID for those). Gate on is_cimd_client so
- # a stray cimd_metadata_url on a non-CIMD app can't flip the behavior.
client_key: str | None = None
- if not hasattr(request, "client") or not request.client:
- client_key = None
- elif getattr(request.client, "is_cimd_client", False):
- client_key = getattr(request.client, "cimd_metadata_url", None)
- else:
+ if hasattr(request, "client") and request.client:
client_key = getattr(request.client, "client_id", None)
return bool(client_key and client_key in CLIENT_IDS_WITHOUT_REFRESH_TOKEN)
def _load_application(self, client_id, request):
"""
- Load the application from the database, supporting CIMD URL-form client_ids.
+ Load the application from the database.
Does NOT fetch metadata — that only happens in validate_client_id().
"""
@@ -397,11 +388,7 @@ class OAuthValidator(OAuth2Validator):
if request.client:
return request.client
- app: OAuthApplication | None = None
- if is_cimd_client_id(client_id):
- app = find_cimd_application(client_id)
- else:
- app = OAuthApplication.objects.filter(client_id=client_id).first()
+ app = OAuthApplication.objects.filter(client_id=client_id).first()
if app is None or not app.is_usable(request):
return None
@@ -451,8 +438,8 @@ class OAuthValidator(OAuth2Validator):
app = self._credentialless_cimd_private_key_jwt_client(request)
if app is None:
return False
- if app.cimd_metadata_url:
- self._enqueue_cimd_metadata_refresh(app.cimd_metadata_url, app.client_id)
+ if app.is_cimd_client:
+ self._enqueue_cimd_metadata_refresh(app.client_id)
return True
def _credentialless_cimd_private_key_jwt_client(self, request) -> OAuthApplication | None:
@@ -495,13 +482,13 @@ class OAuthValidator(OAuth2Validator):
return super().authenticate_client(request, *args, **kwargs)
@staticmethod
- def _enqueue_cimd_metadata_refresh(cimd_metadata_url: str, client_id: str) -> None:
+ def _enqueue_cimd_metadata_refresh(client_id: str) -> None:
"""Token and refresh exchanges never pass through validate_client_id, which is
where a CIMD document is normally re-read, so a client living on refresh grants
alone would otherwise keep a stale auth method or key source forever.
Best-effort: a broker outage must not fail an otherwise valid exchange."""
try:
- enqueue_cimd_refresh_if_stale(cimd_metadata_url)
+ enqueue_cimd_refresh_if_stale(client_id)
except Exception as e:
logger.warning(
"oauth_cimd_refresh_enqueue_error",
@@ -530,8 +517,8 @@ class OAuthValidator(OAuth2Validator):
if app is None or not app.jwks_uri:
return False
- if app.is_cimd_client and app.cimd_metadata_url:
- self._enqueue_cimd_metadata_refresh(app.cimd_metadata_url, assertion.client_id)
+ if app.is_cimd_client:
+ self._enqueue_cimd_metadata_refresh(app.client_id)
try:
verify_client_assertion(
@@ -1297,7 +1284,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
# Must happen here (not in the OAuthValidator) because the validator
# only receives an oauthlib Request which lacks request.META for IP extraction.
client_id = request.query_params.get("client_id")
- if is_cimd_client_id(client_id) and find_cimd_application(client_id) is None:
+ if is_cimd_client_id(client_id) and not OAuthApplication.objects.filter(client_id=client_id).exists():
for throttle_cls in CIMD_THROTTLE_CLASSES:
throttle = throttle_cls()
if not throttle.allow_request(request, view=self):
@@ -1319,7 +1306,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
client_id = request.query_params.get("client_id")
if client_id:
try:
- error_application = get_application_by_client_id(client_id)
+ error_application = OAuthApplication.objects.get(client_id=client_id)
except OAuthApplication.DoesNotExist:
pass
return self.error_response(error, application=error_application, state=request.query_params.get("state"))
@@ -1330,7 +1317,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
# Get application and scope details
try:
- application = get_application_by_client_id(credentials["client_id"])
+ application = OAuthApplication.objects.get(client_id=credentials["client_id"])
except OAuthApplication.DoesNotExist:
return Response({"error": "Invalid client_id"}, status=status.HTTP_400_BAD_REQUEST)
@@ -1455,7 +1442,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
try:
- application = get_application_by_client_id(serializer.validated_data["client_id"])
+ application = OAuthApplication.objects.get(client_id=serializer.validated_data["client_id"])
except OAuthApplication.DoesNotExist:
logger.warning("oauth_authorize_invalid_client", client_id=serializer.validated_data["client_id"])
return Response({"error": "Invalid client_id"}, status=status.HTTP_400_BAD_REQUEST)
@@ -1732,7 +1719,7 @@ class OAuthTokenView(TokenView):
**(get_region_info() or {}),
}
try:
- application = get_application_by_client_id(client_id)
+ application = OAuthApplication.objects.get(client_id=client_id)
except (OAuthApplication.DoesNotExist, DatabaseError):
pass
else:
@@ -2079,7 +2066,7 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
return True
def _client_credentials_client_id(self, request) -> str | None:
- """The effective_client_id the server verified via client credentials, or None.
+ """The client_id the server verified via client credentials, or None.
None means the request reached us through the bearer-token path instead (self-
introspection or the `introspection` scope), where ClientProtectedResourceMixin.dispatch
@@ -2091,7 +2078,7 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
return None
client = getattr(request, "oauth_authenticated_client", None)
- return client.effective_client_id if client is not None else None
+ return client.client_id if client is not None else None
def get_token_response(self, request, token_value=None):
"""
@@ -2128,13 +2115,8 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
if access_token:
# A client-credentials caller may only introspect its own tokens. Being
# confidential is not a meaningful barrier on its own, since /oauth/register/
- # issues a confidential client_id and secret to anyone who asks. Compared against
- # effective_client_id, not client_id, since a CIMD client's wire identity is its
- # metadata URL, never the opaque client_id column.
- if (
- credential_client_id
- and getattr(access_token.application, "effective_client_id", None) != credential_client_id
- ):
+ # issues a confidential client_id and secret to anyone who asks.
+ if credential_client_id and getattr(access_token.application, "client_id", None) != credential_client_id:
return JsonResponse({"active": False}, status=200)
# RFC 7662 Section 2.2: expired tokens MUST return {"active": false}
if not access_token.is_valid():
@@ -2160,10 +2142,7 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
refresh_token = None
if refresh_token:
- if (
- credential_client_id
- and getattr(refresh_token.application, "effective_client_id", None) != credential_client_id
- ):
+ if credential_client_id and getattr(refresh_token.application, "client_id", None) != credential_client_id:
return JsonResponse({"active": False}, status=200)
# Refresh tokens lack scope and exp fields on AbstractRefreshToken,
# so we only return the fields that are available
diff --git a/posthog/migrations/1324_backfill_cimd_client_id.py b/posthog/migrations/1324_backfill_cimd_client_id.py
new file mode 100644
index 000000000000..656c438115f2
--- /dev/null
+++ b/posthog/migrations/1324_backfill_cimd_client_id.py
@@ -0,0 +1,29 @@
+from django.db import migrations
+from django.db.models import F
+
+
+def backfill_cimd_client_id(apps, schema_editor):
+ """Move each CIMD app's wire identifier (its metadata-document URL) into client_id.
+
+ CIMD clients have always identified themselves by their metadata URL; the client_id
+ column held an unused generated value while the URL lived in cimd_metadata_url.
+ Uniqueness carries over: cimd_metadata_url is itself unique, and a URL can never
+ collide with a generated opaque client_id.
+ """
+ OAuthApplication = apps.get_model("posthog", "OAuthApplication")
+ OAuthApplication.objects.filter(is_cimd_client=True, cimd_metadata_url__isnull=False).exclude(
+ cimd_metadata_url=""
+ ).update(client_id=F("cimd_metadata_url"))
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1323_proxyrecord_root_redirect_url"),
+ ]
+
+ operations = [
+ # Reverse is a no-op: the code this rolls back to resolves a CIMD app by
+ # cimd_metadata_url, which stays populated, so the discarded generated client_id
+ # values do not need restoring.
+ migrations.RunPython(backfill_cimd_client_id, migrations.RunPython.noop),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 2266cf277bc2..07f3911c94a5 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1323_proxyrecord_root_redirect_url
+1324_backfill_cimd_client_id
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.py
index 1d1e6720dd22..0527923e4dbc 100644
--- a/posthog/models/oauth.py
+++ b/posthog/models/oauth.py
@@ -81,8 +81,8 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignore
id: models.UUIDField = models.UUIDField(primary_key=True, default=UUIDT, editable=False)
# Overrides the abstract base's max_length=100 so the column can hold a CIMD
- # metadata-document URL as the client's identifier (sized to match cimd_metadata_url).
- # Non-CIMD clients keep the generated opaque value.
+ # metadata-document URL as the client's identifier. Non-CIMD clients keep the
+ # generated opaque value.
client_id: models.CharField = models.CharField(
max_length=2048, unique=True, default=generate_client_id, db_index=True
)
@@ -190,6 +190,9 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignore
verbose_name="Is CIMD client",
help_text="True if this client was registered via Client ID Metadata Document (CIMD)",
)
+ # Superseded by client_id, which now holds this same URL. Nothing resolves a client
+ # through it any more; it stays written on create so a rollback to code that does keeps
+ # working, and is dropped once that window closes.
cimd_metadata_url: models.URLField = models.URLField(
max_length=2048,
null=True,
@@ -314,21 +317,6 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignore
# inferring the method from what a request happens to present would let anyone act as a
# confidential client by presenting nothing at all.
- @property
- def effective_client_id(self) -> str:
- """The identifier this client uses for itself on the wire.
-
- For a CIMD client that is its metadata URL, which is what the client sends and what it
- names itself by in a signed assertion; the ``client_id`` column holds an opaque value
- generated at registration. For every other client the two are the same.
-
- Gated on ``is_cimd_client`` so a stray ``cimd_metadata_url`` on a non-CIMD app cannot
- change which identifier an assertion's ``iss``/``sub`` are checked against.
- """
- if self.is_cimd_client and self.cimd_metadata_url:
- return self.cimd_metadata_url
- return self.client_id
-
@property
def requires_client_authentication(self) -> bool:
"""Whether this client must prove itself, i.e. is confidential (RFC 6749 section 3.2.1)."""
@@ -934,7 +922,7 @@ def generate_random_token_cimd_verification() -> str:
# unparseable-input branch. Issuance validates and normalizes before storing (see
# `CIMDVerificationTokenCreateSerializer` in posthog/api/cimd_verification_token.py), so no
# stored `CIMDVerificationToken.cimd_url` can ever equal this — it exists only to give the
-# refresh path (which normalizes `OAuthApplication.cimd_metadata_url` read straight from the
+# refresh path (which normalizes `OAuthApplication.client_id` read straight from the
# database, unrevalidated) a value to compare against instead of raising.
UNNORMALIZABLE_CIMD_URL = "\x00unnormalizable"
@@ -1122,11 +1110,11 @@ def _block_cimd_url_on_application_delete(sender, instance: OAuthApplication, **
# Auto-blocklist a CIMD URL when its app is deleted, so a metadata refresh
# can't immediately recreate the same partner. Admin can explicitly
# unblock via unblock_cimd_url if they want to allow re-registration.
- if not (instance.is_cimd_client and instance.cimd_metadata_url):
+ if not instance.is_cimd_client:
return
from posthog.api.oauth.cimd import block_cimd_url
block_cimd_url(
- instance.cimd_metadata_url,
+ instance.client_id,
reason=f"Auto-blocked on deletion of OAuthApplication {instance.pk}",
)
diff --git a/posthog/models/test/test_oauth.py b/posthog/models/test/test_oauth.py
index 8480adcf25f5..09167651cd6e 100644
--- a/posthog/models/test/test_oauth.py
+++ b/posthog/models/test/test_oauth.py
@@ -109,7 +109,6 @@ class TestOAuthModels(TestCase):
"CIMD Split",
"cimd_split_client",
is_cimd_client=True,
- cimd_metadata_url="https://example.com/oauth-client",
scopes=["insight:read"],
optional_scopes=["dashboard:read"],
)
diff --git a/posthog/test/test_migration_1324.py b/posthog/test/test_migration_1324.py
new file mode 100644
index 000000000000..31c0d58d78b4
--- /dev/null
+++ b/posthog/test/test_migration_1324.py
@@ -0,0 +1,42 @@
+from typing import Any
+
+from posthog.test.base import TestMigrations
+
+LEGACY_URL = "https://legacy.example.com/.well-known/oauth-client-metadata"
+MOVED_URL = "https://moved.example.com/.well-known/oauth-client-metadata"
+STRAY_URL = "https://stray.example.com/.well-known/oauth-client-metadata"
+
+
+class BackfillCimdClientIdMigrationTest(TestMigrations):
+ migrate_from = "1323_proxyrecord_root_redirect_url"
+ migrate_to = "1324_backfill_cimd_client_id"
+
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUpBeforeMigration(self, apps: Any) -> None:
+ OAuthApplication = apps.get_model("posthog", "OAuthApplication")
+ self.OAuthApplication = OAuthApplication
+
+ def create(client_id: str, **kwargs: Any) -> Any:
+ return OAuthApplication.objects.create(
+ name=client_id,
+ client_id=client_id,
+ client_secret="",
+ client_type="public",
+ authorization_grant_type="authorization-code",
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ **kwargs,
+ )
+
+ self.legacy_cimd = create("generated-legacy", is_cimd_client=True, cimd_metadata_url=LEGACY_URL)
+ # Registered by the code that already writes the URL into client_id.
+ self.already_moved = create(MOVED_URL, is_cimd_client=True, cimd_metadata_url=MOVED_URL)
+ # A stray URL on a non-CIMD row must not become its client_id: the app authenticates
+ # under the opaque id an admin gave it.
+ self.non_cimd = create("opaque-admin-registered", is_cimd_client=False, cimd_metadata_url=STRAY_URL)
+
+ def test_only_cimd_apps_take_their_metadata_url_as_client_id(self) -> None:
+ assert self.OAuthApplication.objects.get(pk=self.legacy_cimd.pk).client_id == LEGACY_URL
+ assert self.OAuthApplication.objects.get(pk=self.already_moved.pk).client_id == MOVED_URL
+ assert self.OAuthApplication.objects.get(pk=self.non_cimd.pk).client_id == "opaque-admin-registered"
diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
index 017f23c3892b..17d46f5c097e 100644
--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
@@ -34,7 +34,7 @@
e.`$window_id` AS `$window_id`,
if(equals(e.event, 'user signed up'), 1, 0) AS step_0,
if(equals(e.event, 'user did things'), 1, 0) AS step_1,
- ([e__person.properties___fish] AS value) AS prop_basic,
+ ([replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', '')] AS value) AS prop_basic,
prop_basic AS prop
FROM events AS e
LEFT OUTER JOIN
@@ -44,16 +44,6 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0)), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -121,17 +111,7 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
GROUP BY breakdown
@@ -188,8 +168,8 @@
e.uuid AS uuid,
e.`$session_id` AS `$session_id`,
e.`$window_id` AS `$window_id`,
- if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_0,
- if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_1
+ if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_0,
+ if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_1
FROM events AS e
LEFT OUTER JOIN
(SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
@@ -198,16 +178,6 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up'))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -324,24 +294,7 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
@@ -373,24 +326,7 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)