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): stop guard-checked tests from reaching real dns (#128033)

Thomas Obermüllerad4702e17794
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index b8ab7f5d8a92..8c3e1fb1e929 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -28,7 +28,7 @@ from redis.exceptions import RedisError
from rest_framework import status
from posthog.api.oauth import OAuthAuthorizationSerializer
-from posthog.api.oauth.cimd import CIMD_SUPPORTED_AUTH_METHODS
+from posthog.api.oauth.cimd import CIMD_SUPPORTED_AUTH_METHODS, refresh_cimd_metadata_task
from posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER
from posthog.api.oauth.metadata import authorization_server_metadata, openid_provider_metadata
from posthog.api.oauth.views import OAuthTokenView, OAuthValidator, _token_error_code
@@ -85,6 +85,8 @@ def private_pem_to_public_pem(private_key_pem: str) -> str:
class TestOAuthAPI(APIBaseTest):
def setUp(self):
super().setUp()
+ # Celery runs the stale-cache CIMD refresh inline, and it would fetch the partner URL over the network.
+ self.enterContext(patch.object(refresh_cimd_metadata_task, "delay"))
self.confidential_application = OAuthApplication.objects.create(
name="Test Confidential App",
diff --git a/posthog/api/test/test_identity_provider_config.py b/posthog/api/test/test_identity_provider_config.py
index 4c26ee7edac3..09e7b7725c0b 100644
--- a/posthog/api/test/test_identity_provider_config.py
+++ b/posthog/api/test/test_identity_provider_config.py
@@ -16,6 +16,7 @@ from posthog.models import (
)
from posthog.models.scim_provisioned_user import SCIMProvisionedUser
from posthog.models.scim_request_log import SCIMRequestLog
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
class TestIdentityProviderConfigAPI(APIBaseTest):
@@ -428,14 +429,15 @@ class TestIdentityProviderConfigAPI(APIBaseTest):
self._make_admin()
self._enable_features(AvailableFeature.XAA_AUTHENTICATION)
config = IdentityProviderConfig.objects.create(organization=self.organization)
- response = self.client.patch(
- f"/api/organizations/@current/identity_provider_configs/{config.id}/",
- {
- "id_jag_issuer_url": "https://example.com/",
- "id_jag_jwks_url": "https://example.com/keys.json",
- "id_jag_allowed_clients": ["client-a"],
- },
- )
+ with mock_anti_ssrf_dns_lookup():
+ response = self.client.patch(
+ f"/api/organizations/@current/identity_provider_configs/{config.id}/",
+ {
+ "id_jag_issuer_url": "https://example.com/",
+ "id_jag_jwks_url": "https://example.com/keys.json",
+ "id_jag_allowed_clients": ["client-a"],
+ },
+ )
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["id_jag_issuer_url"], "https://example.com")
self.assertTrue(response.json()["has_id_jag"])
@@ -443,10 +445,11 @@ class TestIdentityProviderConfigAPI(APIBaseTest):
def test_cannot_configure_id_jag_without_feature(self):
self._make_admin()
config = IdentityProviderConfig.objects.create(organization=self.organization)
- response = self.client.patch(
- f"/api/organizations/@current/identity_provider_configs/{config.id}/",
- {"id_jag_issuer_url": "https://example.com"},
- )
+ with mock_anti_ssrf_dns_lookup():
+ response = self.client.patch(
+ f"/api/organizations/@current/identity_provider_configs/{config.id}/",
+ {"id_jag_issuer_url": "https://example.com"},
+ )
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["attr"], "id_jag_issuer_url")
diff --git a/products/business_knowledge/backend/tests/test_crawl_ingest.py b/products/business_knowledge/backend/tests/test_crawl_ingest.py
index 4778d2608fad..b264b690a149 100644
--- a/products/business_knowledge/backend/tests/test_crawl_ingest.py
+++ b/products/business_knowledge/backend/tests/test_crawl_ingest.py
@@ -31,6 +31,8 @@ from django.test import SimpleTestCase
from parameterized import parameterized
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
+
from products.business_knowledge.backend import crawl, discover, logic, url_fetch
from products.business_knowledge.backend.logic import create_crawl_source, ingest_source, refresh_source
from products.business_knowledge.backend.models import (
@@ -395,6 +397,10 @@ class TestIterFetch(SimpleTestCase):
class TestCreateCrawlSource(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.enterContext(mock_anti_ssrf_dns_lookup())
+
def test_happy_path_indexes_all_discovered_pages(self) -> None:
sitemap = _sitemap_xml(["https://example.com/a", "https://example.com/b", "https://example.com/c"])
behaviours: dict[str, url_fetch.FetchResult | Exception] = {
@@ -592,6 +598,10 @@ class TestCreateCrawlSource(APIBaseTest):
class TestRefreshCrawlSource(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.enterContext(mock_anti_ssrf_dns_lookup())
+
def _seed(self, sitemap_urls: list[str]) -> KnowledgeSource:
sitemap = _sitemap_xml(sitemap_urls)
behaviours: dict[str, url_fetch.FetchResult | Exception] = {
@@ -1052,6 +1062,10 @@ class TestChunkIdIsolation(APIBaseTest):
sources). `_chunk_id` now includes `source_id` to isolate namespaces.
"""
+ def setUp(self) -> None:
+ super().setUp()
+ self.enterContext(mock_anti_ssrf_dns_lookup())
+
def test_two_sources_same_url_do_not_collide(self) -> None:
sitemap_a = _sitemap_xml(["https://example.com/shared"])
sitemap_b = _sitemap_xml(["https://example.com/shared"])
diff --git a/products/exports/backend/api/test/test_exports.py b/products/exports/backend/api/test/test_exports.py
index 6a6e6cbd0836..9d1089468b8b 100644
--- a/products/exports/backend/api/test/test_exports.py
+++ b/products/exports/backend/api/test/test_exports.py
@@ -112,7 +112,7 @@ class TestExports(APIBaseTest):
def test_screenshot_heatmap_export_requires_same_origin_url(
self, _name: str, site_url: str, heatmap_url: str, expected_status: int, mock_exporter_task
) -> None:
- with self.settings(SITE_URL=site_url):
+ with self.settings(SITE_URL=site_url), mock_anti_ssrf_dns_lookup():
response = self.client.post(
f"/api/projects/{self.team.id}/exports/",
{
diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.py
index 342545c598c5..18bcfa9fbed8 100644
--- a/products/mcp_store/backend/test/test_api.py
+++ b/products/mcp_store/backend/test/test_api.py
@@ -25,6 +25,7 @@ from posthog.models.instance_setting import override_instance_config
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.organization import OrganizationMembership
from posthog.security.url_validation import PinnedUrlVerdict
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from posthog.test.authentication_checks import covers_authentication
from products.mcp_store.backend.agents import create_gateway_agent_token, sync_built_in_agents
@@ -2941,7 +2942,8 @@ class TestInstallCustomAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert response.status_code == status.HTTP_201_CREATED
assert response.json()["auth_type"] == "api_key"
- def test_install_custom_none_auth_type_rejected(self):
+ @mock_anti_ssrf_dns_lookup()
+ def test_install_custom_none_auth_type_rejected(self, _dns):
response = self.client.post(
f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",
data={"name": "Server", "url": "https://mcp.example.com", "auth_type": "none"},
@@ -3016,7 +3018,8 @@ class TestInstallCustomAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
assert response.status_code == status.HTTP_201_CREATED
- def test_install_custom_rejects_invalid_posthog_code_callback_url(self):
+ @mock_anti_ssrf_dns_lookup()
+ def test_install_custom_rejects_invalid_posthog_code_callback_url(self, _dns):
response = self.client.post(
f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",
data={
diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.py
index cdc930bb0115..0caba7b1ffb1 100644
--- a/products/mcp_store/backend/test/test_facade.py
+++ b/products/mcp_store/backend/test/test_facade.py
@@ -1115,9 +1115,16 @@ class TestCallMemberServerTool(BaseTest):
@parameterized.expand(
[("disabled", "do_not_use", None, "blocked"), ("removed", "needs_approval", "removed", "tool_missing")]
)
+ @patch("products.mcp_store.backend.tools.fetch_upstream_tools", return_value=[])
@patch("products.mcp_store.backend.facade.api.call_upstream_tool")
def test_approval_does_not_override_blocks(
- self, _name: str, approval_state: str, removed: str | None, expected: str, mock_call: MagicMock
+ self,
+ _name: str,
+ approval_state: str,
+ removed: str | None,
+ expected: str,
+ mock_call: MagicMock,
+ _mock_fetch: MagicMock,
) -> None:
installation = self._installation()
self._tool(installation)
diff --git a/products/mcp_store/backend/test/test_oauth.py b/products/mcp_store/backend/test/test_oauth.py
index 3e05e1994d1e..2b520f1ac176 100644
--- a/products/mcp_store/backend/test/test_oauth.py
+++ b/products/mcp_store/backend/test/test_oauth.py
@@ -10,6 +10,7 @@ import httpx
from parameterized import parameterized
from posthog.models.instance_setting import override_instance_config
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from products.mcp_store.backend.models import MCPServerInstallation, MCPServerTemplate
from products.mcp_store.backend.oauth import (
@@ -120,7 +121,10 @@ class TestRefreshOauthToken(SimpleTestCase):
str(status_code), request=httpx.Request("POST", "https://example.com"), response=mock_resp
)
- with patch("products.mcp_store.backend.oauth.httpx.Client.post", return_value=mock_resp):
+ with (
+ patch("products.mcp_store.backend.oauth.httpx.Client.post", return_value=mock_resp),
+ mock_anti_ssrf_dns_lookup(),
+ ):
with self.assertRaises(TokenRefreshError) as ctx:
refresh_oauth_token(
token_url="https://example.com/token",
@@ -136,7 +140,10 @@ class TestRefreshOauthToken(SimpleTestCase):
mock_resp.json.return_value = {"error": "invalid_grant"}
mock_resp.raise_for_status = MagicMock()
- with patch("products.mcp_store.backend.oauth.httpx.Client.post", return_value=mock_resp):
+ with (
+ patch("products.mcp_store.backend.oauth.httpx.Client.post", return_value=mock_resp),
+ mock_anti_ssrf_dns_lookup(),
+ ):
with self.assertRaises(TokenRefreshError) as ctx:
refresh_oauth_token(
token_url="https://example.com/token",
diff --git a/products/warehouse_sources/sources/pganalyze/tests/test_pganalyze.py b/products/warehouse_sources/sources/pganalyze/tests/test_pganalyze.py
index 2f913a8474f7..b9fed60925d1 100644
--- a/products/warehouse_sources/sources/pganalyze/tests/test_pganalyze.py
+++ b/products/warehouse_sources/sources/pganalyze/tests/test_pganalyze.py
@@ -105,7 +105,10 @@ class TestPostGraphql:
class TestValidateCredentials:
def test_returns_true_on_valid_credentials(self):
- with mock.patch("products.warehouse_sources.sources.pganalyze.pganalyze.make_tracked_session") as mock_sess:
+ with (
+ mock.patch("products.warehouse_sources.sources.pganalyze.pganalyze.make_tracked_session") as mock_sess,
+ mock_anti_ssrf_dns_lookup(),
+ ):
sess = mock.MagicMock()
sess.post.return_value = _mock_response(json_data={"data": {"getServers": []}})
mock_sess.return_value = sess
diff --git a/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py b/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py
index 2579f5990462..ca51581e3804 100644
--- a/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py
+++ b/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py
@@ -12,6 +12,7 @@ from parameterized import parameterized
from prometheus_client import REGISTRY
from posthog.models.team.team_heatmap_config import TeamHeatmapConfig
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from products.web_analytics.backend.api.heatmaps_utils import MAX_TARGET_WIDTHS, PREWARM_TTL
from products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmap
@@ -64,6 +65,7 @@ def _make_response(
class TestHeatmapScreenshotTask(APIBaseTest):
def setUp(self) -> None:
super().setUp()
+ self.enterContext(mock_anti_ssrf_dns_lookup())
# Stub ph_scoped_capture so tests don't spin up a real PostHog client, and record the events.
self.captured_events: list[dict] = []
diff --git a/products/web_analytics/backend/test/test_heatmap_access_control.py b/products/web_analytics/backend/test/test_heatmap_access_control.py
index e214a9645dee..d6a649ca86b0 100644
--- a/products/web_analytics/backend/test/test_heatmap_access_control.py
+++ b/products/web_analytics/backend/test/test_heatmap_access_control.py
@@ -17,6 +17,7 @@ from posthog.kafka_client.topics import KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS
from posthog.models.event.util import format_clickhouse_timestamp
from posthog.models.organization import OrganizationMembership
from posthog.models.user import User
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from products.access_control.backend.facade.user_access_control import ACCESS_CONTROL_RESOURCES, model_to_resource
from products.access_control.backend.models.access_control import AccessControl
@@ -37,6 +38,7 @@ class TestHeatmapResourceRegistration(SimpleTestCase):
class TestHeatmapAccessControl(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
+ self.enterContext(mock_anti_ssrf_dns_lookup())
self.organization.available_product_features = [
{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
diff --git a/products/web_analytics/backend/test/test_heatmap_screenshots.py b/products/web_analytics/backend/test/test_heatmap_screenshots.py
index a10e29fd15d9..182032e98833 100644
--- a/products/web_analytics/backend/test/test_heatmap_screenshots.py
+++ b/products/web_analytics/backend/test/test_heatmap_screenshots.py
@@ -22,6 +22,7 @@ from posthog.models import Team
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.rate_limit import HeatmapPreflightBurstRateThrottle
+from posthog.test.anti_ssrf import mock_anti_ssrf_dns_lookup
from products.exports.backend.models.exported_asset import ExportedAsset
from products.web_analytics.backend.api.heatmaps_api import SavedHeatmapCaptureRequestSerializer
@@ -37,6 +38,7 @@ from products.web_analytics.backend.tasks.heatmap_screenshot import (
class TestHeatmapsAPI(APIBaseTest):
def setUp(self):
super().setUp()
+ self.enterContext(mock_anti_ssrf_dns_lookup())
self.client = APIClient()
self.client.force_authenticate(user=self.user)