: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
chore(tests): share one anti-ssrf dns mock across tests (#127974)
Thomas Obermüller9970c9996adc
diff --git a/ee/api/agentic_provisioning/test/test_client_registration.py b/ee/api/agentic_provisioning/test/test_client_registration.pyindex 7af18a63f8e1..e55edc082e46 100644--- a/ee/api/agentic_provisioning/test/test_client_registration.py+++ b/ee/api/agentic_provisioning/test/test_client_registration.py@@ -1,6 +1,5 @@import jsonimport time-from ipaddress import ip_addressfrom unittest.mock import patch@@ -18,6 +17,7 @@ from posthog.api.oauth.client_assertion import (ClientAssertionError,)from posthog.models.oauth import OAuthApplication+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom ee.api.agentic_provisioning.test.base import TEST_PARTNER_SCOPES, ProvisioningTestBase, provisioning_config@@ -94,7 +94,7 @@ class TestClientRegistration(ProvisioningTestBase):with (# example.com does not resolve, and the SSRF guard runs before the fetch, so# without this the metadata check would fail for a reason unrelated to the test.- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")}),+ mock_anti_ssrf_dns_lookup(),metadata_patch,patch("posthog.api.oauth.client_assertion.fetch_client_json_document",diff --git a/ee/api/agentic_provisioning/test/test_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.pyindex 3741ae428578..803167c27f4b 100644--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py@@ -1,5 +1,4 @@import json-from ipaddress import ip_addressfrom unittest.mock import MagicMock, patch@@ -16,6 +15,7 @@ from posthog.models.activity_logging.utils import ActivityCredential, activity_sfrom posthog.models.oauth import OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.user import User+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom ee.api.agentic_provisioning.authentication import ProvisioningAuthenticationfrom ee.api.agentic_provisioning.test.base import (@@ -566,7 +566,7 @@ def _cimd_mock_response(metadata: dict | None, status_code: int = 200):return resp-@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+@mock_anti_ssrf_dns_lookup()class TestCimdProvisioningRegistration(ProvisioningTestBase):def setUp(self):super().setUp()diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.pyindex 8c9c7605386a..bfd42e8eb9fb 100644--- a/posthog/api/oauth/test_cimd.py+++ b/posthog/api/oauth/test_cimd.py@@ -1,7 +1,6 @@import jsonimport base64import hashlib-from ipaddress import ip_addressfrom typing import castfrom urllib.parse import urlencode@@ -44,6 +43,7 @@ from posthog.models.oauth import ()from posthog.models.oauth_provisioning import PartnerTierfrom posthog.scopes import OAUTH_SCOPES_HIDDEN, PRIVILEGED_SCOPES+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupVALID_CIMD_URL = "https://app.example.com/.well-known/oauth-client-metadata.json"@@ -184,7 +184,7 @@ def test_validate_cimd_url_ssrf_blocked(mock_return, url, expected_error):assert error == expected_error-@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+@mock_anti_ssrf_dns_lookup()class TestFetchCimdMetadata(SimpleTestCase):@patch("posthog.api.oauth.cimd.requests.Session.get")def test_success(self, mock_get, _url_mock):@@ -213,12 +213,12 @@ class TestFetchCimdMetadata(SimpleTestCase):# Patched in the body: a method-level patch of the class-patched resolver would lose to it.def test_unresolvable_host_says_so(self, _url_mock):- with patch("posthog.security.url_validation.resolve_host_ips", return_value=set()):+ with mock_anti_ssrf_dns_lookup(resolves_to=[]):with self.assertRaisesRegex(CIMDValidationError, "host name does not resolve"):fetch_cimd_metadata(VALID_CIMD_URL)def test_internal_address_is_refused_without_naming_it(self, _url_mock):- with patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("10.0.0.5")}):+ with mock_anti_ssrf_dns_lookup(resolves_to=["10.0.0.5"]):with self.assertRaises(CIMDValidationError) as ctx:fetch_cimd_metadata(VALID_CIMD_URL)self.assertIn("not a public internet address", str(ctx.exception))@@ -370,7 +370,7 @@ class TestFetchCimdMetadata(SimpleTestCase):self.assertEqual(ttl, 3600) # Default 1 hour-@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+@mock_anti_ssrf_dns_lookup()class TestFetchAndUpsertCimdApplication(APIBaseTest):"""Tests for fetch_and_upsert_cimd_application — the core fetch+create/update function."""@@ -614,7 +614,7 @@ class TestFetchAndUpsertCimdApplication(APIBaseTest):self.assertIsNone(real_cache.get(_fetch_lock_key(VALID_CIMD_URL)))-@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+@mock_anti_ssrf_dns_lookup()class TestGetOrCreateCimdApplication(APIBaseTest):"""Tests for get_or_create_cimd_application — the orchestration layer."""@@ -740,7 +740,7 @@ class TestGetOrCreateCimdApplication(APIBaseTest):mock_capture.assert_not_called()-@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+@mock_anti_ssrf_dns_lookup()class TestApplyProvisioningDefaults(APIBaseTest):@patch("posthog.api.oauth.cimd.requests.Session.get")def test_opting_a_cimd_app_in_grants_the_full_default_profile(self, mock_get, _url_mock):@@ -848,7 +848,7 @@ class TestApplyProvisioningDefaults(APIBaseTest):self.assertTrue(app.provisioning.can_create_accounts)-@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+@mock_anti_ssrf_dns_lookup()class TestCIMDVerificationToken(APIBaseTest):@patch("posthog.api.oauth.cimd.requests.Session.get")def test_valid_verification_token_links_app_to_organization(self, mock_get, _url_mock):@@ -1017,7 +1017,7 @@ class TestCIMDVerificationToken(APIBaseTest):self.assertEqual(refreshed.provisioning.rate_limits, {"account_requests": 250})-@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+@mock_anti_ssrf_dns_lookup()class TestCIMDVerificationTokenURLBinding(APIBaseTest):"""The metadata document is public, so the token in it can be read and republishedby anyone. These lock in that the URL is what decides who the token belongs to."""@@ -1089,7 +1089,7 @@ class TestCIMDVerificationTokenURLBinding(APIBaseTest):self.assertEqual(app.organization_id, self.organization.id)-@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+@mock_anti_ssrf_dns_lookup()class TestCIMDVerificationRejectedCaptureEvent(APIBaseTest):"""`_capture_verification_rejected` emits `cimd_verification_token_rejected`. These lock in:the event reaching an injected capture callable (so it isn't silently dropped in Celery),@@ -1196,7 +1196,7 @@ class TestCIMDVerificationRejectedCaptureEvent(APIBaseTest):self.assertEqual(rejected[0].kwargs["properties"]["reason"], "app_url_missing")-@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+@mock_anti_ssrf_dns_lookup()class TestCIMDAuthorizeIntegration(APIBaseTest):"""Integration tests for the CIMD flow through /oauth/authorize/."""@@ -1423,7 +1423,7 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):self.assertEqual(app.client_type, OAuthApplication.CLIENT_PUBLIC)-@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+@mock_anti_ssrf_dns_lookup()class TestCIMDComPostHogNamespace(APIBaseTest):"""Tests for the com.posthog namespace: scopes and nested verification_token."""diff --git a/posthog/api/oauth/test_dcr.py b/posthog/api/oauth/test_dcr.pyindex 84c308ce9ce6..3b9bfc429893 100644--- a/posthog/api/oauth/test_dcr.py+++ b/posthog/api/oauth/test_dcr.py@@ -1,6 +1,5 @@import base64import hashlib-import ipaddressfrom urllib.parse import parse_qs, urlparsefrom posthog.test.base import APIBaseTest@@ -12,8 +11,7 @@ from rest_framework.test import APIClientfrom posthog.api.oauth.client_name import sanitize_client_namefrom posthog.models.oauth import OAuthApplication, OAuthApplicationAccessLevel, OAuthGrant--PUBLIC_IPS = {ipaddress.ip_address("93.184.216.34")}+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupclass TestDynamicClientRegistration(APIBaseTest):@@ -45,7 +43,7 @@ class TestDynamicClientRegistration(APIBaseTest):self.assertIsNone(app.organization)self.assertIsNone(app.user)- @patch("posthog.security.url_validation.resolve_host_ips", return_value=PUBLIC_IPS)+ @mock_anti_ssrf_dns_lookup()def test_register_full_client(self, _resolve):response = self.client.post("/oauth/register/",@@ -278,7 +276,6 @@ class TestDynamicClientRegistration(APIBaseTest):def test_rate_limiting_enforced(self):"""DCR endpoint should enforce rate limiting."""- from unittest.mock import patch# Mock the throttle to have a very low limitwith patch("posthog.api.oauth.dcr.DCRBurstThrottle.rate", "2/minute"):diff --git a/posthog/api/oauth/test_logo_uri.py b/posthog/api/oauth/test_logo_uri.pyindex 5ad37793884c..ccb1c7ad11a6 100644--- a/posthog/api/oauth/test_logo_uri.py+++ b/posthog/api/oauth/test_logo_uri.py@@ -1,14 +1,13 @@import ipaddress-from unittest.mock import patch-from django.test import SimpleTestCasefrom parameterized import parameterized+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup+from .logo_uri import MAX_LOGO_URI_LENGTH, usable_logo_uri-PUBLIC_IPS = {ipaddress.ip_address("93.184.216.34")}PRIVATE_IPS = {ipaddress.ip_address("10.1.2.3")}@@ -20,7 +19,7 @@ class TestUsableLogoUri(SimpleTestCase):])def test_keeps(self, _name: str, value: str) -> None:- with patch("posthog.security.url_validation.resolve_host_ips", return_value=PUBLIC_IPS):+ with mock_anti_ssrf_dns_lookup():self.assertEqual(usable_logo_uri(value), value)@parameterized.expand(@@ -40,11 +39,11 @@ class TestUsableLogoUri(SimpleTestCase):])def test_drops(self, _name: str, value: object) -> None:- with patch("posthog.security.url_validation.resolve_host_ips", return_value=PUBLIC_IPS):+ with mock_anti_ssrf_dns_lookup():self.assertIsNone(usable_logo_uri(value))def test_drops_a_public_name_that_resolves_to_a_private_address(self) -> None:- with patch("posthog.security.url_validation.resolve_host_ips", return_value=PRIVATE_IPS):+ with mock_anti_ssrf_dns_lookup(resolves_to=PRIVATE_IPS):self.assertIsNone(usable_logo_uri("https://logo.example.com/logo.png"))def test_drops_a_uri_past_the_column_limit(self) -> None:diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 04b485154e40..cf7463a7ff36 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -33,6 +33,7 @@ from posthog.temporal.ai_observability.sentiment.extraction import truncate_to_hfrom posthog.temporal.ai_observability.sentiment.schema import SentimentResultfrom posthog.temporal.common.errors import NonReportableErrorfrom posthog.temporal.common.posthog_client import is_expected_activity_failure+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom products.access_control.backend.models.access_control import AccessControlfrom products.ai_observability.backend.llm.attachments import AttachmentPart@@ -490,7 +491,7 @@ def test_openai_native_decisions_use_shared_result_semantics(stream=httpx.ByteStream(json.dumps(payload).encode()),)with (- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),+ mock_anti_ssrf_dns_lookup(resolves_to=["8.8.8.8"]),patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response) as transport,):@@ -619,7 +620,7 @@ def test_system_one_judge_emits_boolean_probability_without_reasoning("products.ai_observability.backend.llm.providers.openrouter._model_output_modalities",return_value={"typesafe/jev-1.13": ["decisions"]},),- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),+ mock_anti_ssrf_dns_lookup(resolves_to=["8.8.8.8"]),patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response) as request,):@@ -713,7 +714,7 @@ def test_system_one_categorical_results_use_category_keys_without_boolean_probab"products.ai_observability.backend.llm.providers.openrouter._model_output_modalities",return_value={"typesafe/jev-1.13": ["decisions"]},),- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),+ mock_anti_ssrf_dns_lookup(resolves_to=["8.8.8.8"]),patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,patch("httpx.AsyncHTTPTransport.handle_async_request") as request,):@@ -795,7 +796,7 @@ def test_decision_numeric_scores_use_configured_bounds("products.ai_observability.backend.llm.providers.openrouter._model_output_modalities",return_value={"typesafe/jev-1.13": ["decisions"]},),- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),+ mock_anti_ssrf_dns_lookup(resolves_to=["8.8.8.8"]),patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,patch("httpx.AsyncHTTPTransport.handle_async_request",@@ -840,7 +841,7 @@ def test_decision_numeric_scores_use_configured_bounds(@pytest.mark.parametrize("output_config", [{}, {"min": 0}, {"max": 10}, {"min": 1, "max": 1}])def test_system_one_numeric_requires_a_score_range(output_config: dict[str, float]) -> None:with (- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),+ mock_anti_ssrf_dns_lookup(resolves_to=["8.8.8.8"]),patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,patch("httpx.AsyncHTTPTransport.handle_async_request") as request,):@@ -894,7 +895,7 @@ def test_provider_rejections_distinguish_blocked_endpoints_from_bad_inputs("products.ai_observability.backend.llm.providers.openrouter._model_output_modalities",return_value={"example-judge-v1": ["decisions"]},),- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),+ mock_anti_ssrf_dns_lookup(resolves_to=["8.8.8.8"]),patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response) as request,):@@ -941,7 +942,7 @@ def _call_openai_compatible_judge(encrypted_config={"api_key": "example-token", "base_url": "https://decisions.example.com/v1"},)with (- patch("posthog.security.url_validation.resolve_host_ips", return_value=resolved_ips),+ mock_anti_ssrf_dns_lookup(resolves_to=resolved_ips),patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,):spec.return_value.resolve.return_value = MagicMock(@@ -1070,7 +1071,7 @@ def test_custom_provider_rate_limit_retries_without_disabling_the_evaluation(encrypted_config={"api_key": "example-token", "base_url": "https://decisions.example.com/v1"},)with (- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),+ mock_anti_ssrf_dns_lookup(resolves_to=["8.8.8.8"]),patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,patch("httpx.AsyncHTTPTransport.handle_async_request",diff --git a/posthog/test/anti_ssrf.py b/posthog/test/anti_ssrf.pynew file mode 100644index 000000000000..c70532efcbf9--- /dev/null+++ b/posthog/test/anti_ssrf.py@@ -0,0 +1,30 @@+from collections.abc import Iterable+from ipaddress import IPv4Address, IPv6Address, ip_address+from typing import TYPE_CHECKING++from unittest.mock import MagicMock, patch++if TYPE_CHECKING:+ from unittest.mock import _patch++PUBLIC_TEST_IP = ip_address("93.184.216.34")+++def mock_anti_ssrf_dns_lookup(+ resolves_to: Iterable[str | IPv4Address | IPv6Address] = (PUBLIC_TEST_IP,),+) -> "_patch[MagicMock]":+ """Replace only the DNS lookup of the anti-SSRF guard in `posthog.security.url_validation`.++ The guard still runs in full: it parses the URL, checks the host, and rejects an internal address.+ Only the answer to "which addresses does this host name resolve to" comes from the test,+ so the test does not depend on real DNS and stays in control of what the guard sees.+ The default is a public address, which lets a URL through the guard.+ Pass an internal address to check that the guard blocks it, or an empty list for a host name that does not resolve.++ Use it as a class decorator, a method decorator or a context manager.+ As a decorator it passes the mock to the test method as an extra argument, like `unittest.mock.patch`.+ """+ return patch(+ "posthog.security.url_validation.resolve_host_ips",+ return_value={ip_address(ip) for ip in resolves_to},+ )diff --git a/products/ai_observability/backend/api/test/test_provider_keys.py b/products/ai_observability/backend/api/test/test_provider_keys.pyindex 300f4f7d16e6..6faa28196f05 100644--- a/products/ai_observability/backend/api/test/test_provider_keys.py+++ b/products/ai_observability/backend/api/test/test_provider_keys.py@@ -1,5 +1,4 @@import json-from ipaddress import ip_addressfrom uuid import uuid4from posthog.test.base import APIBaseTest@@ -15,6 +14,7 @@ from rest_framework import serializers, statusfrom posthog.constants import AvailableFeaturefrom posthog.models import Organization, OrganizationMembership, Project, Team, User+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom products.access_control.backend.models.access_control import AccessControlfrom products.ai_observability.backend.api.provider_keys import LLMProviderKeySerializer@@ -250,7 +250,7 @@ class TestLLMProviderKeyViewSet(APIBaseTest):)mock_validate.assert_called_once_with(provider, "sk-test-key-12345", team_id=self.team.id, **expected_config)- @patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")})+ @mock_anti_ssrf_dns_lookup(resolves_to=["8.8.8.8"])@patch("httpx.AsyncHTTPTransport.handle_async_request")def test_custom_system_one_connection_round_trip(self, request: Mock, _dns: Mock) -> None:body = json.dumps(diff --git a/products/ai_observability/backend/llm/providers/test/test_openai_compatible.py b/products/ai_observability/backend/llm/providers/test/test_openai_compatible.pyindex 3f0b30ff8a50..c2a4e19dd3be 100644--- a/products/ai_observability/backend/llm/providers/test/test_openai_compatible.py+++ b/products/ai_observability/backend/llm/providers/test/test_openai_compatible.py@@ -14,6 +14,7 @@ from temporalio.exceptions import CancelledErrorfrom posthog.security.pinned_requests import SSRFBlockedErrorfrom posthog.security.url_validation import UNRESOLVED_HOST_REASON, PinnedUrlVerdict+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom products.ai_observability.backend.llm.errors import (AuthenticationError,@@ -185,7 +186,7 @@ class TestOpenAICompatibleAdapter:def test_complete_reports_an_unresolved_host_as_retryable(self):adapter = OpenAICompatibleAdapter(base_url="https://llm.example.com/v1")- with patch("posthog.security.url_validation.resolve_host_ips", return_value=set()):+ with mock_anti_ssrf_dns_lookup(resolves_to=[]):with pytest.raises(ProviderHostUnresolvedError):adapter.complete(_completion_request(), "test-key", AnalyticsContext())diff --git a/products/ai_observability/backend/llm/providers/test/test_openai_decisions.py b/products/ai_observability/backend/llm/providers/test/test_openai_decisions.pyindex c24031317a5a..33798f6c17fd 100644--- a/products/ai_observability/backend/llm/providers/test/test_openai_decisions.py+++ b/products/ai_observability/backend/llm/providers/test/test_openai_decisions.py@@ -2,7 +2,6 @@ import jsonimport asynciofrom collections.abc import Iteratorfrom contextlib import nullcontext-from ipaddress import ip_addressimport pytestfrom unittest.mock import patch@@ -20,6 +19,7 @@ from posthog.llm.system_one import (ScoreAnswer,ScoreQuestion,)+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom products.ai_observability.backend.llm.errors import (AuthenticationError,@@ -36,7 +36,7 @@ from products.ai_observability.backend.llm.providers.openai_decisions import Ope@pytest.fixture(autouse=True)def pin_endpoint() -> Iterator[None]:- with patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}):+ with mock_anti_ssrf_dns_lookup(resolves_to=["8.8.8.8"]):yield@@ -252,9 +252,7 @@ def test_http_errors_keep_retryable_and_terminal_failures_distinct(def test_transport_failure_is_retryable(error: httpx.RequestError | None) -> None:with (patch("httpx.AsyncHTTPTransport.handle_async_request", side_effect=error),- patch("posthog.security.url_validation.resolve_host_ips", return_value=set())- if error is None- else nullcontext(),+ mock_anti_ssrf_dns_lookup(resolves_to=[]) if error is None else nullcontext(),pytest.raises(ProviderConnectionError),):OpenAIDecisionAdapter().evaluate(diff --git a/products/ai_observability/backend/llm/test/test_decisions.py b/products/ai_observability/backend/llm/test/test_decisions.pyindex 4ce2ea0164a0..57fe1153dabc 100644--- a/products/ai_observability/backend/llm/test/test_decisions.py+++ b/products/ai_observability/backend/llm/test/test_decisions.py@@ -1,7 +1,6 @@import jsonfrom collections.abc import Iteratorfrom contextlib import nullcontext-from ipaddress import ip_addressfrom typing import Literalimport pytest@@ -12,6 +11,7 @@ from django.test import override_settingsimport httpxfrom posthog.llm.system_one import NoulAnswer, NoulQuestion, ScoreAnswer, ScoreQuestion+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom products.ai_observability.backend.llm.client import Clientfrom products.ai_observability.backend.llm.decisions import (@@ -41,7 +41,7 @@ def _response(status: int, body: dict[str, object] | str = "") -> httpx.Response@pytest.fixture(autouse=True)def public_endpoint_dns() -> Iterator[None]:with (- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),+ mock_anti_ssrf_dns_lookup(resolves_to=["8.8.8.8"]),):yield@@ -302,9 +302,7 @@ def test_endpoint_resolution_errors() -> None:with (override_settings(DEBUG=False, TEST=False),- patch(- "posthog.security.url_validation.resolve_host_ips", return_value={ip_address(address)} if address else set()- ),+ mock_anti_ssrf_dns_lookup(resolves_to=[address] if address else []),patch("httpx.AsyncHTTPTransport.handle_async_request") as request,pytest.raises(error_type),):@@ -397,7 +395,7 @@ def test_invalid_endpoint_is_rejected_before_sending_credentials(base_url: str)def test_private_endpoint_is_blocked(base_url: str) -> None:with (override_settings(DEBUG=False, TEST=False),- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("127.0.0.1")}),+ mock_anti_ssrf_dns_lookup(resolves_to=["127.0.0.1"]),patch("httpx.AsyncHTTPTransport.handle_async_request") as request,):state, _ = DecisionClient.validate_key("example-token", base_url=base_url, model="custom-model")diff --git a/products/data_warehouse/backend/tests/api/test_table.py b/products/data_warehouse/backend/tests/api/test_table.pyindex 451a8ef02f5f..d334789f73b2 100644--- a/products/data_warehouse/backend/tests/api/test_table.py+++ b/products/data_warehouse/backend/tests/api/test_table.py@@ -18,6 +18,7 @@ from rest_framework.test import APIRequestFactoryfrom posthog.models import Teamfrom posthog.models.activity_logging.activity_log import ActivityLog+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom products.data_warehouse.backend.direct_postgres import DIRECT_POSTGRES_URL_PATTERNfrom products.data_warehouse.backend.presentation.views.table import (@@ -33,8 +34,6 @@ from products.warehouse_sources.backend.facade.models import (ExternalDataSource,)-PUBLIC_IP = {ipaddress.ip_address("93.184.216.34")}-class TestResolveCreatedVia(SimpleTestCase):@parameterized.expand(@@ -158,7 +157,7 @@ class TestTable(APIBaseTest):):with (patch("posthog.security.url_validation.is_dev_mode", return_value=False),- patch("posthog.security.url_validation.resolve_host_ips", return_value=resolved_ips),+ mock_anti_ssrf_dns_lookup(resolves_to=resolved_ips),patch.object(DataWarehouseTable, "get_columns") as patch_get_columns,):response = self.client.post(@@ -999,7 +998,7 @@ class TestTable(APIBaseTest):with (patch("posthog.security.url_validation.is_dev_mode", return_value=False),- patch("posthog.security.url_validation.resolve_host_ips", return_value=PUBLIC_IP),+ mock_anti_ssrf_dns_lookup(),):response = self.client.patch(f"/api/projects/{self.team.id}/warehouse_tables/{table.id}",@@ -1052,7 +1051,7 @@ class TestTable(APIBaseTest):with (patch("posthog.security.url_validation.is_dev_mode", return_value=False),- patch("posthog.security.url_validation.resolve_host_ips", return_value=PUBLIC_IP),+ mock_anti_ssrf_dns_lookup(),):response = self.client.patch(f"/api/projects/{self.team.id}/warehouse_tables/{table.id}",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 24d8d31c42fd..bd9c2e24ff64 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,4 @@import io-import ipaddressfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch@@ -12,6 +11,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.models.team import Team+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom products.warehouse_sources.backend.facade.api import FILE_FORMAT_READ_HINTSfrom products.warehouse_sources.backend.facade.testing import (@@ -262,10 +262,7 @@ class TestCreateTableFromUpload(APIBaseTest):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")},- ),+ mock_anti_ssrf_dns_lookup(),):response = self.client.patch(f"/api/environments/{self.team.pk}/warehouse_tables/{table.id}",diff --git a/products/exports/backend/api/test/test_exports.py b/products/exports/backend/api/test/test_exports.pyindex ec46a24f91aa..6a6e6cbd0836 100644--- a/products/exports/backend/api/test/test_exports.py+++ b/products/exports/backend/api/test/test_exports.py@@ -1,5 +1,4 @@import asyncio-import ipaddressfrom contextlib import nullcontextfrom datetime import datetime, timedeltafrom typing import Literal, Optional@@ -38,6 +37,7 @@ from posthog.settings import ()from posthog.tasks import exporterfrom posthog.temporal.session_replay.rasterize_recording.types import RASTERIZE_WORKFLOW_TIMEOUT+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom posthog.test.insight_queries import browser_filtered_pageview_queryfrom products.access_control.backend.models.access_control import AccessControl@@ -2037,10 +2037,9 @@ class TestExportHeatmapSSRFValidation(APIBaseTest):)def test_accepts_valid_heatmap_url(self, _name: str, url: str) -> None:with (- patch("posthog.security.url_validation.resolve_host_ips") as mock_resolve,+ mock_anti_ssrf_dns_lookup(),patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow"),):- mock_resolve.return_value = {ipaddress.ip_address("93.184.216.34")}response = self.client.post(f"/api/projects/{self.team.id}/exports",{@@ -2059,10 +2058,9 @@ class TestExportHeatmapSSRFValidation(APIBaseTest):def test_accepts_screenshot_url_with_default_site_port(self, _name: str, site_url: str, heatmap_url: str) -> None:with (self.settings(SITE_URL=site_url),- patch("posthog.security.url_validation.resolve_host_ips") as mock_resolve,+ mock_anti_ssrf_dns_lookup(),patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow"),):- mock_resolve.return_value = {ipaddress.ip_address("93.184.216.34")}response = self.client.post(f"/api/projects/{self.team.id}/exports",{diff --git a/products/exports/backend/tasks/test/test_image_exporter.py b/products/exports/backend/tasks/test/test_image_exporter.pyindex 61acd3c87909..dfc5aa755a4b 100644--- a/products/exports/backend/tasks/test/test_image_exporter.py+++ b/products/exports/backend/tasks/test/test_image_exporter.py@@ -1,4 +1,3 @@-import ipaddressfrom datetime import datetimefrom typing import Anyfrom urllib.parse import parse_qs, urlparse@@ -30,6 +29,7 @@ from posthog.settings import ()from posthog.storage import object_storagefrom posthog.storage.object_storage import ObjectStorageError+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom products.access_control.backend.facade.user_access_control import UserAccessControlErrorfrom products.dashboards.backend.models.dashboard import Dashboard@@ -684,9 +684,7 @@ class TestHeatmapExportURLEncoding(APIBaseTest):with (self.settings(OBJECT_STORAGE_ENABLED=False),- patch(- "posthog.security.url_validation.resolve_host_ips", return_value={ipaddress.ip_address("93.184.216.34")}- ),+ mock_anti_ssrf_dns_lookup(),):image_exporter.export_image(exported_asset)diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 78aac1b61813..8da1c30cd625 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport jsonfrom datetime import UTC, datetime, timedeltafrom decimal import Decimal-from ipaddress import ip_addressfrom typing import TYPE_CHECKINGfrom uuid import UUID, uuid4@@ -41,6 +40,7 @@ from posthog.temporal.oauth import (PosthogMcpScopes,create_oauth_access_token_for_user,)+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControlfrom products.engineering_analytics.backend.facade.contracts import GitHubTeamMembership, GitHubTeamRoster@@ -5825,9 +5825,7 @@ _LIGHTHOUSE_REPORT = {class TestScoutHarnessLighthouseAPI(APIBaseTest):def setUp(self) -> None:super().setUp()- self.enterContext(- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})- )+ self.enterContext(mock_anti_ssrf_dns_lookup())# lighthouse-audit requires `signal_scout_internal:write` — session auth is rejected._authenticate_as_scout(self)diff --git a/products/signals/backend/test/test_scout_harness_tools.py b/products/signals/backend/test/test_scout_harness_tools.pyindex 65d92217b8b6..e2127f29d10e 100644--- a/products/signals/backend/test/test_scout_harness_tools.py+++ b/products/signals/backend/test/test_scout_harness_tools.py@@ -4,7 +4,6 @@ import uuidimport dataclassesfrom collections.abc import Iteratorfrom datetime import timedelta-from ipaddress import ip_addressfrom typing import TYPE_CHECKINGfrom urllib.parse import quote@@ -26,6 +25,7 @@ from posthog.egress.limiter.policies import Priorityfrom posthog.models.scoping import team_scopefrom posthog.settings.signals import _parse_team_idsfrom posthog.sync import database_sync_to_async+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom products.signals.backend.artefact_schemas import ReportLinkfrom products.signals.backend.enums import ReportLinkKind@@ -1968,7 +1968,7 @@ def _no_flag_payload():class TestLighthouseAudit:@pytest.fixture(autouse=True)def mock_target_dns(self) -> Iterator[None]:- with patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")}):+ with mock_anti_ssrf_dns_lookup():yielddef _audit(self, payload: dict, *, url: str = "https://posthog.com/pricing", form_factor: str = "desktop"):diff --git a/products/tasks/backend/tests/test_presentation_serializers.py b/products/tasks/backend/tests/test_presentation_serializers.pyindex 7447e90fec5b..443f9cc38dc0 100644--- a/products/tasks/backend/tests/test_presentation_serializers.py+++ b/products/tasks/backend/tests/test_presentation_serializers.py@@ -1,5 +1,4 @@import base64-import ipaddressfrom types import SimpleNamespaceimport time_machine@@ -19,6 +18,7 @@ from posthog.temporal.oauth import (ARRAY_APP_CLIENT_ID_US,POSTHOG_DESKTOP_MOBILE_APP_CLIENT_ID_US,)+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.model_catalogue import GatewayModel@@ -149,7 +149,7 @@ class TestTaskRunCreateRequestSerializer(SimpleTestCase):])@time_machine.travel("2026-09-18T12:00:00Z", tick=False)- @patch("posthog.security.url_validation.resolve_host_ips", return_value={ipaddress.ip_address("93.184.216.34")})+ @mock_anti_ssrf_dns_lookup()def test_schedule_rejects_unsupported_inputs(self, name: str, payload: dict, field: str, _resolve_host_ips) -> None:serializer = TaskRunCreateRequestSerializer(data={"scheduled_at": "2026-09-19T12:00:00", **payload})with patch(@@ -250,10 +250,7 @@ class TestTaskRunCreateRequestSerializer(SimpleTestCase):if not accepted:assert "claude_model_access" in serializer.errors- @patch(- "posthog.security.url_validation.resolve_host_ips",- return_value={ipaddress.ip_address("93.184.216.34")},- )+ @mock_anti_ssrf_dns_lookup()def test_deduplicates_imported_mcp_server_host_resolution(self, mock_resolve_host_ips) -> None:serializer = TaskRunCreateRequestSerializer(data={diff --git a/products/warehouse_sources/backend/tests/test_util.py b/products/warehouse_sources/backend/tests/test_util.pyindex 0ffe474bc43b..1aebef61876c 100644--- a/products/warehouse_sources/backend/tests/test_util.py+++ b/products/warehouse_sources/backend/tests/test_util.py@@ -1,5 +1,3 @@-import ipaddress-from posthog.test.base import BaseTestfrom unittest.mock import patch@@ -8,6 +6,8 @@ from django.test import SimpleTestCase, override_settingsfrom parameterized import parameterized+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup+from products.warehouse_sources.backend.models.credential import DataWarehouseCredentialfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -21,8 +21,6 @@ from products.warehouse_sources.backend.models.util import ()from products.warehouse_sources.backend.types import ExternalDataSourceType-PUBLIC_IP = {ipaddress.ip_address("93.184.216.34")}-class TestReconstructOrderedColumns(SimpleTestCase):@parameterized.expand(@@ -158,7 +156,7 @@ class TestValidateWarehouseTableUrlPattern(SimpleTestCase):def test_allows_a_customers_own_bucket(self, _name: str, url_pattern: str) -> None:with (patch("posthog.security.url_validation.is_dev_mode", return_value=False),- patch("posthog.security.url_validation.resolve_host_ips", return_value=PUBLIC_IP),+ mock_anti_ssrf_dns_lookup(),):is_valid, error_message = validate_warehouse_table_url_pattern(url_pattern)@@ -209,7 +207,7 @@ class TestValidateWarehouseTableUrlPattern(SimpleTestCase):# 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),+ mock_anti_ssrf_dns_lookup(),):is_valid, error_message = validate_warehouse_table_url_pattern("https://s3.us-east-1.amazonaws.com/acme-exports/reports/q1.2026/data.csv"@@ -252,10 +250,7 @@ class TestValidateWarehouseTableUrlPattern(SimpleTestCase):# 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")},- ),+ mock_anti_ssrf_dns_lookup(resolves_to=["10.0.0.5"]),):is_valid, error_message = validate_warehouse_table_url_pattern("https://internal-alias.example/x.csv")diff --git a/products/warehouse_sources/sources/pganalyze/tests/test_pganalyze.py b/products/warehouse_sources/sources/pganalyze/tests/test_pganalyze.pyindex 84a24b5752ef..2f913a8474f7 100644--- a/products/warehouse_sources/sources/pganalyze/tests/test_pganalyze.py+++ b/products/warehouse_sources/sources/pganalyze/tests/test_pganalyze.py@@ -1,4 +1,3 @@-import ipaddressfrom datetime import UTC, datetimefrom typing import Any@@ -24,11 +23,10 @@ from products.warehouse_sources.sources.sdk.testing import (RecordedRequest,ScriptedResponse,SourceDriver,+ mock_anti_ssrf_dns_lookup,scripted_network,)-_PUBLIC_IP = {ipaddress.ip_address("93.184.216.34")}-def _mock_response(status_code: int = 200, json_data: dict | None = None, text: str = "") -> mock.MagicMock:response = mock.MagicMock()@@ -166,14 +164,14 @@ class TestResolveApiUrl:def test_defaults_to_public_api_when_none(self):with (mock.patch("posthog.security.url_validation.is_dev_mode", return_value=False),- mock.patch("posthog.security.url_validation.resolve_host_ips", return_value=_PUBLIC_IP),+ mock_anti_ssrf_dns_lookup(),):assert _resolve_api_url(None) == PGANALYZE_API_URLdef test_defaults_to_public_api_when_empty_string(self):with (mock.patch("posthog.security.url_validation.is_dev_mode", return_value=False),- mock.patch("posthog.security.url_validation.resolve_host_ips", return_value=_PUBLIC_IP),+ mock_anti_ssrf_dns_lookup(),):assert _resolve_api_url("") == PGANALYZE_API_URLassert _resolve_api_url(" ") == PGANALYZE_API_URL@@ -181,7 +179,7 @@ class TestResolveApiUrl:def test_accepts_well_formed_public_url(self):with (mock.patch("posthog.security.url_validation.is_dev_mode", return_value=False),- mock.patch("posthog.security.url_validation.resolve_host_ips", return_value=_PUBLIC_IP),+ mock_anti_ssrf_dns_lookup(),):url = "https://app.pganalyze.com/graphql"assert _resolve_api_url(url) == urldiff --git a/products/warehouse_sources/sources/sdk/testing.py b/products/warehouse_sources/sources/sdk/testing.pyindex 0191e95604b8..74b7b13b6494 100644--- a/products/warehouse_sources/sources/sdk/testing.py+++ b/products/warehouse_sources/sources/sdk/testing.py@@ -8,6 +8,7 @@ on a re-export changes nothing.from posthog.hogql.parser import parse_selectfrom posthog.models.integration.model import Integration+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom products.warehouse_sources.backend.temporal.data_imports.sources.common import boundary_checkpoint, resumablefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches@@ -60,6 +61,7 @@ __all__ = ["build_default_schemas","build_default_sync_settings","error_message_matches",+ "mock_anti_ssrf_dns_lookup","parse_select","rest_client","resumable",diff --git a/products/web_analytics/backend/api/test/test_screenshot_settings.py b/products/web_analytics/backend/api/test/test_screenshot_settings.pyindex b90a4579c7cf..ae8e952ae5b1 100644--- a/products/web_analytics/backend/api/test/test_screenshot_settings.py+++ b/products/web_analytics/backend/api/test/test_screenshot_settings.py@@ -1,5 +1,3 @@-from ipaddress import ip_address-from posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch@@ -13,6 +11,7 @@ from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team_heatmap_config import TeamHeatmapConfigfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookupfrom products.access_control.backend.models.access_control import AccessControlfrom products.web_analytics.backend.presentation.views.screenshot_settings import (@@ -193,7 +192,7 @@ class TestScreenshotSettings(APIBaseTest):@parameterized.expand([("attacker.example", False), ("www.example.com", True)])@override_settings(**BROWSERLESS_SETTINGS)- @patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+ @mock_anti_ssrf_dns_lookup()@patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")@patch("products.web_analytics.backend.api.heatmaps_api.generate_heatmap_screenshot.delay")def test_editor_renders_only_send_credentials_to_admin_approved_hosts(