: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
refactor(security): move the destination host check out of batch_exports (#93681)
Rosse3206e03d5d2
diff --git a/posthog/models/integration/postgres.py b/posthog/models/integration/postgres.pyindex 301b7b5ebdcf..1c1b2258e840 100644--- a/posthog/models/integration/postgres.py+++ b/posthog/models/integration/postgres.py@@ -3,6 +3,7 @@from typing import ClassVar, Literal, NamedTuplefrom posthog.models.user import User+from posthog.security.url_validation import resolve_and_validate_hostfrom . import common, model@@ -75,8 +76,6 @@ class PostgreSQLServerIntegration:created_by: User | None = None,**config,) -> model.Integration:- from products.batch_exports.backend.api.batch_export import resolve_and_validate_host-host = common._return_non_empty_str_from_config(config, "host", friendly_name="Host", kind=cls.integration_kind)try:resolve_and_validate_host(host)diff --git a/posthog/security/url_validation.py b/posthog/security/url_validation.pyindex f897a3800ca1..a965507aea7d 100644--- a/posthog/security/url_validation.py+++ b/posthog/security/url_validation.py@@ -1,4 +1,5 @@import re+import socketimport ipaddressimport urllib.parse as urlparsefrom collections.abc import Iterable, Mapping@@ -407,3 +408,80 @@ def should_block_url(u: str) -> bool:"""allowed, _ = is_url_allowed(u)return not allowed+++# The destination-host check below guards a batch export or warehouse-import target that a+# customer supplies and our servers later connect to. It duplicates the concern the rest of+# this module already covers, with its own ranges and its own resolver, and it is kept+# unchanged here only so the move carries no behavior change. Unifying it with+# `is_url_allowed` changes what we reject, so that lands separately.++INTERNAL_NETWORKS = (+ ipaddress.ip_network("10.0.0.0/8"),+ ipaddress.ip_network("172.16.0.0/12"),+ ipaddress.ip_network("192.168.0.0/16"),+ ipaddress.ip_network("127.0.0.0/8"),+ ipaddress.ip_network("169.254.0.0/16"),+ ipaddress.ip_network("0.0.0.0/8"),+ ipaddress.ip_network("::1/128"),+ ipaddress.ip_network("fc00::/7"),+ ipaddress.ip_network("fe80::/10"),+)+++def is_ip_internal(ip: str) -> bool:+ """Check if IP belongs to an internal network."""+ try:+ addr = ipaddress.ip_address(ip)+ except ValueError:+ raise ValueError("Could not parse IP")++ if any(addr in network for network in INTERNAL_NETWORKS):+ return True+ return False+++def resolve_and_validate_url(url: str) -> None:+ """Ensure provided url point to a non-internal IP."""+ try:+ parsed = urlparse.urlparse(url)+ except Exception as e:+ raise ValueError(f"Invalid URL'{url}': {e}") from e++ host = parsed.hostname+ if not host:+ raise ValueError("URL has no hostname")++ resolve_and_validate_host(host)+++def is_local_dev_or_test() -> bool:+ return settings.DEBUG or settings.TEST+++def resolve_and_validate_host(host: str) -> None:+ """Ensure provided host resolves to a non-internal IP."""+ if host == "localhost" and is_local_dev_or_test():+ return++ # Host may already be an IP literal+ try:+ if is_ip_internal(host) and not is_local_dev_or_test():+ raise ValueError("Host resolved to internal IP")+ return+ except ValueError:+ # Not an IP literal, requires DNS+ pass++ try:+ # getaddrinfo supports both ipv4 and ipv6+ results = socket.getaddrinfo(host, None)+ except socket.gaierror as e:+ raise ValueError(f"Could not resolve '{host}': {e}") from e++ # Keeps only unique ips from the result tuple+ resolved_ips = {str(r[4][0]) for r in results}++ for ip in resolved_ips:+ if is_ip_internal(ip) and not is_local_dev_or_test():+ raise ValueError("Host resolved to internal IP")diff --git a/products/batch_exports/backend/api/batch_export.py b/products/batch_exports/backend/api/batch_export.pyindex a5287b5f854c..e64e37556f88 100644--- a/products/batch_exports/backend/api/batch_export.py+++ b/products/batch_exports/backend/api/batch_export.py@@ -1,14 +1,11 @@import uuid-import socketimport typingimport builtinsimport datetime as dt-import ipaddressimport dataclassesimport collections.abcfrom dataclasses import dataclassfrom typing import Any, TypedDict, cast-from urllib.parse import urlparsefrom django.conf import settingsfrom django.db import models, transaction@@ -44,6 +41,7 @@ from posthog.models.integration import (DatabricksIntegrationError,Integration,)+from posthog.security.url_validation import resolve_and_validate_hostfrom posthog.temporal.common.client import sync_connectfrom posthog.utils import relative_date_parse, str_to_bool@@ -1082,80 +1080,9 @@ class _DatabaseFieldFinder(TraversingVisitor):super().visit_field(node)-INTERNAL_NETWORKS = (- ipaddress.ip_network("10.0.0.0/8"),- ipaddress.ip_network("172.16.0.0/12"),- ipaddress.ip_network("192.168.0.0/16"),- ipaddress.ip_network("127.0.0.0/8"),- ipaddress.ip_network("169.254.0.0/16"),- ipaddress.ip_network("0.0.0.0/8"),- ipaddress.ip_network("::1/128"),- ipaddress.ip_network("fc00::/7"),- ipaddress.ip_network("fe80::/10"),-)---def is_ip_internal(ip: str) -> bool:- """Check if IP belongs to an internal network."""- try:- addr = ipaddress.ip_address(ip)- except ValueError:- raise ValueError("Could not parse IP")-- if any(addr in network for network in INTERNAL_NETWORKS):- return True- return False---def resolve_and_validate_url(url: str) -> None:- """Ensure provided url point to a non-internal IP."""- try:- parsed = urlparse(url)- except Exception as e:- raise ValueError(f"Invalid URL'{url}': {e}") from e-- host = parsed.hostname- if not host:- raise ValueError("URL has no hostname")-- resolve_and_validate_host(host)---def is_local_dev_or_test() -> bool:- return settings.DEBUG or settings.TEST--INVALID_HOST_MESSAGE = "Invalid host. Enter a hostname or IP address without credentials, scheme, or path."-def resolve_and_validate_host(host: str) -> None:- """Ensure provided host resolves to a non-internal IP."""- if host == "localhost" and is_local_dev_or_test():- return-- # Host may already be an IP literal- try:- if is_ip_internal(host) and not is_local_dev_or_test():- raise ValueError("Host resolved to internal IP")- return- except ValueError:- # Not an IP literal, requires DNS- pass-- try:- # getaddrinfo supports both ipv4 and ipv6- results = socket.getaddrinfo(host, None)- except socket.gaierror as e:- raise ValueError(f"Could not resolve '{host}': {e}") from e-- # Keeps only unique ips from the result tuple- resolved_ips = {str(r[4][0]) for r in results}-- for ip in resolved_ips:- if is_ip_internal(ip) and not is_local_dev_or_test():- raise ValueError("Host resolved to internal IP")--class BatchExportSerializer(serializers.ModelSerializer):"""Serializer for a BatchExport model."""diff --git a/products/managed_migrations/backend/api/batch_imports.py b/products/managed_migrations/backend/api/batch_imports.pyindex 80ba84401ffa..70454eada969 100644--- a/products/managed_migrations/backend/api/batch_imports.py+++ b/products/managed_migrations/backend/api/batch_imports.py@@ -24,6 +24,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.user import User+from posthog.security.url_validation import resolve_and_validate_urlfrom products.managed_migrations.backend import trial_storagefrom products.managed_migrations.backend.models.batch_imports import (@@ -121,10 +122,6 @@ class BatchImportSerializer(serializers.ModelSerializer):def validate_endpoint_url(self, value: str | None) -> str | None:if not value or not value.strip():return None- # Deferred: batch_export pulls the batch-export Temporal framework, which has no- # business on this module's import path.- from products.batch_exports.backend.api.batch_export import resolve_and_validate_url # noqa: PLC0415-try:resolve_and_validate_url(value)except ValueError: