: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): diagnose blocked Cloudflare hostnames and 1014 bans (#82048)
posthog[bot]9735880cfdd2
diff --git a/posthog/api/proxy_record_diagnostics.py b/posthog/api/proxy_record_diagnostics.pyindex 42c0e2e4b6b7..06ed9bd6e094 100644--- a/posthog/api/proxy_record_diagnostics.py+++ b/posthog/api/proxy_record_diagnostics.py@@ -29,10 +29,16 @@ from posthog.models.proxy_record import is_valid_proxy_domainfrom posthog.security.pinned_requests import SSRFBlockedError, pinned_request, select_pinned_ipfrom posthog.security.url_validation import validate_url_and_pin_ipsfrom posthog.temporal.proxy_service.cloudflare import (+ BLOCKED_HOSTNAME_STATUSES,+ CLOUDFLARE_ERROR_CROSS_USER_BANNED,CloudflareAPIError,CustomHostname,CustomHostnameSSLStatus,+ CustomHostnameStatus,+ describe_blocked_hostname_status,+ describe_cross_user_banned,get_custom_hostname_by_domain,+ parse_cloudflare_error_code,)from posthog.temporal.proxy_service.common import is_cloudflare_proxy_by_cname@@ -410,6 +416,27 @@ def _check_cloudflare(record: ProxyRecord) -> tuple[CheckResult, Optional[CustomNone,)+ # A blocked or moved hostname rejects traffic at the edge even when the certificate is+ # active. Check the hostname status before the SSL status, or an active certificate masks+ # the block.+ if info.status in BLOCKED_HOSTNAME_STATUSES:+ moved = info.status in (CustomHostnameStatus.MOVED, CustomHostnameStatus.PENDING_MIGRATION)+ return (+ CheckResult(+ id="cloudflare",+ name="Cloudflare custom hostname",+ status="failed",+ detail=describe_blocked_hostname_status(info.status, record.domain),+ remediation=Remediation(+ type="config",+ summary="Contact support to restore this domain."+ if moved+ else "Check for a Cloudflare zone hold on this domain, or contact support.",+ ),+ ),+ info,+ )+ssl_status = info.ssl.statusif ssl_status == CustomHostnameSSLStatus.ACTIVE:return (@@ -666,6 +693,19 @@ def _check_live_event(record: ProxyRecord) -> CheckResult:detail=f"Live probe got HTTP {response.status_code} — proxy is up but failing.",)if response.status_code >= 400:+ # A 403 that carries Cloudflare error 1014 is a hostname authorization problem, not a+ # transient failure. Report it as failed with the remediation message.+ if parse_cloudflare_error_code(response.text) == CLOUDFLARE_ERROR_CROSS_USER_BANNED:+ return CheckResult(+ id="live_event",+ name="Live event probe",+ status="failed",+ detail=describe_cross_user_banned(record.domain),+ remediation=Remediation(+ type="config",+ summary="Check the domain's Cloudflare zone for a hold, or contact support.",+ ),+ )return CheckResult(id="live_event",name="Live event probe",diff --git a/posthog/api/test/test_proxy_record_diagnostics.py b/posthog/api/test/test_proxy_record_diagnostics.pyindex de4cd91a8c16..cda61d2ae673 100644--- a/posthog/api/test/test_proxy_record_diagnostics.py+++ b/posthog/api/test/test_proxy_record_diagnostics.py@@ -124,6 +124,28 @@ class TestCheckCloudflare(TestCase):self.assertEqual(result.remediation.type, "retry")self.assertIsNone(info)+ @parameterized.expand(+ [+ ("blocked", CustomHostnameStatus.BLOCKED, "zone hold"),+ ("pending_blocked", CustomHostnameStatus.PENDING_BLOCKED, "zone hold"),+ ("moved", CustomHostnameStatus.MOVED, "restore"),+ ("pending_migration", CustomHostnameStatus.PENDING_MIGRATION, "restore"),+ ]+ )+ @patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")+ def test_fail_when_hostname_blocked_despite_active_cert(self, _name, status, remediation_word, get_mock):+ # An active SSL certificate must not let a blocked or moved hostname pass the check.+ info = _hostname_info(ssl_status=CustomHostnameSSLStatus.ACTIVE)+ info.status = status+ get_mock.return_value = info++ result, _ = diagnostics._check_cloudflare(_record())++ self.assertEqual(result.status, "failed")+ assert result.remediation is not None+ self.assertEqual(result.remediation.type, "config")+ self.assertIn(remediation_word, result.remediation.summary)+@patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")def test_fail_when_api_errors(self, get_mock):get_mock.side_effect = CloudflareAPIError("boom")@@ -255,6 +277,14 @@ class TestCheckLiveEvent(TestCase):result = diagnostics._check_live_event(_record())self.assertEqual(result.status, "passed")+ @patch("posthog.api.proxy_record_diagnostics.pinned_request")+ def test_403_with_cloudflare_1014_fails_with_authorization_message(self, post_mock):+ # A 403 with Cloudflare error 1014 must fail the check with the authorization message.+ post_mock.return_value = MagicMock(status_code=403, text="<h1>Error 1014</h1>")+ result = diagnostics._check_live_event(_record())+ self.assertEqual(result.status, "failed")+ self.assertIn("1014", result.detail)+@patch("posthog.api.proxy_record_diagnostics.pinned_request")def test_ssrf_block_fails_the_check_instead_of_escaping(self, post_mock):# SSRFBlockedError is not a RequestException, so without its own handler it woulddiff --git a/posthog/temporal/proxy_service/cloudflare.py b/posthog/temporal/proxy_service/cloudflare.pyindex a73c40436c24..b9ae26a1507d 100644--- a/posthog/temporal/proxy_service/cloudflare.py+++ b/posthog/temporal/proxy_service/cloudflare.py@@ -7,6 +7,7 @@ This module provides functions to interact with Cloudflare's API for:- Getting Custom Hostname status (for monitoring certificate status)"""+import reimport typing as tfrom dataclasses import dataclass, fieldfrom enum import Enum@@ -96,6 +97,68 @@ class CustomHostnameStatus(CloudflareStatus):BLOCKED = "blocked"+# Custom Hostname statuses where Cloudflare stops serving traffic for the hostname, even when+# the SSL certificate is active. `blocked` and `pending_blocked` mean the edge rejects requests+# with a cross-user ban (error 1014). The usual cause is a zone hold on the customer's own+# Cloudflare zone, which forbids other accounts from activating the domain. `moved` means the+# hostname no longer points at our zone. `pending_migration` means the hostname is mid-migration+# and does not serve traffic yet. All four statuses cause the certificate check to fail.+BLOCKED_HOSTNAME_STATUSES: frozenset[CustomHostnameStatus] = frozenset(+ {+ CustomHostnameStatus.BLOCKED,+ CustomHostnameStatus.PENDING_BLOCKED,+ CustomHostnameStatus.MOVED,+ CustomHostnameStatus.PENDING_MIGRATION,+ }+)++# Cloudflare returns this error code in a 403 body when a hostname's CNAME target is banned+# across accounts. See Cloudflare's 1xxx error reference.+CLOUDFLARE_ERROR_CROSS_USER_BANNED = 1014++# Cloudflare's HTML error page shows the code as "Error 1014". The plain-text+# body sent to API clients shows "error code: 1014".+_CF_ERROR_CODE_RE = re.compile(r"error(?:\s+code)?[ :]+(\d{4})(?!\d)", re.IGNORECASE)+++def parse_cloudflare_error_code(body: t.Any) -> t.Optional[int]:+ """Extract the Cloudflare error code from a 403 or 5xx error page body.++ Returns the first four-digit code found, or None when the body is not a string or+ contains no Cloudflare error code.+ """+ if not isinstance(body, str):+ return None+ match = _CF_ERROR_CODE_RE.search(body)+ if match:+ return int(match.group(1))+ return None+++def describe_blocked_hostname_status(status: CustomHostnameStatus, domain: str) -> str:+ """Customer-facing sentence for a Custom Hostname stuck in a blocked or moved state."""+ if status in (CustomHostnameStatus.MOVED, CustomHostnameStatus.PENDING_MIGRATION):+ return (+ f"`{domain}` is no longer served by the proxy. Its hostname was moved or is "+ "mid-migration. Contact support to restore it."+ )+ return (+ f"`{domain}` is blocked from activating on the proxy. This usually means its Cloudflare "+ "zone has a hold that also covers subdomains. Release the hold on the zone's overview page "+ 'in Cloudflare, or turn off "Also prevent subdomains", then run diagnostics again. '+ "If the domain is not on Cloudflare, contact support."+ )+++def describe_cross_user_banned(domain: str) -> str:+ """Customer-facing sentence for a 403 carrying Cloudflare error 1014."""+ return (+ f"`{domain}` is not authorized to serve traffic through the proxy (error 1014). "+ "If the domain is on Cloudflare, check its zone for a hold that also covers subdomains "+ "and release it, then run diagnostics again. Otherwise contact support."+ )++@dataclassclass CustomHostnameSSL:"""SSL configuration for a Custom Hostname."""diff --git a/posthog/temporal/proxy_service/monitor.py b/posthog/temporal/proxy_service/monitor.pyindex 6607a10f6442..220e106a97ef 100644--- a/posthog/temporal/proxy_service/monitor.py+++ b/posthog/temporal/proxy_service/monitor.py@@ -26,9 +26,14 @@ from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.client import async_connectfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.proxy_service.cloudflare import (+ BLOCKED_HOSTNAME_STATUSES,+ CLOUDFLARE_ERROR_CROSS_USER_BANNED,CloudflareAPIError,CustomHostnameSSLStatus,+ describe_blocked_hostname_status,+ describe_cross_user_banned,get_custom_hostname_by_domain,+ parse_cloudflare_error_code,)from posthog.temporal.proxy_service.common import (CaptureEventInputs,@@ -220,6 +225,14 @@ async def _check_cloudflare_certificate_status(proxy_record, logger) -> CheckActwarnings=[],)+ # A blocked or moved hostname rejects traffic at the edge even when the certificate is+ # active, so it is an error, not a certificate warning.+ if hostname_info.status in BLOCKED_HOSTNAME_STATUSES:+ return CheckActivityOutput(+ errors=[describe_blocked_hostname_status(hostname_info.status, proxy_record.domain)],+ warnings=[],+ )+if hostname_info.ssl.status != CustomHostnameSSLStatus.ACTIVE:return CheckActivityOutput(errors=[],@@ -401,8 +414,18 @@ def _probe_proxy(proxy_record: ProxyRecord) -> CheckActivityOutput:warnings=[],)except requests.exceptions.HTTPError as e:+ # Parse the Cloudflare error code from the 403 body. The check then reports a cross-user+ # CNAME ban (1014) as a hostname authorization problem, not a bare status code.+ response = e.response+ cf_code = parse_cloudflare_error_code(response.text) if response is not None else None+ if cf_code == CLOUDFLARE_ERROR_CROSS_USER_BANNED:+ return CheckActivityOutput(+ errors=[describe_cross_user_banned(proxy_record.domain)],+ warnings=[],+ )+ status_code = response.status_code if response is not None else "unknown"return CheckActivityOutput(- errors=[f"Failed to send event to proxy, expected 200 but got {e.response.status_code}"],+ errors=[f"Failed to send event to proxy, expected 200 but got {status_code}"],warnings=[],)except requests.exceptions.RequestException:diff --git a/posthog/temporal/proxy_service/test/monitor_test.py b/posthog/temporal/proxy_service/test/monitor_test.pyindex e600e77c6d1c..e5f76af0b123 100644--- a/posthog/temporal/proxy_service/test/monitor_test.py+++ b/posthog/temporal/proxy_service/test/monitor_test.py@@ -12,7 +12,18 @@ from parameterized import parameterizedfrom posthog.models import Organization, ProxyRecordfrom posthog.security.url_validation import PinnedUrlVerdict-from posthog.temporal.proxy_service.monitor import PROXY_LIVE_CHECK_TIMEOUT_S, CheckActivityInput, check_proxy_is_live+from posthog.temporal.proxy_service.cloudflare import (+ CustomHostname,+ CustomHostnameSSL,+ CustomHostnameSSLStatus,+ CustomHostnameStatus,+)+from posthog.temporal.proxy_service.monitor import (+ PROXY_LIVE_CHECK_TIMEOUT_S,+ CheckActivityInput,+ _check_cloudflare_certificate_status,+ check_proxy_is_live,+)class TestCheckProxyIsLive(TestCase):@@ -199,6 +210,23 @@ class TestCheckProxyIsLive(TestCase):mock_create_connection.assert_not_called()self.assertEqual(result.warnings, [])+ @pytest.mark.asyncio+ @patch("posthog.temporal.proxy_service.monitor.requests.post")+ @patch("posthog.temporal.proxy_service.monitor.get_record")+ async def test_check_proxy_is_live_reports_cloudflare_1014(self, mock_get_record, mock_post):+ # A 403 body with Cloudflare error 1014 must report a hostname authorization problem,+ # not a bare status code.+ mock_get_record.return_value = self.proxy_record+ mock_response = Mock(status_code=403, text="<h1>Error 1014</h1>")+ mock_response.raise_for_status.side_effect = requests.exceptions.HTTPError(response=mock_response)+ mock_post.return_value = mock_response++ result = await check_proxy_is_live(self.input)++ self.assertEqual(len(result.errors), 1)+ self.assertIn("1014", result.errors[0])+ self.assertEqual(result.warnings, [])+@pytest.mark.asyncio@patch("posthog.temporal.proxy_service.monitor.requests.post")@patch("posthog.temporal.proxy_service.monitor.get_record")@@ -252,3 +280,43 @@ class TestCheckProxyIsLive(TestCase):self.assertEqual(result.errors, ["Live proxy certificate is expiring soon"])self.assertEqual(result.warnings, [])+++def _hostname(status: CustomHostnameStatus, ssl_status=CustomHostnameSSLStatus.ACTIVE) -> CustomHostname:+ return CustomHostname(+ id="id",+ hostname="e.example.com",+ status=status,+ ssl=CustomHostnameSSL(status=ssl_status, validation_errors=[]),+ )+++class TestCheckCloudflareCertificateStatus(TestCase):+ @parameterized.expand(+ [+ ("blocked", CustomHostnameStatus.BLOCKED),+ ("pending_blocked", CustomHostnameStatus.PENDING_BLOCKED),+ ("moved", CustomHostnameStatus.MOVED),+ ("pending_migration", CustomHostnameStatus.PENDING_MIGRATION),+ ]+ )+ @pytest.mark.asyncio+ @patch("posthog.temporal.proxy_service.monitor.get_custom_hostname_by_domain")+ async def test_blocked_hostname_is_error_even_when_cert_active(self, _name, status, mock_get):+ # An active SSL certificate must not mask a hostname that the edge blocked or moved.+ mock_get.return_value = _hostname(status=status, ssl_status=CustomHostnameSSLStatus.ACTIVE)++ result = await _check_cloudflare_certificate_status(Mock(domain="e.example.com"), Mock())++ self.assertEqual(len(result.errors), 1)+ self.assertEqual(result.warnings, [])++ @pytest.mark.asyncio+ @patch("posthog.temporal.proxy_service.monitor.get_custom_hostname_by_domain")+ async def test_active_hostname_and_cert_passes(self, mock_get):+ mock_get.return_value = _hostname(status=CustomHostnameStatus.ACTIVE)++ result = await _check_cloudflare_certificate_status(Mock(domain="e.example.com"), Mock())++ self.assertEqual(result.errors, [])+ self.assertEqual(result.warnings, [])diff --git a/posthog/temporal/proxy_service/test/test_cloudflare.py b/posthog/temporal/proxy_service/test/test_cloudflare.pyindex 460b0b6c8a51..d657ab9ebe3e 100644--- a/posthog/temporal/proxy_service/test/test_cloudflare.py+++ b/posthog/temporal/proxy_service/test/test_cloudflare.py@@ -7,6 +7,7 @@ from posthog.temporal.proxy_service.cloudflare import (CustomHostnameSSLStatus,CustomHostnameStatus,_parse_hostname,+ parse_cloudflare_error_code,)# Every status Cloudflare can send, which is a superset of what the enums name. Re-derive with:@@ -111,3 +112,21 @@ class TestParseHostnameStatuses(SimpleTestCase):def test_an_unmodeled_hostname_status_is_not_active(self):info = _parse_hostname(_hostname_payload(status="some_future_status"))self.assertNotEqual(info.status, CustomHostnameStatus.ACTIVE)+++class TestParseCloudflareErrorCode(SimpleTestCase):+ @parameterized.expand(+ [+ ("html_error_page", "<h1>Error 1014</h1> Ray ID: abc", 1014),+ ("plain_text_body", "error code: 1014", 1014),+ ("lowercase", "error 1014", 1014),+ ("colon_separator", "Error: 1014", 1014),+ ("other_code", "Error 1000 Access denied", 1000),+ ("five_digit_code", "error code: 10140", None),+ ("no_code", "403 Forbidden", None),+ ("empty", "", None),+ ("non_string", None, None),+ ]+ )+ def test_extracts_error_code(self, _name, body, expected):+ self.assertEqual(parse_cloudflare_error_code(body), expected)