: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(business-knowledge): prefer ipv4 when pinning crawl fetches (#117562)
Alex V47822ec9d513
diff --git a/products/business_knowledge/backend/tests/test_url_ingest.py b/products/business_knowledge/backend/tests/test_url_ingest.pyindex 4515022cefd0..def42f556e5c 100644--- a/products/business_knowledge/backend/tests/test_url_ingest.py+++ b/products/business_knowledge/backend/tests/test_url_ingest.py@@ -11,12 +11,17 @@ Design notes:attempt should fail fast)."""+import ipaddress+from collections.abc import Iterator+from posthog.test.base import APIBaseTest, BaseTestfrom unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase+import requestsfrom parameterized import parameterized+from requests.adapters import HTTPAdapterfrom rest_framework import statusfrom posthog.security.url_validation import PinnedUrlVerdict@@ -143,6 +148,30 @@ class TestFetchUrl(SimpleTestCase):# SSRF check was re-run on the redirect target.assert mock_ssrf.call_count == 2+ @patch("products.business_knowledge.backend.url_fetch.requests.Session")+ @patch("products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips")+ def test_pins_ipv4_when_aaaa_is_also_validated(self, mock_ssrf: MagicMock, mock_session_cls: MagicMock) -> None:+ class _Ipv6First(set[ipaddress.IPv4Address | ipaddress.IPv6Address]):+ def __iter__(self) -> Iterator[ipaddress.IPv4Address | ipaddress.IPv6Address]:+ items = list(super().__iter__())+ items.sort(key=lambda ip: (ip.version != 6, int(ip)))+ return iter(items)++ ipv4 = ipaddress.ip_address("93.184.216.34")+ ipv6 = ipaddress.ip_address("2600:1f18::1")+ mock_ssrf.return_value = PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=_Ipv6First({ipv4, ipv6}))+ session = mock_session_cls.return_value+ session.get.return_value = _mock_response(body=b"<html>hi</html>")++ url_fetch.fetch_url("https://example.com/x")++ adapter = session.mount.call_args_list[0].args[1]+ request = requests.Request("GET", "https://example.com/x").prepare()+ with patch.object(HTTPAdapter, "send", return_value=MagicMock()):+ adapter.send(request)+ assert request.url == "https://93.184.216.34/x"+ assert request.headers["Host"] == "example.com"+@patch("products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips",return_value=PinnedUrlVerdict(allowed=False, reason="Loopback", pinned_ips=set()),diff --git a/products/business_knowledge/backend/url_fetch.py b/products/business_knowledge/backend/url_fetch.pyindex 5b5cadff9d43..04d668e8e7bd 100644--- a/products/business_knowledge/backend/url_fetch.py+++ b/products/business_knowledge/backend/url_fetch.py@@ -22,7 +22,7 @@ from dataclasses import dataclassimport requestsimport structlog-from posthog.security.pinned_requests import PinnedIPAdapter+from posthog.security.pinned_requests import PinnedIPAdapter, select_pinned_ipfrom posthog.security.url_validation import strip_userinfo, validate_url_and_pin_ipsfrom .constants import URL_CONNECT_TIMEOUT, URL_MAX_BYTES, URL_MAX_REDIRECTS, URL_READ_TIMEOUT, URL_USER_AGENT@@ -139,11 +139,13 @@ def _ssrf_safe_get()raise UrlFetchError("URL is not reachable from this environment.")- # Pin the first validated IP so requests connects to it directly+ # select_pinned_ip prefers IPv4. An arbitrary member of pinned_ips can be+ # an AAAA record, and an IPv4-only worker then fails the connection.parsed = urlparse.urlparse(current)hostname = (parsed.hostname or "").lower()- if verdict.pinned_ips:- adapter.pin(hostname, next(iter(verdict.pinned_ips)))+ chosen_ip = select_pinned_ip(verdict.pinned_ips)+ if chosen_ip is not None:+ adapter.pin(hostname, chosen_ip)merged_headers = dict(headers)if etag: