: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(proxy): make proxy diagnostics path-aware and endpoint-first (#68175)
Yasenc5132d996261
diff --git a/posthog/api/proxy_record_diagnostics.py b/posthog/api/proxy_record_diagnostics.pyindex be2b8427c025..5b8234f35200 100644--- a/posthog/api/proxy_record_diagnostics.py+++ b/posthog/api/proxy_record_diagnostics.py@@ -31,6 +31,7 @@ from posthog.temporal.proxy_service.cloudflare import (CustomHostnameSSLStatus,get_custom_hostname_by_domain,)+from posthog.temporal.proxy_service.common import is_cloudflare_proxy_by_cname# --- Customer-facing message helpers ---# All user-visible strings live here so copy can be reviewed in one place. Functions@@ -160,7 +161,19 @@ class DiagnosticReport:def diagnose(record: ProxyRecord) -> DiagnosticReport:- """Run the full diagnostic pipeline against a proxy record."""+ """Run the full diagnostic pipeline against a proxy record.++ The proxy's own endpoint is the source of truth: if it serves HTTPS and accepts a test+ event, the certificate is issued and deployed and the proxy is healthy — whatever any+ certificate-provider API reports. So the live-event probe runs first and, on success,+ short-circuits to healthy.++ Provider-specific checks only run when the endpoint *isn't* serving, and only for the+ path the proxy was actually provisioned on — detected from `target_cname`, never a+ global flag. This keeps the Cloudflare checks from misfiring on legacy proxies that+ predate the Cloudflare path (where a Cloudflare lookup always comes back empty and would+ otherwise read as a false "we don't have a record of this proxy").+ """log = LOGGER.bind(proxy_record_id=str(record.id),organization_id=str(record.organization_id),@@ -168,38 +181,48 @@ def diagnose(record: ProxyRecord) -> DiagnosticReport:)log.info("Starting proxy diagnostics")- checks: list[CheckResult] = []+ is_cloudflare = is_cloudflare_proxy_by_cname(record.target_cname)cname_check = _check_cname(record)- checks.append(cname_check)-- cloudflare_check, hostname_info = _check_cloudflare(record)- checks.append(cloudflare_check)-- ssl_active = hostname_info is not None and hostname_info.ssl.status == CustomHostnameSSLStatus.ACTIVE-- if ssl_active:- checks.append(_skip("caa", "CAA records", "Skipped — certificate is already active."))- else:- checks.append(_check_caa(record, hostname_info))-- if ssl_active:- checks.append(_skip("http_challenge", "HTTP-01 challenge", "Skipped — certificate is already active."))- elif hostname_info is None or not hostname_info.ssl.http_url:- checks.append(_skip("http_challenge", "HTTP-01 challenge", "Skipped — no challenge URL available."))+ checks: list[CheckResult] = [cname_check]++ # Primary signal: does the proxy actually serve HTTPS and accept an event? A pass means+ # the cert is live and deployed, regardless of what the provider API says.+ #+ # Gate the probe on the CNAME first. `record.domain` is org-admin-controlled, so we only+ # fire the outbound request once DNS confirms the domain points at our managed proxy+ # target — otherwise Diagnose could be aimed at an internal address and used as an+ # SSRF / port-scan primitive. A failed CNAME is the actionable issue anyway.+ if cname_check.status == "passed":+ live_check = _check_live_event(record)else:- checks.append(_check_http_challenge(record, hostname_info))-- if not ssl_active:- checks.append(_skip("live_event", "Live event probe", "Skipped — certificate is not active yet."))+ live_check = _skip("live_event", "Live event probe", "Skipped — DNS isn't pointing at the proxy yet.")+ checks.append(live_check)++ if live_check.status == "passed":+ # Healthy — the endpoint works. The only remaining concern is renewal, read from the+ # certificate the proxy is actually serving.+ checks.append(_check_cert_expiry(record, is_cloudflare=is_cloudflare))+ elif is_cloudflare:+ # Not serving, and provisioned on the Cloudflare path — inspect the custom hostname.+ cloudflare_check, hostname_info = _check_cloudflare(record)+ checks.append(cloudflare_check)+ checks.append(_check_caa(record, hostname_info, is_cloudflare=True))+ if hostname_info is not None and hostname_info.ssl.http_url:+ checks.append(_check_http_challenge(record, hostname_info))+ else:+ checks.append(_skip("http_challenge", "HTTP-01 challenge", "Skipped — no challenge URL available."))checks.append(_skip("cert_expiry", "Certificate expiry", "Skipped — certificate is not active yet."))else:- live_check = _check_live_event(record)- checks.append(live_check)- if live_check.status == "passed":- checks.append(_check_cert_expiry(record))- else:- checks.append(_skip("cert_expiry", "Certificate expiry", "Skipped — live event probe failed."))+ # Not serving, and provisioned on the legacy path — there is no Cloudflare custom+ # hostname by design, so the Cloudflare check would only ever produce a false+ # "missing" result. CAA still matters for the legacy (Let's Encrypt) issuer.+ checks.append(+ _skip("cloudflare", "Certificate provider", "Skipped — this proxy uses the legacy certificate path.")+ )+ checks.append(_check_caa(record, None, is_cloudflare=False))+ checks.append(_skip("http_challenge", "HTTP-01 challenge", "Skipped — not applicable for this proxy."))+ checks.append(_skip("cert_expiry", "Certificate expiry", "Skipped — proxy isn't serving traffic yet."))summary = _build_summary(checks)log.info("Diagnostics complete", primary_issue=summary.primary_issue, status=summary.status)@@ -390,18 +413,24 @@ def _check_cloudflare(record: ProxyRecord) -> tuple[CheckResult, Optional[Custom)-def _check_caa(record: ProxyRecord, hostname_info: Optional[CustomHostnameInfo]) -> CheckResult:+def _check_caa(record: ProxyRecord, hostname_info: Optional[CustomHostnameInfo], *, is_cloudflare: bool) -> CheckResult:"""Walk up the DNS tree from `record.domain` to apex, looking for the first non-emptyset of CAA records. Per RFC 8659, the first non-empty CAA result wins — climbing- stops there. If those records don't authorize the CA Cloudflare uses, surface a- remediation block listing CAA records the customer should add.+ stops there. If those records don't authorize the CA that issues this proxy's+ certificate, surface a remediation block listing CAA records the customer should add.++ The required issuer depends on the provisioning path: Cloudflare-path certs come from+ the CA in the hostname info (Google by default), legacy-path certs come from Let's+ Encrypt."""if hostname_info is not None and hostname_info.ssl.certificate_authority:ca_field = hostname_info.ssl.certificate_authorityrequired_issuer = CA_TO_CAA_ISSUER.get(ca_field, "pki.goog")- else:+ elif is_cloudflare:required_issuer = "pki.goog"+ else:+ required_issuer = "letsencrypt.org"name = dns.name.from_text(record.domain)resolver = dns.resolver.Resolver()@@ -567,7 +596,7 @@ def _check_live_event(record: ProxyRecord) -> CheckResult:)-def _check_cert_expiry(record: ProxyRecord) -> CheckResult:+def _check_cert_expiry(record: ProxyRecord, *, is_cloudflare: bool) -> CheckResult:try:ctx = ssl_module.create_default_context()ctx.minimum_version = ssl_module.TLSVersion.TLSv1_2@@ -613,12 +642,20 @@ def _check_cert_expiry(record: ProxyRecord) -> CheckResult:days_remaining = (expires_at - dt.datetime.now(dt.UTC)).daysif days_remaining < CERT_EXPIRY_WARN_DAYS:+ # Retry re-runs provisioning, which is only safe to suggest for Cloudflare-path+ # proxies. For a legacy proxy, retry would migrate it onto Cloudflare and break a+ # working setup, so point at support rather than offering a "recreate".+ remediation = (+ Remediation(type="retry", summary="Hit Retry to start a fresh issuance.")+ if is_cloudflare+ else Remediation(type="config", summary="The certificate isn't auto-renewing — contact support.")+ )return CheckResult(id="cert_expiry",name="Certificate expiry",status="failed",detail=_msg_cert_expiring_soon(record.domain, days_remaining),- remediation=Remediation(type="retry", summary="Hit Retry to start a fresh issuance."),+ remediation=remediation,)return CheckResult(diff --git a/posthog/api/test/test_proxy_record_diagnostics.py b/posthog/api/test/test_proxy_record_diagnostics.pyindex 7f737c72ae1f..776fe528a13d 100644--- a/posthog/api/test/test_proxy_record_diagnostics.py+++ b/posthog/api/test/test_proxy_record_diagnostics.py@@ -1,6 +1,6 @@from unittest.mock import MagicMock, patch-from django.test import TestCase+from django.test import TestCase, override_settingsimport requestsimport dns.resolver@@ -156,21 +156,21 @@ class TestCheckCaa(TestCase):@patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")def test_pass_when_no_caa_records(self, ResolverMock):ResolverMock.return_value.resolve.side_effect = dns.resolver.NoAnswer()- result = diagnostics._check_caa(_record(), _hostname_info())+ result = diagnostics._check_caa(_record(), _hostname_info(), is_cloudflare=True)self.assertEqual(result.status, "passed")self.assertIn("unrestricted", result.detail.lower())@patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")def test_pass_when_caa_authorizes_required_issuer(self, ResolverMock):ResolverMock.return_value.resolve.return_value = [_caa_rdata(b"issue", "pki.goog")]- result = diagnostics._check_caa(_record(), _hostname_info(certificate_authority="google"))+ result = diagnostics._check_caa(_record(), _hostname_info(certificate_authority="google"), is_cloudflare=True)self.assertEqual(result.status, "passed")self.assertIn("pki.goog", result.detail)@patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")def test_fail_when_caa_blocks_required_issuer(self, ResolverMock):ResolverMock.return_value.resolve.return_value = [_caa_rdata(b"issue", "digicert.com")]- result = diagnostics._check_caa(_record(), _hostname_info(certificate_authority="google"))+ result = diagnostics._check_caa(_record(), _hostname_info(certificate_authority="google"), is_cloudflare=True)self.assertEqual(result.status, "failed")self.assertIn("digicert.com", result.detail)self.assertIn("pki.goog", result.detail)@@ -178,6 +178,15 @@ class TestCheckCaa(TestCase):self.assertEqual(result.remediation.type, "dns")self.assertGreater(len(result.remediation.records), 0)+ @patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")+ def test_legacy_proxy_requires_letsencrypt_issuer(self, ResolverMock):+ # Legacy proxies have no Cloudflare hostname info; their cert is Let's Encrypt, so a+ # CAA record authorizing only Google must fail against letsencrypt.org (not pki.goog).+ ResolverMock.return_value.resolve.return_value = [_caa_rdata(b"issue", "pki.goog")]+ result = diagnostics._check_caa(_record(), None, is_cloudflare=False)+ self.assertEqual(result.status, "failed")+ self.assertIn("letsencrypt.org", result.detail)+class TestCheckHttpChallenge(TestCase):@patch("posthog.api.proxy_record_diagnostics.requests.get")@@ -242,37 +251,147 @@ class TestCheckLiveEvent(TestCase):self.assertEqual(result.status, "passed")+class TestCheckCertExpiry(TestCase):+ @parameterized.expand(+ [+ ("cloudflare_path", True, "retry"),+ ("legacy_path", False, "config"),+ ]+ )+ @patch("posthog.api.proxy_record_diagnostics.ssl_module.create_default_context")+ @patch("posthog.api.proxy_record_diagnostics.socket.create_connection")+ def test_expiring_cert_remediation_depends_on_path(+ self, _name, is_cloudflare, expected_type, _create_conn_mock, ctx_mock+ ):+ # An expiring cert triggers the failed branch; the remediation differs by path — a+ # Cloudflare proxy can safely re-provision (retry), a legacy proxy must not (config),+ # since retry would migrate it onto Cloudflare and break a working setup.+ wrapped = ctx_mock.return_value.wrap_socket.return_value.__enter__.return_value+ wrapped.getpeercert.return_value = {"notAfter": "Jan 1 00:00:00 2000 GMT"}++ result = diagnostics._check_cert_expiry(_record(), is_cloudflare=is_cloudflare)++ self.assertEqual(result.status, "failed")+ assert result.remediation is not None+ self.assertEqual(result.remediation.type, expected_type)+++CF_TARGET = "abc.cf-prod-eu-proxy.europehog.com."+LEGACY_TARGET = "abc.proxy-us.posthog.com."+++@override_settings(CLOUDFLARE_PROXY_BASE_CNAME="cf-prod-eu-proxy.europehog.com")class TestDiagnoseOrchestrator(TestCase):- """End-to-end orchestrator with all external deps mocked."""+ """End-to-end orchestrator with all external deps mocked.++ Path is detected from `target_cname` vs `CLOUDFLARE_PROXY_BASE_CNAME` (overridden above):+ `CF_TARGET` reads as a Cloudflare proxy, `LEGACY_TARGET` as a legacy one.+ """+ @parameterized.expand([("cloudflare_path", CF_TARGET), ("legacy_path", LEGACY_TARGET)])@patch("posthog.api.proxy_record_diagnostics._check_cert_expiry")@patch("posthog.api.proxy_record_diagnostics.requests.post")@patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")@patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")- def test_healthy_when_ssl_active_and_live_passes(self, ResolverMock, get_mock, post_mock, cert_mock):+ def test_live_pass_short_circuits_to_healthy(self, _name, target, ResolverMock, get_mock, post_mock, cert_mock):+ # A working endpoint means the cert is live and deployed, so no provider API is+ # consulted — on either path. This is the regression that made a healthy legacy+ # proxy report as broken because its Cloudflare lookup came back empty.cname = MagicMock()- cname.target.to_text.return_value = "abc.cf-prod-eu-proxy.europehog.com."+ cname.target.to_text.return_value = targetResolverMock.return_value.resolve.return_value = [cname]- get_mock.return_value = _hostname_info(ssl_status=CustomHostnameSSLStatus.ACTIVE)post_mock.return_value = MagicMock(status_code=200)cert_mock.return_value = diagnostics.CheckResult(id="cert_expiry", name="Certificate expiry", status="passed", detail="ok")- report = diagnostics.diagnose(_record())+ report = diagnostics.diagnose(_record(target=target))self.assertEqual(report.summary.status, "healthy")- self.assertIsNone(report.summary.primary_issue)- ids = [c.id for c in report.checks]- self.assertEqual(ids, ["cname", "cloudflare", "caa", "http_challenge", "live_event", "cert_expiry"])+ self.assertEqual([c.id for c in report.checks], ["cname", "live_event", "cert_expiry"])+ get_mock.assert_not_called()++ @patch("posthog.api.proxy_record_diagnostics.requests.post")+ @patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")+ @patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")+ def test_cname_failure_skips_live_probe(self, ResolverMock, get_mock, post_mock):+ # SSRF guard: when DNS doesn't confirm the domain points at our managed proxy target,+ # the live probe must not fire an outbound request to the org-controlled hostname.+ cname = MagicMock()+ cname.target.to_text.return_value = "somewhere-else.example.net."++ def resolve_side_effect(name, rdtype):+ if rdtype == "CNAME":+ return [cname]+ raise dns.resolver.NoAnswer()++ ResolverMock.return_value.resolve.side_effect = resolve_side_effect+ get_mock.return_value = None++ report = diagnostics.diagnose(_record(target=CF_TARGET))++ post_mock.assert_not_called()+ live_check = next(c for c in report.checks if c.id == "live_event")+ self.assertEqual(live_check.status, "skipped")+ self.assertEqual(report.summary.primary_issue, "cname")++ @patch("posthog.api.proxy_record_diagnostics.requests.post")+ @patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")+ @patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")+ def test_legacy_not_serving_skips_cloudflare_and_offers_no_retry(self, ResolverMock, get_mock, post_mock):+ # A broken legacy proxy must skip the Cloudflare check (not fail it), never call the+ # Cloudflare API, and never suggest retry — retry would migrate it onto Cloudflare.+ cname = MagicMock()+ cname.target.to_text.return_value = LEGACY_TARGET++ def resolve_side_effect(name, rdtype):+ if rdtype == "CNAME":+ return [cname]+ raise dns.resolver.NoAnswer()++ ResolverMock.return_value.resolve.side_effect = resolve_side_effect+ post_mock.side_effect = requests.exceptions.ConnectionError("refused")++ report = diagnostics.diagnose(_record(target=LEGACY_TARGET))++ get_mock.assert_not_called()+ cf_check = next(c for c in report.checks if c.id == "cloudflare")+ self.assertEqual(cf_check.status, "skipped")+ self.assertFalse(any(c.remediation and c.remediation.type == "retry" for c in report.checks))+ self.assertEqual(report.summary.primary_issue, "live_event")++ @patch("posthog.api.proxy_record_diagnostics.requests.post")+ @patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")+ @patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")+ def test_cloudflare_missing_hostname_still_offers_retry(self, ResolverMock, get_mock, post_mock):+ # A genuine Cloudflare-path proxy whose custom hostname is missing: retry is correct.+ cname = MagicMock()+ cname.target.to_text.return_value = CF_TARGET++ def resolve_side_effect(name, rdtype):+ if rdtype == "CNAME":+ return [cname]+ raise dns.resolver.NoAnswer()++ ResolverMock.return_value.resolve.side_effect = resolve_side_effect+ post_mock.side_effect = requests.exceptions.ConnectionError("refused")+ get_mock.return_value = None++ report = diagnostics.diagnose(_record(target=CF_TARGET))++ cf_check = next(c for c in report.checks if c.id == "cloudflare")+ self.assertEqual(cf_check.status, "failed")+ assert cf_check.remediation is not None+ self.assertEqual(cf_check.remediation.type, "retry")@patch("posthog.api.proxy_record_diagnostics.requests.get")+ @patch("posthog.api.proxy_record_diagnostics.requests.post")@patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")@patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")- def test_caa_failure_surfaces_as_primary_issue(self, ResolverMock, get_mock, http_get_mock):+ def test_cloudflare_not_serving_caa_blocking_is_primary(self, ResolverMock, get_mock, post_mock, http_get_mock):# CNAME query returns the right target; CAA query returns a blocking record.cname = MagicMock()- cname.target.to_text.return_value = "abc.cf-prod-eu-proxy.europehog.com."+ cname.target.to_text.return_value = CF_TARGETdef resolve_side_effect(name, rdtype):if rdtype == "CNAME":@@ -282,15 +401,13 @@ class TestDiagnoseOrchestrator(TestCase):raise dns.resolver.NoAnswer()ResolverMock.return_value.resolve.side_effect = resolve_side_effect+ post_mock.side_effect = requests.exceptions.ConnectionError("refused")get_mock.return_value = _hostname_info(ssl_status=CustomHostnameSSLStatus.PENDING_VALIDATION)http_get_mock.return_value = MagicMock(status_code=200, text="tok.body")- report = diagnostics.diagnose(_record())+ report = diagnostics.diagnose(_record(target=CF_TARGET))self.assertEqual(report.summary.status, "fail")self.assertEqual(report.summary.primary_issue, "caa")# next_action is the fix (authorize pki.goog), not the causeself.assertIn("pki.goog", report.summary.next_action or "")- # the underlying cause is in the check's detail- caa_check = next(c for c in report.checks if c.id == "caa")- self.assertIn("digicert.com", caa_check.detail)