: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(warehouse-sources): share the SSRF guard in url validation (#81603)
Tom Piccirello9b842fe6fc8b
diff --git a/products/data_warehouse/backend/tests/api/test_table.py b/products/data_warehouse/backend/tests/api/test_table.pyindex 0c08af32394f..88c0d30ddcdd 100644--- a/products/data_warehouse/backend/tests/api/test_table.py+++ b/products/data_warehouse/backend/tests/api/test_table.py@@ -1,4 +1,4 @@-import socket+import ipaddressfrom typing import Anyfrom posthog.test.base import APIBaseTest@@ -15,7 +15,7 @@ from products.data_warehouse.backend.direct_postgres import DIRECT_POSTGRES_URL_from products.data_warehouse.backend.presentation.views.table import SimpleTableSerializerfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource-PUBLIC_ADDRINFO = [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("93.184.216.34", 0))]+PUBLIC_IP = {ipaddress.ip_address("93.184.216.34")}class TestTable(APIBaseTest):@@ -23,15 +23,20 @@ class TestTable(APIBaseTest):[("http_scheme", "http://example.com/path/*.csv", "URL pattern must use https."),("s3_scheme", "s3://bucket/path/*.parquet", "URL pattern must use https."),- ("localhost", "https://localhost/path/*.csv", "hostname is not allowed"),- ("literal_ipv4_loopback", "https://127.0.0.1/path/*.csv", "internal IP ranges"),- ("literal_ipv4_linklocal", "https://169.254.169.254/path/*.csv", "internal IP ranges"),- ("literal_ipv6_mapped_loopback", "https://[::ffff:127.0.0.1]/path/*.csv", "internal IP ranges"),- ("literal_ipv6_6to4_loopback", "https://[2002:7f00:1::]/path/*.csv", "internal IP ranges"),+ ("localhost", "https://localhost/path/*.csv", "Local/Loopback host not allowed"),+ ("literal_ipv4_loopback", "https://127.0.0.1/path/*.csv", "Local/Loopback host not allowed"),+ ("literal_ipv4_linklocal", "https://169.254.169.254/path/*.csv", "Local/metadata host"),+ ("literal_ipv6_mapped_loopback", "https://[::ffff:127.0.0.1]/path/*.csv", "Disallowed target IP"),+ ("literal_ipv6_6to4_loopback", "https://[2002:7f00:1::]/path/*.csv", "Disallowed target IP"),])def test_create_columns_blocks_unsafe_url_patterns(self, _: str, url_pattern: str, expected_error: str):- with patch.object(DataWarehouseTable, "get_columns") as patch_get_columns:+ # is_dev_mode is forced off so this exercises the real SSRF check instead of the+ # local-dev bypass that posthog.security.url_validation applies when DEBUG is set.+ with (+ patch("posthog.security.url_validation.is_dev_mode", return_value=False),+ patch.object(DataWarehouseTable, "get_columns") as patch_get_columns,+ ):response = self.client.post(f"/api/projects/{self.team.id}/warehouse_tables/",{@@ -54,50 +59,43 @@ class TestTable(APIBaseTest):("nip_io_loopback","https://127.0.0.1.nip.io/latest/meta-data/",- [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", 0))],- "internal IP ranges",+ {ipaddress.ip_address("127.0.0.1")},+ "Disallowed target IP",),(+ # The hostname string itself starts with "169.254." (a link-local prefix), so this+ # is blocked by the literal-prefix check before resolve_host_ips is ever called."sslip_io_linklocal","https://169.254.169.254.sslip.io/latest/meta-data/",- [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("169.254.169.254", 0))],- "internal IP ranges",+ {ipaddress.ip_address("169.254.169.254")},+ "Private IP address not allowed",),("custom_dns_rebinding","https://evil.attacker.com/path/*.csv",- [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("10.0.0.1", 0))],- "internal IP ranges",+ {ipaddress.ip_address("10.0.0.1")},+ "Disallowed target IP",),("mixed_results_one_internal","https://sneaky.example.com/path/*.csv",- [- (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("93.184.216.34", 0)),- (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("192.168.1.1", 0)),- ],- "internal IP ranges",+ {ipaddress.ip_address("93.184.216.34"), ipaddress.ip_address("192.168.1.1")},+ "Disallowed target IP",),("unresolvable_hostname","https://does-not-exist.invalid/path/*.csv",- socket.gaierror("Name or service not known"),- "could not be resolved",+ set(),+ "Could not resolve host",),])def test_create_columns_blocks_dns_resolved_internal_ips(- self, _: str, url_pattern: str, getaddrinfo_result: Any, expected_error: str+ self, _: str, url_pattern: str, resolved_ips: set, expected_error: str):- side_effect = getaddrinfo_result if isinstance(getaddrinfo_result, Exception) else None- return_value = None if isinstance(getaddrinfo_result, Exception) else getaddrinfo_result-with (- patch(- "products.warehouse_sources.backend.models.util.socket.getaddrinfo",- side_effect=side_effect,- return_value=return_value,- ),+ patch("posthog.security.url_validation.is_dev_mode", return_value=False),+ patch("posthog.security.url_validation.resolve_host_ips", return_value=resolved_ips),patch.object(DataWarehouseTable, "get_columns") as patch_get_columns,):response = self.client.post(@@ -126,14 +124,15 @@ class TestTable(APIBaseTest):url_pattern="https://your-org.s3.amazonaws.com/bucket/whatever.pqt",columns={},)- response = self.client.patch(- f"/api/projects/{self.team.id}/warehouse_tables/{table.id}",- {- "url_pattern": "https://127.0.0.1/latest/meta-data/",- },- )+ with patch("posthog.security.url_validation.is_dev_mode", return_value=False):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/warehouse_tables/{table.id}",+ {+ "url_pattern": "https://127.0.0.1/latest/meta-data/",+ },+ )assert response.status_code == 400- assert "internal IP ranges" in str(response.json())+ assert "Local/Loopback host not allowed" in str(response.json())@patch("products.warehouse_sources.backend.models.table.DataWarehouseTable.get_columns",@@ -698,7 +697,10 @@ class TestTable(APIBaseTest):url_pattern=hosted_url,)- with patch("products.warehouse_sources.backend.models.util.socket.getaddrinfo", return_value=PUBLIC_ADDRINFO):+ with (+ patch("posthog.security.url_validation.is_dev_mode", return_value=False),+ patch("posthog.security.url_validation.resolve_host_ips", return_value=PUBLIC_IP),+ ):response = self.client.patch(f"/api/projects/{self.team.id}/warehouse_tables/{table.id}",{"url_pattern": target_url},@@ -724,7 +726,10 @@ class TestTable(APIBaseTest):credential=credential,)- with patch("products.warehouse_sources.backend.models.util.socket.getaddrinfo", return_value=PUBLIC_ADDRINFO):+ with (+ patch("posthog.security.url_validation.is_dev_mode", return_value=False),+ patch("posthog.security.url_validation.resolve_host_ips", return_value=PUBLIC_IP),+ ):response = self.client.patch(f"/api/projects/{self.team.id}/warehouse_tables/{table.id}",{"url_pattern": "https://acme-exports.s3.amazonaws.com/new/*.pqt"},diff --git a/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py b/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.pyindex e4f6a8bebc4b..680589280aaa 100644--- a/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py+++ b/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py@@ -1,5 +1,5 @@import io-import socket+import ipaddressfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch@@ -243,9 +243,12 @@ class TestCreateTableFromUpload(APIBaseTest):table = DataWarehouseTable.objects.get(id=created.json()["id"])original_url_pattern = table.url_pattern- with patch(- "products.warehouse_sources.backend.models.util.socket.getaddrinfo",- return_value=[(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("93.184.216.34", 0))],+ with (+ patch("posthog.security.url_validation.is_dev_mode", return_value=False),+ patch(+ "posthog.security.url_validation.resolve_host_ips",+ return_value={ipaddress.ip_address("93.184.216.34")},+ ),):response = self.client.patch(f"/api/environments/{self.team.pk}/warehouse_tables/{table.id}",diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.pyindex c34c7f5c06aa..b1a7621a8c9b 100644--- a/products/warehouse_sources/backend/models/util.py+++ b/products/warehouse_sources/backend/models/util.py@@ -1,5 +1,4 @@import re-import socketfrom collections.abc import Mappingfrom ipaddress import IPv6Address, ip_addressfrom typing import TYPE_CHECKING, Any, Protocol, TypeVar, Union@@ -23,6 +22,8 @@ from posthog.hogql.database.models import (UUIDDatabaseField,)+from posthog.security.url_validation import is_url_allowed+if TYPE_CHECKING:from products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -580,6 +581,8 @@ def clickhouse_columns_to_dwh_columns(columns: list[tuple[str, str, bool]]) -> d}+# Used by mixins.resolve_host for direct SQL-source connections (its own IP-pinning check).+# validate_warehouse_table_url_pattern below calls posthog.security.url_validation instead.def _is_safe_public_ip(host: str) -> bool:ip = ip_address(host)@@ -649,11 +652,23 @@ def _validate_url_pattern_is_not_posthog_storage(return True, ""if _PATH_STYLE_STORAGE_HOST.match(normalized_hostname):- bucket = path.lstrip("/").split("/", 1)[0]+ segments = path.lstrip("/").split("/")+ bucket = segments[0]# A glob here expands across buckets rather than within one, so it can reach ours whatever# it looks like. No source needs to pattern-match a bucket name.if any(character in _GLOB_METACHARACTERS for character in bucket):return False, "The bucket name in a URL pattern must be exact. Wildcards belong in the file path."+ # A percent-encoded slash here would put a second path segment (potentially one of our own+ # bucket names) after whatever the request client decodes it into, while this check still+ # sees it as part of one opaque bucket segment. Reject the encoding outright rather than+ # depend on this parser agreeing with ClickHouse's about where it splits.+ if "%" in bucket:+ return False, "The bucket name in a URL pattern can't contain percent-encoded characters."+ # Same reasoning as the percent-encoding check: a literal "." or ".." segment is opaque to+ # this parser (bucket is just the first segment), but would let a path-normalizing client+ # resolve a different bucket than the one checked below. No object key legitimately needs one.+ if any(segment in (".", "..") for segment in segments):+ return False, "The path in a URL pattern can't contain '.' or '..' segments."if bucket in owned_buckets:return False, _NOT_OUR_STORAGE@@ -673,32 +688,20 @@ def validate_warehouse_table_url_pattern(url_pattern: str | None) -> tuple[bool,normalized_hostname = parsed.hostname.lower().strip().rstrip(".")- # Runs before the DNS checks below so a URL aimed at our own storage always reports that, rather- # than whatever the internal hostname happens to resolve to.+ # Runs before the generic SSRF check below so a URL aimed at our own storage always reports+ # that, rather than whatever the internal hostname happens to resolve to.is_valid, error_message = _validate_url_pattern_is_not_posthog_storage(url_pattern, normalized_hostname, parsed.path)if not is_valid:return is_valid, error_message- if normalized_hostname in {"localhost"}:- return False, "URL pattern hostname is not allowed."-- # Block direct internal IP literals.- try:- if not _is_safe_public_ip(parsed.hostname):- return False, "URL pattern hostname must not resolve to internal IP ranges."- except ValueError:- pass-- # Resolve the hostname and block if any resolved IP is internal (catches DNS rebinding services).- try:- addrinfo = socket.getaddrinfo(normalized_hostname, None, proto=socket.IPPROTO_TCP)- for _family, _type, _proto, _canonname, sockaddr in addrinfo:- resolved_ip = sockaddr[0]- if not _is_safe_public_ip(str(resolved_ip)):- return False, "URL pattern hostname must not resolve to internal IP ranges."- except socket.gaierror:- return False, "URL pattern hostname could not be resolved."+ # is_url_allowed is the same SSRF guard used for outbound fetches elsewhere in the codebase+ # (webhook destinations, integration probes, sibling warehouse_sources connectors): metadata+ # IPs, loopback/internal-TLD hosts, the backslash/%5c authority-parsing mismatch between+ # urlparse and the client that actually connects, and DNS resolution to a private IP.+ allowed, reason = is_url_allowed(url_pattern)+ if not allowed:+ return False, reason or "URL pattern hostname is not allowed."return True, ""diff --git a/products/warehouse_sources/backend/tests/test_util.py b/products/warehouse_sources/backend/tests/test_util.pyindex a29b96dfe6c1..15bf86c31163 100644--- a/products/warehouse_sources/backend/tests/test_util.py+++ b/products/warehouse_sources/backend/tests/test_util.py@@ -1,4 +1,4 @@-import socket+import ipaddressfrom posthog.test.base import BaseTestfrom unittest.mock import patch@@ -17,7 +17,7 @@ from products.warehouse_sources.backend.models.util import ()from products.warehouse_sources.backend.types import ExternalDataSourceType-PUBLIC_ADDRINFO = [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("93.184.216.34", 0))]+PUBLIC_IP = {ipaddress.ip_address("93.184.216.34")}class TestReconstructOrderedColumns(SimpleTestCase):@@ -95,14 +95,111 @@ class TestValidateWarehouseTableUrlPattern(SimpleTestCase):# A PostHog bucket name used as a key prefix in someone else's bucket is theirs, not ours.("our_bucket_name_as_a_key_prefix", "https://acme-exports.s3.amazonaws.com/ph-warehouse/*.csv"),("non_storage_host", "https://files.acme.example/exports/*.csv"),+ # Percent-encoding is fine in the object key, only the bucket segment of a path-style+ # URL rejects it.+ ("percent_encoding_in_the_key", "https://s3.us-east-1.amazonaws.com/acme-exports/my%20file.csv"),])def test_allows_a_customers_own_bucket(self, _name: str, url_pattern: str) -> None:- with patch("products.warehouse_sources.backend.models.util.socket.getaddrinfo", return_value=PUBLIC_ADDRINFO):+ with (+ patch("posthog.security.url_validation.is_dev_mode", return_value=False),+ patch("posthog.security.url_validation.resolve_host_ips", return_value=PUBLIC_IP),+ ):is_valid, error_message = validate_warehouse_table_url_pattern(url_pattern)assert is_valid, error_message+ @parameterized.expand(+ [+ (+ "path_style_encoded_slash_in_bucket_position",+ "https://s3.us-east-1.amazonaws.com/ph-warehouse%2Ffile_uploads/team_2/x.csv",+ ),+ ("path_style_encoded_char_in_bucket_position", "https://s3.us-east-1.amazonaws.com/acme%2dexports/x.csv"),+ ]+ )+ def test_rejects_percent_encoding_in_the_bucket_position(self, _name: str, url_pattern: str) -> None:+ # A request client that decodes %2F before splitting the path could resolve a different+ # bucket than this parser sees, so any percent-encoding there is rejected outright rather+ # than trusted to agree with whatever library ClickHouse uses.+ is_valid, error_message = validate_warehouse_table_url_pattern(url_pattern)++ assert not is_valid+ assert "percent-encoded" in error_message++ @parameterized.expand(+ [+ ("dot_segment_as_bucket", "https://s3.us-east-1.amazonaws.com/./ph-warehouse/x.csv"),+ ("dot_dot_segment_as_bucket", "https://s3.us-east-1.amazonaws.com/../ph-warehouse/x.csv"),+ # bucket resolves to "attacker" here, but a client that normalizes ".." before+ # connecting would resolve "ph-warehouse" instead - the exact case the percent-encoding+ # check above exists for, just via a different parser-vs-client disagreement.+ ("dot_dot_segment_later_in_the_path", "https://s3.us-east-1.amazonaws.com/attacker/../ph-warehouse/x.csv"),+ ]+ )+ def test_rejects_dot_segments_in_the_path(self, _name: str, url_pattern: str) -> None:+ is_valid, error_message = validate_warehouse_table_url_pattern(url_pattern)++ assert not is_valid+ assert "'.' or '..'" in error_message++ def test_allows_a_dot_within_a_path_segment(self) -> None:+ # Only a segment that IS exactly "." or ".." is rejected - a normal filename containing a+ # dot must not be caught by the same check.+ with (+ patch("posthog.security.url_validation.is_dev_mode", return_value=False),+ patch("posthog.security.url_validation.resolve_host_ips", return_value=PUBLIC_IP),+ ):+ is_valid, error_message = validate_warehouse_table_url_pattern(+ "https://s3.us-east-1.amazonaws.com/acme-exports/reports/q1.2026/data.csv"+ )++ assert is_valid, error_message++ # Each of these is a hostname the old bespoke IP/DNS check did not reliably reject: it had no+ # domain-suffix or authority-parsing checks at all, and metadata.google.internal was only+ # caught if DNS actually resolved it in whatever environment the check ran in. All four are+ # checked by posthog.security.url_validation before DNS resolution, so none need+ # resolve_host_ips mocked - only is_dev_mode, to exercise the real check instead of the+ # local-dev bypass.+ @parameterized.expand(+ [+ ("metadata_domain", "https://metadata.google.internal/computeMetadata/v1/"),+ ("internal_tld_suffix", "https://data.corp/team_1/x.csv"),+ ("kubernetes_service_suffix", "https://minio.storage.svc.cluster.local/team_1/x.csv"),+ # \ before @ is parsed as part of the authority by urlparse but as a path separator by+ # the client that actually connects, so the host each of them sees can disagree.+ ("authority_bypass_backslash", "https://acme-exports.s3.amazonaws.com\\@169.254.169.254/x.csv"),+ ("authority_bypass_encoded_backslash", "https://acme-exports.s3.amazonaws.com%[email protected]/x.csv"),+ ]+ )+ def test_rejects_ssrf_targets_gained_from_the_shared_url_validator(self, _name: str, url_pattern: str) -> None:+ with patch("posthog.security.url_validation.is_dev_mode", return_value=False):+ is_valid, error_message = validate_warehouse_table_url_pattern(url_pattern)++ assert not is_valid, error_message++ def test_rejects_a_private_ip_literal(self) -> None:+ # The old bespoke check's core case: a raw internal IP, blocked without any DNS lookup.+ with patch("posthog.security.url_validation.is_dev_mode", return_value=False):+ is_valid, error_message = validate_warehouse_table_url_pattern("https://10.0.0.5/team_1/x.csv")++ assert not is_valid, error_message++ def test_rejects_a_hostname_that_resolves_to_a_private_ip(self) -> None:+ # Same case, but through DNS - catches a hostname pointed at an internal address rather+ # than one supplied as a literal.+ with (+ patch("posthog.security.url_validation.is_dev_mode", return_value=False),+ patch(+ "posthog.security.url_validation.resolve_host_ips",+ return_value={ipaddress.ip_address("10.0.0.5")},+ ),+ ):+ is_valid, error_message = validate_warehouse_table_url_pattern("https://internal-alias.example/x.csv")++ assert not is_valid, error_message+class TestGetViewOrTableByName(BaseTest):def _create_warehouse_table(self, *, name, url_pattern, source=None, credential=None) -> DataWarehouseTable: