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.

refactor(oauth): remove the CIMD URL blocklist (#93605)

Matt Brooker0da126b11c2e
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index e216e0aaef8f..10e4d775afee 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -220,9 +220,6 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"ExplicitTeamMembership",
# --- Other internal (no user-facing lookup by ID) ---
"AlertCheck",
- # Global CIMD URL blocklist - queried by `cimd_url` (unique), never by user-supplied ID.
- # `created_by` is for audit only.
- "CIMDBlocklistEntry",
"CohortCalculationHistory",
"ColumnConfiguration",
"DataDeletionRequest",
diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.py
index f0da89b8db8a..32ee2719dadf 100644
--- a/ee/api/agentic_provisioning/authentication.py
+++ b/ee/api/agentic_provisioning/authentication.py
@@ -10,7 +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, is_cimd_client_id, is_cimd_url_blocked
+from posthog.api.oauth.cimd import enqueue_cimd_refresh_if_stale
from posthog.api.oauth.client_assertion import (
ClientAssertionError,
ResolvedClientAssertion,
@@ -194,8 +194,6 @@ class ProvisioningAuthentication(BaseAuthentication):
explicit call to client_registration, so an unknown client_id simply does not resolve
and the caller is pointed there.
"""
- if is_cimd_client_id(client_id) and is_cimd_url_blocked(client_id):
- return None
return self._resolve_partner(client_id)
diff --git a/ee/api/agentic_provisioning/test/test_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
index 8bed1d6303ec..adfec083db71 100644
--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py
+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
@@ -7,7 +7,7 @@ from django.core.cache import cache as real_cache
from parameterized import parameterized
-from posthog.api.oauth.cimd import _blocked_key, _cache_key, fetch_and_upsert_cimd_application
+from posthog.api.oauth.cimd import _cache_key, fetch_and_upsert_cimd_application
from posthog.models.oauth import OAuthApplication
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.user import User
@@ -372,8 +372,6 @@ class TestProvisioningAuthentication(ProvisioningTestBase):
),
)
self.addCleanup(real_cache.delete, _cache_key(cimd_url))
- # _identify_pkce_partner warms the blocklist cache with a 1-year TTL; clear it too.
- self.addCleanup(real_cache.delete, _blocked_key(cimd_url))
if cache_is_fresh:
real_cache.set(_cache_key(cimd_url), True, timeout=300)
@@ -684,56 +682,3 @@ class TestCimdProvisioningRegistration(ProvisioningTestBase):
user = User.objects.get(email=email)
org = user.organization_memberships.first().organization
assert org.name == f"Partner App ({email})"
-
- def test_blocked_cimd_url_returns_unauthorized(self, _url_mock):
- from posthog.api.oauth.cimd import block_cimd_url
-
- block_cimd_url(CIMD_PROV_URL)
-
- _, challenge = self._pkce_pair()
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data={
- "id": "req_blocked",
- "email": "[email protected]",
- "client_id": CIMD_PROV_URL,
- "code_challenge": challenge,
- "code_challenge_method": "S256",
- },
- content_type="application/json",
- )
- assert res.status_code == 401
-
- @patch("posthog.api.oauth.cimd.refresh_cimd_metadata_task")
- def test_blocked_cimd_url_with_existing_app_returns_unauthorized(self, mock_refresh, _url_mock):
- from posthog.api.oauth.cimd import block_cimd_url
-
- OAuthApplication.objects.create(
- name="Blocked 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",
- client_id=CIMD_PROV_URL,
- is_cimd_client=True,
- is_provisioning_partner=True,
- _provisioning_config=provisioning_config(
- active=True, can_create_accounts=True, can_provision_resources=True
- ),
- )
- block_cimd_url(CIMD_PROV_URL)
-
- _, challenge = self._pkce_pair()
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data={
- "id": "req_blocked_existing",
- "email": "[email protected]",
- "client_id": CIMD_PROV_URL,
- "code_challenge": challenge,
- "code_challenge_method": "S256",
- },
- content_type="application/json",
- )
- assert res.status_code == 401
diff --git a/ee/api/agentic_provisioning/views/client_registration.py b/ee/api/agentic_provisioning/views/client_registration.py
index 875ae7788ce5..ca6352fb7f72 100644
--- a/ee/api/agentic_provisioning/views/client_registration.py
+++ b/ee/api/agentic_provisioning/views/client_registration.py
@@ -9,9 +9,9 @@ individually so a broken setup names its own cause instead of surfacing as a bar
Deliberately unauthenticated: a partner that has not registered yet has no credential to
present, so requiring one would make the endpoint useless for the case it exists to serve.
What that exposes is bounded on two counts. The only URL a caller can make us dereference is
-the one it is claiming as its own client_id, which goes through the same SSRF validation, DNS
-check and blocklist as any other CIMD fetch, and it is rate limited per client_id, per IP and
-per domain because the fetch is synchronous. The capabilities that registration grants come
+the one it is claiming as its own client_id, which goes through the same SSRF validation and
+DNS check as any other CIMD fetch, and it is rate limited per client_id, per IP and per domain
+because the fetch is synchronous. The capabilities that registration grants come
from the fetched document declaring the opt-in, never from the request, so the caller decides
which client_id we look at and nothing else. Without that, sending a third party's client_id
would be enough to conscript its OAuth client into a provisioning partner, since a CIMD
@@ -30,7 +30,6 @@ from posthog.api.oauth.cimd import (
CIMDValidationError,
fetch_and_upsert_cimd_application,
is_cimd_client_id,
- is_cimd_url_blocked,
)
from posthog.api.oauth.client_assertion import ClientAssertionError, describe_jwks, verify_client_assertion
from posthog.models.oauth import OAuthApplication
@@ -116,10 +115,6 @@ class ClientRegistrationView(ProvisioningAPIView):
_record(checks, "client_exists", True, "Registered by a PostHog admin")
return self._require_partner(admin_registered, checks)
- if is_cimd_url_blocked(client_id):
- _record(checks, "metadata_document", False, "This client_id has been blocked")
- return None
-
# 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.
diff --git a/posthog/admin/admins/oauth_admin.py b/posthog/admin/admins/oauth_admin.py
index d68a1a3aced3..e4b3ae450fe6 100644
--- a/posthog/admin/admins/oauth_admin.py
+++ b/posthog/admin/admins/oauth_admin.py
@@ -298,7 +298,8 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne
# A CIMD client's scope ceiling is derived from its own metadata document and
# re-applied on every refresh, so a manual edit here would be silently reverted.
# The unprivileged/hidden allow-list is the only ceiling that applies to CIMD
- # apps; to cut off an abusive one, block its metadata URL rather than editing scopes.
+ # apps. To cut off an abusive partner, set its provisioning `disabled` switch: deleting
+ # the app only revokes its tokens, and a self-registered partner can register again.
readonly.append("scopes")
# Model validation also rejects optional_scopes on CIMD apps: a split would
# let the partner grow the locked required set via metadata refresh.
diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.py
index d0bfe3649a6b..7228a6f0ec6b 100644
--- a/posthog/api/oauth/cimd.py
+++ b/posthog/api/oauth/cimd.py
@@ -29,7 +29,6 @@ from rest_framework.throttling import SimpleRateThrottle
from posthog.exceptions_capture import capture_exception
from posthog.models.oauth import (
- CIMDBlocklistEntry,
CIMDVerificationToken,
OAuthApplication,
TokenEndpointAuthMethod,
@@ -219,41 +218,6 @@ def _fetch_lock_key(url: str) -> str:
return f"cimd:fetching:{url_hash}"
-def _blocked_key(url: str) -> str:
- url_hash = hashlib.sha256(url.encode()).hexdigest()
- return f"cimd:blocked:{url_hash}"
-
-
-def block_cimd_url(url: str, *, reason: str = "", created_by=None, ttl: int = 86400 * 365) -> None:
- """Add a CIMD URL to the blocklist. Persists in Postgres; Redis is cache."""
- CIMDBlocklistEntry.objects.update_or_create(
- cimd_url=url,
- defaults={"reason": reason, "created_by": created_by},
- )
- cache.set(_blocked_key(url), True, timeout=ttl)
-
-
-def unblock_cimd_url(url: str) -> None:
- """Remove a CIMD URL from the blocklist."""
- CIMDBlocklistEntry.objects.filter(cimd_url=url).delete()
- cache.delete(_blocked_key(url))
-
-
-def is_cimd_url_blocked(url: str) -> bool:
- """Check if a CIMD URL has been blocklisted.
-
- Postgres is source of truth; Redis is a read-through cache so the hot
- path stays a single in-memory lookup. A cache miss falls back to a DB
- read and re-warms the cache, so a Redis flush doesn't expose blocked
- URLs."""
- cached = cache.get(_blocked_key(url))
- if cached is not None:
- return bool(cached)
- blocked = CIMDBlocklistEntry.objects.filter(cimd_url=url).exists()
- cache.set(_blocked_key(url), blocked, timeout=86400 * 365)
- return blocked
-
-
def _parse_cache_ttl(response: requests.Response) -> int:
"""Extract cache TTL from HTTP headers, clamped to [min, max]."""
cache_control = response.headers.get("Cache-Control", "")
@@ -885,10 +849,6 @@ def fetch_and_upsert_cimd_application(
that fails model validation a ``CIMDValidationError`` rather than a kept row, so nothing is
granted off metadata we could not store; see ``_update_cimd_application``.
"""
- if is_cimd_url_blocked(url):
- logger.warning("cimd_blocked_url_fetch_attempt", url=url)
- return None
-
fetch_lock = _fetch_lock_key(url)
if not cache.add(fetch_lock, True, timeout=CIMD_FETCH_TIMEOUT_SECONDS * 3):
return None
diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.py
index d840028d3dc2..7dc590bdaa98 100644
--- a/posthog/api/oauth/test_cimd.py
+++ b/posthog/api/oauth/test_cimd.py
@@ -439,15 +439,18 @@ class TestFetchAndUpsertCimdApplication(APIBaseTest):
fetch_and_upsert_cimd_application(VALID_CIMD_URL)
@patch("posthog.api.oauth.cimd.requests.Session.get")
- def test_blocked_url_prevents_fetch(self, mock_get, _url_mock):
- from posthog.api.oauth.cimd import block_cimd_url, unblock_cimd_url
+ def test_deleting_the_application_lets_the_url_register_again(self, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata(), headers={})
+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+ assert app is not None
- block_cimd_url(VALID_CIMD_URL)
- result = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
- self.assertIsNone(result)
- self.assertEqual(_document_fetches(mock_get), [])
+ app.delete()
+
+ mock_get.return_value = _mock_response(_make_metadata(), headers={})
+ recreated = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
- unblock_cimd_url(VALID_CIMD_URL)
+ assert recreated is not None
+ self.assertTrue(OAuthApplication.objects.filter(client_id=VALID_CIMD_URL).exists())
@patch("posthog.api.oauth.cimd.requests.Session.get")
def test_releases_lock_on_failure(self, mock_get, _url_mock):
diff --git a/posthog/migrations/1334_remove_cimd_blocklist_entry.py b/posthog/migrations/1334_remove_cimd_blocklist_entry.py
new file mode 100644
index 000000000000..f193eb880c48
--- /dev/null
+++ b/posthog/migrations/1334_remove_cimd_blocklist_entry.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.17 on 2026-09-02 15:54
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1333_uploaded_media_library_index"),
+ ]
+
+ operations = [
+ # State-only: the CIMD URL blocklist is removed, but the posthog_cimdblocklistentry
+ # table is kept for now (deploy safety: old code may still read it mid-rollout).
+ # A later RunSQL migration can DROP TABLE once this has been out for a full
+ # deploy cycle.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.DeleteModel(name="CIMDBlocklistEntry"),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index f94ad6c837a5..91e66cb69b23 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1333_uploaded_media_library_index
+1334_remove_cimd_blocklist_entry
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.py
index 2d897dc02f89..d698c01af7cf 100644
--- a/posthog/models/oauth.py
+++ b/posthog/models/oauth.py
@@ -1035,27 +1035,6 @@ def create_cimd_verification_token(
return token, plaintext
-class CIMDBlocklistEntry(models.Model):
- """Persistent blocklist for CIMD partner URLs.
-
- Source of truth for is_cimd_url_blocked - the Redis check is a read-through
- cache. Persisting in Postgres means the blocklist survives Redis flushes /
- LRU eviction and a deleted CIMD app can stay blocked across restarts.
- """
-
- id: models.UUIDField = models.UUIDField(primary_key=True, default=UUIDT, editable=False)
- cimd_url: models.URLField = models.URLField(max_length=2048, unique=True)
- reason: models.CharField = models.CharField(max_length=200, blank=True, default="")
- created_at: models.DateTimeField = models.DateTimeField(default=timezone.now)
- created_by: "User | None" = models.ForeignKey( # type: ignore[assignment] # ty: ignore[invalid-assignment]
- "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
- )
-
- class Meta:
- verbose_name = "CIMD Blocklist Entry"
- verbose_name_plural = "CIMD Blocklist Entries"
-
-
logger = structlog.get_logger(__name__)
@@ -1100,18 +1079,3 @@ def _revoke_impersonation_oauth_tokens(sender, request, user, **kwargs):
refresh_tokens_revoked=refresh_revoked,
grants_deleted=grants_deleted,
)
-
-
-@receiver(models.signals.post_delete, sender=OAuthApplication)
-def _block_cimd_url_on_application_delete(sender, instance: OAuthApplication, **kwargs):
- # 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:
- return
- from posthog.api.oauth.cimd import block_cimd_url
-
- block_cimd_url(
- instance.client_id,
- reason=f"Auto-blocked on deletion of OAuthApplication {instance.pk}",
- )
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index 8688ac410534..6c4f4d64af9f 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -54,7 +54,6 @@ post_delete:posthog.models.file_system.file_system_mixin.FileSystemSyncMixin.__i
post_delete:posthog.models.file_system.file_system_view_log._drop_view_logs_when_file_deleted
post_delete:posthog.models.global_rate_limit_threshold_config.update_redis_thresholds_on_delete
post_delete:posthog.models.integration.email.cleanup_ses_identity_on_integration_delete
-post_delete:posthog.models.oauth._block_cimd_url_on_application_delete
post_delete:posthog.models.organization.clean_up_alert_subscriptions_on_membership_removal
post_delete:posthog.models.organization.clean_up_event_streams_on_membership_removal
post_delete:posthog.models.organization.pause_loops_on_membership_removal