Skip to content

: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.

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.py
index 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 json
import time
-from ipaddress import ip_address
from 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_lookup
from 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.py
index 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_address
from unittest.mock import MagicMock, patch
@@ -16,6 +15,7 @@ from posthog.models.activity_logging.utils import ActivityCredential, activity_s
from posthog.models.oauth import OAuthApplication
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.user import User
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from ee.api.agentic_provisioning.authentication import ProvisioningAuthentication
from 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.py
index 8c9c7605386a..bfd42e8eb9fb 100644
--- a/posthog/api/oauth/test_cimd.py
+++ b/posthog/api/oauth/test_cimd.py
@@ -1,7 +1,6 @@
import json
import base64
import hashlib
-from ipaddress import ip_address
from typing import cast
from urllib.parse import urlencode
@@ -44,6 +43,7 @@ from posthog.models.oauth import (
)
from posthog.models.oauth_provisioning import PartnerTier
from posthog.scopes import OAUTH_SCOPES_HIDDEN, PRIVILEGED_SCOPES
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
VALID_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 republished
by 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.py
index 84c308ce9ce6..3b9bfc429893 100644
--- a/posthog/api/oauth/test_dcr.py
+++ b/posthog/api/oauth/test_dcr.py
@@ -1,6 +1,5 @@
import base64
import hashlib
-import ipaddress
from urllib.parse import parse_qs, urlparse
from posthog.test.base import APIBaseTest
@@ -12,8 +11,7 @@ from rest_framework.test import APIClient
from posthog.api.oauth.client_name import sanitize_client_name
from 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_lookup
class 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 limit
with 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.py
index 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 SimpleTestCase
from 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.py
index 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_h
from posthog.temporal.ai_observability.sentiment.schema import SentimentResult
from posthog.temporal.common.errors import NonReportableError
from posthog.temporal.common.posthog_client import is_expected_activity_failure
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from products.access_control.backend.models.access_control import AccessControl
from 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.py
new file mode 100644
index 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.py
index 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_address
from uuid import uuid4
from posthog.test.base import APIBaseTest
@@ -15,6 +14,7 @@ from rest_framework import serializers, status
from posthog.constants import AvailableFeature
from posthog.models import Organization, OrganizationMembership, Project, Team, User
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from products.access_control.backend.models.access_control import AccessControl
from 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.py
index 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 CancelledError
from posthog.security.pinned_requests import SSRFBlockedError
from posthog.security.url_validation import UNRESOLVED_HOST_REASON, PinnedUrlVerdict
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from 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.py
index 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 json
import asyncio
from collections.abc import Iterator
from contextlib import nullcontext
-from ipaddress import ip_address
import pytest
from 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_lookup
from 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.py
index 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 json
from collections.abc import Iterator
from contextlib import nullcontext
-from ipaddress import ip_address
from typing import Literal
import pytest
@@ -12,6 +11,7 @@ from django.test import override_settings
import httpx
from posthog.llm.system_one import NoulAnswer, NoulQuestion, ScoreAnswer, ScoreQuestion
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from products.ai_observability.backend.llm.client import Client
from 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.py
index 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 APIRequestFactory
from posthog.models import Team
from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from products.data_warehouse.backend.direct_postgres import DIRECT_POSTGRES_URL_PATTERN
from 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.py
index 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 ipaddress
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -12,6 +11,7 @@ from parameterized import parameterized
from rest_framework import status
from posthog.models.team import Team
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from products.warehouse_sources.backend.facade.api import FILE_FORMAT_READ_HINTS
from 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.py
index 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 ipaddress
from contextlib import nullcontext
from datetime import datetime, timedelta
from typing import Literal, Optional
@@ -38,6 +37,7 @@ from posthog.settings import (
)
from posthog.tasks import exporter
from posthog.temporal.session_replay.rasterize_recording.types import RASTERIZE_WORKFLOW_TIMEOUT
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from posthog.test.insight_queries import browser_filtered_pageview_query
from 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.py
index 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 ipaddress
from datetime import datetime
from typing import Any
from urllib.parse import parse_qs, urlparse
@@ -30,6 +29,7 @@ from posthog.settings import (
)
from posthog.storage import object_storage
from posthog.storage.object_storage import ObjectStorageError
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from products.access_control.backend.facade.user_access_control import UserAccessControlError
from 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.py
index 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 annotations
import json
from datetime import UTC, datetime, timedelta
from decimal import Decimal
-from ipaddress import ip_address
from typing import TYPE_CHECKING
from 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_lookup
from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl
from 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.py
index 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 uuid
import dataclasses
from collections.abc import Iterator
from datetime import timedelta
-from ipaddress import ip_address
from typing import TYPE_CHECKING
from urllib.parse import quote
@@ -26,6 +25,7 @@ from posthog.egress.limiter.policies import Priority
from posthog.models.scoping import team_scope
from posthog.settings.signals import _parse_team_ids
from posthog.sync import database_sync_to_async
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from products.signals.backend.artefact_schemas import ReportLink
from 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():
yield
def _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.py
index 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 ipaddress
from types import SimpleNamespace
import 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_lookup
from products.tasks.backend.facade import api as tasks_facade
from 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.py
index 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 BaseTest
from unittest.mock import patch
@@ -8,6 +6,8 @@ from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
+
from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from 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.py
index 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 ipaddress
from datetime import UTC, datetime
from 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_URL
def 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_URL
assert _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) == url
diff --git a/products/warehouse_sources/sources/sdk/testing.py b/products/warehouse_sources/sources/sdk/testing.py
index 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_select
from posthog.models.integration.model import Integration
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from products.warehouse_sources.backend.temporal.data_imports.sources.common import boundary_checkpoint, resumable
from 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.py
index 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 APIBaseTest
from unittest.mock import MagicMock, patch
@@ -13,6 +11,7 @@ from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.team_heatmap_config import TeamHeatmapConfig
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from products.access_control.backend.models.access_control import AccessControl
from 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(