: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): don't follow redirects in the proxy liveness check (#68423)
Paul D'Ambraacf61bf8de03
diff --git a/posthog/temporal/proxy_service/monitor.py b/posthog/temporal/proxy_service/monitor.pyindex db8f084f7125..74bf890d2242 100644--- a/posthog/temporal/proxy_service/monitor.py+++ b/posthog/temporal/proxy_service/monitor.py@@ -41,6 +41,13 @@ from posthog.temporal.proxy_service.proto import CertificateState_READY, StatusRLOGGER = get_logger(__name__)+# Timeout (seconds) for every network call in the live-proxy probe - the POST and the raw-socket+# cert fetch. The domain is attacker-controllable, so an unbounded call lets a malicious domain+# hang the activity until Temporal's start_to_close_timeout. 5.0 (vs the diagnostics probe's 3.0 in+# proxy_record_diagnostics.py) leaves headroom under this activity's 10s start_to_close budget,+# where a single on-demand diagnostics run instead shares its tighter budget across several checks.+PROXY_LIVE_CHECK_TIMEOUT_S = 5.0+@dataclassclass MonitorManagedProxyInputs:@@ -255,32 +262,56 @@ async def check_proxy_is_live(inputs: CheckActivityInput) -> CheckActivityOutput# send dummy event to check the proxy is workingtry:+ # allow_redirects=False is a security boundary: the domain is attacker-controllable+ # (an org admin sets it, and controls its DNS), so following redirects would let them+ # point us at internal targets (ClickHouse's HTTP interface, cloud metadata, management+ # APIs) - an SSRF. A working proxy answers /i/v0/e/ with a 2xx directly. Same protection+ # as the on-demand diagnostics probe in posthog/api/proxy_record_diagnostics.py+ # (_check_live_event).response = requests.post(f"https://{proxy_record.domain}/i/v0/e/",headers={"Content-Type": "application/json"},data=json.dumps({"event": "test", "api_key": "test", "distinct_id": "test"}),+ timeout=PROXY_LIVE_CHECK_TIMEOUT_S,+ allow_redirects=False,)+ # Since we don't follow redirects, treat a 3xx as a failed check rather than a live proxy:+ # a working proxy answers /i/v0/e/ with a direct 2xx, and a redirect is exactly the response+ # the allow_redirects=False guard above refuses to chase. raise_for_status only rejects+ # 4xx/5xx, so 3xx would otherwise slip through and mark the record VALID.+ if 300 <= response.status_code < 400:+ return CheckActivityOutput(+ errors=[f"Proxy returned a redirect ({response.status_code}); expected a direct 2xx response"],+ warnings=[],+ )+response.raise_for_status()- # fetch the cert info to see how far away the expiry is - if less than 2 weeks we have a problem+ # fetch the cert info to see how far away the expiry is - if less than 2 weeks we have a problem.+ # create_connection carries PROXY_LIVE_CHECK_TIMEOUT_S into the connect and the TLS handshake so+ # an attacker-controlled domain can't stall this raw socket the way it could the POST above -+ # same guard, same reason. Mirrors _check_cert_expiry in proxy_record_diagnostics.py.ctx = ssl.create_default_context()ctx.minimum_version = ssl.TLSVersion.TLSv1_2- with ctx.wrap_socket(socket.socket(), server_hostname=proxy_record.domain) as s:- s.connect((proxy_record.domain, 443))- cert = s.getpeercert()- if cert is None:- # How can cert be none if we sent an event over https?- raise Exception(- "Certificate not found while monitoring proxy endpoint (but we sent an event successfully)"- )- assert isinstance(cert["notAfter"], str)- expires_at = dt.datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z")- if expires_at - dt.datetime.now(dt.UTC).replace(tzinfo=None) < dt.timedelta(days=14):- return CheckActivityOutput(- errors=["Live proxy certificate is expiring soon"],- warnings=[],- )+ with socket.create_connection((proxy_record.domain, 443), timeout=PROXY_LIVE_CHECK_TIMEOUT_S) as sock:+ with ctx.wrap_socket(sock, server_hostname=proxy_record.domain) as s:+ cert = s.getpeercert()+ if cert is None:+ # How can cert be none if we sent an event over https?+ raise Exception("Certificate not found while monitoring proxy endpoint (but we sent an event successfully)")+ assert isinstance(cert["notAfter"], str)+ expires_at = dt.datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z")+ if expires_at - dt.datetime.now(dt.UTC).replace(tzinfo=None) < dt.timedelta(days=14):+ return CheckActivityOutput(+ errors=["Live proxy certificate is expiring soon"],+ warnings=[],+ )+ except requests.exceptions.Timeout:+ return CheckActivityOutput(+ errors=["Proxy did not respond within the timeout"],+ warnings=[],+ )except requests.exceptions.SSLError:return CheckActivityOutput(errors=["Failed to connect to proxy: invalid SSL certificate"],@@ -296,6 +327,21 @@ async def check_proxy_is_live(inputs: CheckActivityInput) -> CheckActivityOutputerrors=[f"Failed to send event to proxy, expected 200 but got {e.response.status_code}"],warnings=[],)+ except requests.exceptions.RequestException:+ # Any other POST-phase requests failure (malformed response, bad URL, etc). Caught before the+ # stdlib handler below so a POST error isn't mislabelled as a cert-fetch failure - requests+ # exceptions subclass OSError. Mirrors the sibling's broad RequestException handling.+ return CheckActivityOutput(+ errors=["Failed to send event to proxy"],+ warnings=[],+ )+ except (TimeoutError, ssl.SSLError, OSError) as e:+ # Raw-socket cert fetch failed (timeout, refused connection, TLS error). requests exceptions+ # are handled above; this catches the stdlib socket/ssl errors the cert probe can raise.+ return CheckActivityOutput(+ errors=[f"Failed to fetch proxy certificate: {e.__class__.__name__}"],+ warnings=[],+ )return CheckActivityOutput(errors=[],diff --git a/posthog/temporal/proxy_service/test/monitor_test.py b/posthog/temporal/proxy_service/test/monitor_test.pyindex d11688dbd4f7..8a915b545db7 100644--- a/posthog/temporal/proxy_service/test/monitor_test.py+++ b/posthog/temporal/proxy_service/test/monitor_test.py@@ -2,14 +2,15 @@ import jsonimport pytestfrom freezegun import freeze_time-from unittest.mock import Mock, patch+from unittest.mock import MagicMock, Mock, patchfrom django.test import TestCaseimport requests+from parameterized import parameterizedfrom posthog.models import Organization, ProxyRecord-from posthog.temporal.proxy_service.monitor import CheckActivityInput, check_proxy_is_live+from posthog.temporal.proxy_service.monitor import PROXY_LIVE_CHECK_TIMEOUT_S, CheckActivityInput, check_proxy_is_liveclass TestCheckProxyIsLive(TestCase):@@ -34,18 +35,25 @@ class TestCheckProxyIsLive(TestCase):@pytest.mark.asyncio@freeze_time("2024-01-16 10:00:00") # Frozen at Jan 16, cert expires Feb 15 (30 days later)+ @patch("posthog.temporal.proxy_service.monitor.socket.create_connection")@patch("posthog.temporal.proxy_service.monitor.ssl.create_default_context")@patch("posthog.temporal.proxy_service.monitor.requests.post")@patch("posthog.temporal.proxy_service.monitor.get_record")- async def test_check_proxy_is_live_success_mocked(self, mock_get_record, mock_post, mock_ssl_context):+ async def test_check_proxy_is_live_success_mocked(+ self, mock_get_record, mock_post, mock_ssl_context, mock_create_connection+ ):"""Test successful proxy check with mocked dependencies"""mock_get_record.return_value = self.proxy_record# Mock successful HTTP responsemock_response = Mock()+ mock_response.status_code = 200mock_response.raise_for_status.return_value = Nonemock_post.return_value = mock_response+ # Mock the raw socket the cert fetch opens so no real network connection is made+ mock_create_connection.return_value = MagicMock()+# Mock SSL certificate check with fixed future date (20 days from frozen time)mock_cert = {"notAfter": "Feb 5 10:00:00 2024 GMT"}mock_socket = Mock()@@ -60,72 +68,98 @@ class TestCheckProxyIsLive(TestCase):result = await check_proxy_is_live(self.input)- # Verify the request was made correctly+ # Verify the request was made correctly. allow_redirects=False is a security boundary:+ # the domain is org-admin-controlled, so following redirects would enable SSRF to+ # internal targets (see check_proxy_is_live). timeout stops a malicious domain hanging us.mock_post.assert_called_once_with(f"https://{self.proxy_record.domain}/i/v0/e/",headers={"Content-Type": "application/json"},data=json.dumps({"event": "test", "api_key": "test", "distinct_id": "test"}),+ timeout=PROXY_LIVE_CHECK_TIMEOUT_S,+ allow_redirects=False,)self.assertEqual(result.errors, [])self.assertEqual(result.warnings, [])+ @parameterized.expand(+ [+ (+ "ssl_error",+ requests.exceptions.SSLError("SSL certificate problem"),+ ["Failed to connect to proxy: invalid SSL certificate"],+ ),+ (+ "connection_error",+ requests.exceptions.ConnectionError("Connection refused"),+ ["Failed to connect to proxy"],+ ),+ # read_timeout guards the dedicated Timeout handler: ReadTimeout subclasses+ # requests.Timeout (not ConnectionError), so it must return the specific timeout+ # message rather than being caught by one of the later, more generic handlers.+ (+ "read_timeout",+ requests.exceptions.ReadTimeout("timed out"),+ ["Proxy did not respond within the timeout"],+ ),+ (+ "http_error",+ requests.exceptions.HTTPError(response=Mock(status_code=500)),+ ["Failed to send event to proxy, expected 200 but got 500"],+ ),+ ]+ )@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_ssl_error(self, mock_get_record, mock_post):- """Test SSL error handling"""+ async def test_check_proxy_is_live_probe_errors(+ self, _name, post_side_effect, expected_errors, mock_get_record, mock_post+ ):mock_get_record.return_value = self.proxy_record- mock_post.side_effect = requests.exceptions.SSLError("SSL certificate problem")+ mock_post.side_effect = post_side_effectresult = await check_proxy_is_live(self.input)- self.assertEqual(result.errors, ["Failed to connect to proxy: invalid SSL certificate"])+ self.assertEqual(result.errors, expected_errors)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_connection_error(self, mock_get_record, mock_post):- """Test connection error handling"""+ async def test_check_proxy_is_live_rejects_redirect(self, mock_get_record, mock_post):+ # With allow_redirects=False a 3xx is not followed; raise_for_status only rejects 4xx/5xx,+ # so this guards that a redirect fails the check instead of silently marking the proxy live.mock_get_record.return_value = self.proxy_record- mock_post.side_effect = requests.exceptions.ConnectionError("Connection refused")-- result = await check_proxy_is_live(self.input)-- self.assertEqual(result.errors, ["Failed to connect to proxy"])- 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_http_error(self, mock_get_record, mock_post):- """Test HTTP error handling"""- mock_get_record.return_value = self.proxy_record-- mock_response = Mock()- mock_response.status_code = 500- mock_post.side_effect = requests.exceptions.HTTPError(response=mock_response)+ mock_response = Mock(status_code=302)+ mock_response.raise_for_status.return_value = None+ mock_post.return_value = mock_responseresult = await check_proxy_is_live(self.input)- self.assertEqual(result.errors, ["Failed to send event to proxy, expected 200 but got 500"])+ self.assertEqual(result.errors, ["Proxy returned a redirect (302); expected a direct 2xx response"])self.assertEqual(result.warnings, [])@pytest.mark.asyncio@freeze_time("2024-01-16 10:00:00") # Frozen at Jan 16, cert expires Jan 25 (9 days later, < 14 day threshold)+ @patch("posthog.temporal.proxy_service.monitor.socket.create_connection")@patch("posthog.temporal.proxy_service.monitor.ssl.create_default_context")@patch("posthog.temporal.proxy_service.monitor.requests.post")@patch("posthog.temporal.proxy_service.monitor.get_record")- async def test_check_proxy_is_live_cert_expiring_soon(self, mock_get_record, mock_post, mock_ssl_context):+ async def test_check_proxy_is_live_cert_expiring_soon(+ self, mock_get_record, mock_post, mock_ssl_context, mock_create_connection+ ):"""Test certificate expiring soon warning"""mock_get_record.return_value = self.proxy_record# Mock successful HTTP responsemock_response = Mock()+ mock_response.status_code = 200mock_response.raise_for_status.return_value = Nonemock_post.return_value = mock_response+ # Mock the raw socket the cert fetch opens so no real network connection is made+ mock_create_connection.return_value = MagicMock()+# Mock SSL certificate that expires in 9 days (less than 14 day threshold)mock_cert = {"notAfter": "Jan 25 10:00:00 2024 GMT"}mock_socket = Mock()