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(provisioning): refresh CIMD metadata on the agentic provisioning auth path (#66052)

Matt Brookere408fcde6e6e
diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.py
index 3dd9fd3cc00c..efd5f28f01e8 100644
--- a/ee/api/agentic_provisioning/authentication.py
+++ b/ee/api/agentic_provisioning/authentication.py
@@ -16,6 +16,7 @@ from rest_framework.request import Request
from posthog.api.oauth.cimd import (
apply_provisioning_defaults,
+ enqueue_cimd_refresh_if_stale,
get_application_by_client_id,
is_cimd_client_id,
is_cimd_registration_in_progress,
@@ -147,6 +148,21 @@ class ProvisioningAuthentication(BaseAuthentication):
app = OAuthApplication.objects.filter(cimd_metadata_url=client_id).first()
if app is not None:
+ # The raw lookup above bypasses get_or_create_cimd_application, so the
+ # CIMD document's TTL-based refresh never fires on this path. Enqueue it
+ # here so edits to live metadata (scope ceiling, redirect_uris, config)
+ # propagate instead of freezing at first registration. Refresh stays
+ # async; this request still serves the existing app.
+ try:
+ enqueue_cimd_refresh_if_stale(client_id)
+ except Exception as e:
+ logger.warning(
+ "provisioning_cimd_refresh_enqueue_error",
+ client_id=client_id,
+ error=str(e),
+ error_type=type(e).__name__,
+ )
+
try:
if not app.is_provisioning_partner:
apply_provisioning_defaults(app)
diff --git a/ee/api/agentic_provisioning/test/test_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
index ce5d157800ec..1d2179f96f58 100644
--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py
+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
@@ -11,10 +11,13 @@ from unittest.mock import MagicMock, patch
from django.core.cache import cache as real_cache
from django.test import override_settings
+from parameterized import parameterized
from rest_framework.test import APIClient
+from posthog.api.oauth.cimd import _blocked_key, _cache_key
from posthog.models.oauth import OAuthApplication
+from ee.api.agentic_provisioning.authentication import ProvisioningAuthentication
from ee.api.agentic_provisioning.signature import compute_signature
HMAC_SECRET = "test_hmac_secret"
@@ -577,6 +580,49 @@ class TestProvisioningAuthentication(APIBaseTest):
cimd_app.delete()
+ @parameterized.expand(
+ [
+ ("stale_cache_fires_refresh", False, 1),
+ ("fresh_cache_skips_refresh", True, 0),
+ ]
+ )
+ @patch("posthog.api.oauth.cimd.refresh_cimd_metadata_task")
+ def test_cimd_provisioning_partner_refreshes_metadata_only_when_stale(
+ self, _name, cache_is_fresh, expected_delay_calls, mock_refresh
+ ):
+ cimd_url = "https://example.com/api/oauth/wizard/refresh-on-auth"
+ cimd_app = OAuthApplication.objects.create(
+ name="CIMD Wizard Refresh",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="http://localhost:8239/callback",
+ algorithm="RS256",
+ is_cimd_client=True,
+ cimd_metadata_url=cimd_url,
+ provisioning_auth_method="pkce",
+ provisioning_partner_type="wizard",
+ provisioning_active=True,
+ provisioning_can_create_accounts=True,
+ provisioning_can_provision_resources=True,
+ )
+ self.addCleanup(cimd_app.delete)
+ 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)
+ else:
+ real_cache.delete(_cache_key(cimd_url))
+
+ partner = ProvisioningAuthentication()._identify_pkce_partner(cimd_url)
+
+ assert partner == cimd_app
+ assert mock_refresh.delay.call_count == expected_delay_calls
+ if expected_delay_calls:
+ mock_refresh.delay.assert_called_once_with(cimd_url)
+
# --- PKCE code_challenge_method validation ---
def test_plain_code_challenge_method_rejected(self):
@@ -689,6 +735,44 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
assert res.status_code == 200
assert res.json()["type"] == "oauth"
+ @patch("posthog.api.oauth.cimd.requests.get")
+ def test_cimd_scope_ceiling_refreshes_on_agentic_auth_after_metadata_edit(self, mock_get, _url_mock):
+ from posthog.api.oauth.cimd import _cache_key, register_cimd_provisioning_application_task
+
+ initial = _make_cimd_metadata()
+ initial["com.posthog"] = {"scopes": ["insight:read"]}
+ mock_get.return_value = _cimd_mock_response(initial)
+ register_cimd_provisioning_application_task(CIMD_PROV_URL)
+
+ app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_PROV_URL)
+ assert app.scopes == ["insight:read"]
+
+ # Partner edits the live metadata to widen the ceiling; the cached doc goes stale.
+ real_cache.delete(_cache_key(CIMD_PROV_URL))
+ widened = _make_cimd_metadata()
+ widened["com.posthog"] = {"scopes": ["insight:read", "dashboard:read"]}
+ mock_get.return_value = _cimd_mock_response(widened)
+
+ # A later agentic provisioning auth request must propagate the edit — the bug was that
+ # this raw-lookup path never refreshed, so the ceiling stayed frozen at registration.
+ _, challenge = _pkce_pair()
+ res = self.client.post(
+ "/api/agentic/provisioning/account_requests",
+ data={
+ "id": "req_cimd_refresh_e2e",
+ "email": "[email protected]",
+ "client_id": CIMD_PROV_URL,
+ "code_challenge": challenge,
+ "code_challenge_method": "S256",
+ },
+ content_type="application/json",
+ HTTP_API_VERSION="0.1d",
+ )
+ assert res.status_code == 200
+
+ app.refresh_from_db()
+ assert app.scopes == ["insight:read", "dashboard:read"]
+
@patch("posthog.api.oauth.cimd.refresh_cimd_metadata_task")
def test_existing_cimd_app_gets_provisioning_backfilled(self, mock_refresh, _url_mock):
OAuthApplication.objects.create(
diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.py
index 75fc4c1c283d..e94c9a6f7f4b 100644
--- a/posthog/api/oauth/cimd.py
+++ b/posthog/api/oauth/cimd.py
@@ -663,8 +663,7 @@ def get_or_create_cimd_application(url: str) -> OAuthApplication:
"""
# Existing client: check cache freshness and if not fresh, fire refresh in the background, returning existing app immediately
if app := OAuthApplication.objects.filter(cimd_metadata_url=url).first():
- if not cache.get(_cache_key(url)):
- refresh_cimd_metadata_task.delay(url)
+ enqueue_cimd_refresh_if_stale(url)
return app
# New client: synchronous fetch
@@ -682,6 +681,18 @@ def get_or_create_cimd_application(url: str) -> OAuthApplication:
raise CIMDFetchError(f"Another request is already registering this client ({url}). Please try again.")
+def enqueue_cimd_refresh_if_stale(url: str) -> None:
+ """Fire a background metadata refresh if the cached document has gone stale.
+
+ Single source of the freshness check, used both by get_or_create_cimd_application
+ and by callers that resolve an existing CIMD app via a direct lookup (the agentic
+ provisioning auth path) so document changes are picked up on the same TTL, instead
+ of freezing the app's scopes and config at first registration.
+ """
+ if not cache.get(_cache_key(url)):
+ refresh_cimd_metadata_task.delay(url)
+
+
def get_application_by_client_id(client_id: str) -> OAuthApplication:
"""
Look up an OAuthApplication by client_id, supporting CIMD URL-form client_ids.