:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(auth): add missing network timeouts for sso, redis, and outbound requests (#69603)
Julian Bez75e8851852dd
diff --git a/ee/api/license.py b/ee/api/license.pyindex ad0a77259191..661120cd96d7 100644--- a/ee/api/license.py+++ b/ee/api/license.py@@ -30,7 +30,9 @@ class LicenseSerializer(serializers.ModelSerializer):extra_kwargs = {"key": {"write_only": True}}def validate(self, data):- validation = requests.post("https://license.posthog.com/licenses/activate", data={"key": data["key"]})+ validation = requests.post(+ "https://license.posthog.com/licenses/activate", data={"key": data["key"]}, timeout=10+ )resp = validation.json()user = self.context["request"].userif not validation.ok:@@ -71,7 +73,9 @@ class LicenseViewSet(def destroy(self, request: request.Request, *args, **kwargs) -> Response:license = self.get_object()- validation = requests.post("https://license.posthog.com/licenses/deactivate", data={"key": license.key})+ validation = requests.post(+ "https://license.posthog.com/licenses/deactivate", data={"key": license.key}, timeout=10+ )validation.raise_for_status()has_another_valid_license = License.objects.filter(valid_until__gte=now()).exclude(pk=license.pk).exists()diff --git a/ee/api/sentry_stats.py b/ee/api/sentry_stats.pyindex 13a042280d5d..36a9c0d95800 100644--- a/ee/api/sentry_stats.py+++ b/ee/api/sentry_stats.py@@ -24,7 +24,7 @@ def get_sentry_stats(start_time: str, end_time: str) -> tuple[dict, int]:params = {"start": start_time, "end": end_time, "sort": "freq", "utc": "true"}- response = requests.get(url=url, headers=headers, params=params).json()+ response = requests.get(url=url, headers=headers, params=params, timeout=10).json()counts = {}total_count = 0@@ -74,7 +74,7 @@ def get_tagged_issues_stats(for i in range(0, len(target_issues), pagination_chunk_size):groups = target_issues[i : i + pagination_chunk_size]params["groups"] = groups- response = requests.get(url=url, headers=headers, params=params).json()+ response = requests.get(url=url, headers=headers, params=params, timeout=10).json()# TODO: Confirm sentry always sends this informationfor item in response:diff --git a/ee/middleware.py b/ee/middleware.pyindex fd1e6ee82cdb..2b4c964c29aa 100644--- a/ee/middleware.py+++ b/ee/middleware.py@@ -225,7 +225,7 @@ def _exchange_code_for_token(request: HttpRequest, code: str) -> dict:"redirect_uri": request.build_absolute_uri("/admin/oauth2/callback"),"grant_type": "authorization_code",}- response = requests.post(token_url, data=data)+ response = requests.post(token_url, data=data, timeout=10)response.raise_for_status()return response.json()diff --git a/posthog/api/user.py b/posthog/api/user.pyindex 29a3f2894f05..8603fcd07a0c 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -1812,6 +1812,7 @@ def redirect_to_website(request):"lastName": request.user.last_name,},headers={"Content-Type": "application/json"},+ timeout=10,)if response.status_code == 200:diff --git a/posthog/cdp/services/icons.py b/posthog/cdp/services/icons.pyindex 7317577006d4..634938e7f85a 100644--- a/posthog/cdp/services/icons.py+++ b/posthog/cdp/services/icons.py@@ -27,6 +27,7 @@ class CDPIconsService:"token": settings.LOGO_DEV_TOKEN,"query": query,},+ timeout=10,)data = res.json() or []@@ -52,6 +53,7 @@ class CDPIconsService:params={"token": settings.LOGO_DEV_TOKEN,},+ timeout=10,)return HttpResponse(res.content, content_type=res.headers["Content-Type"])diff --git a/posthog/email.py b/posthog/email.pyindex 25d8be205b59..fa79d632dc9b 100644--- a/posthog/email.py+++ b/posthog/email.py@@ -203,7 +203,9 @@ def _send_via_http("message_data": properties,}- response = requests.post(f"{settings.CUSTOMER_IO_API_URL}/v1/send/email", headers=headers, json=payload)+ response = requests.post(+ f"{settings.CUSTOMER_IO_API_URL}/v1/send/email", headers=headers, json=payload, timeout=30+ )if response.status_code != 200:raise Exception(f"Customer.io API error: {response.status_code} - {response.text}")diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 77db5aea3ec4..1c83607bcbb8 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -779,6 +779,7 @@ class OauthIntegration:"grant_type": "authorization_code",},headers={"User-Agent": "PostHog/1.0 by PostHogTeam"},+ timeout=10,)# Pinterest uses HTTP Basic Auth for token exchange (base64-encoded client_id:client_secret)elif kind == "pinterest-ads":@@ -790,6 +791,7 @@ class OauthIntegration:"redirect_uri": OauthIntegration.redirect_uri(kind),"grant_type": "authorization_code",},+ timeout=10,)elif kind == "tiktok-ads":# TikTok Ads uses JSON request body instead of form data and maps 'code' to 'auth_code'@@ -801,6 +803,7 @@ class OauthIntegration:"auth_code": params["code"],},headers={"Content-Type": "application/json"},+ timeout=10,)elif kind == "stripe":# Stripe Apps OAuth authenticates with the developer secret key as HTTP Basic@@ -813,6 +816,7 @@ class OauthIntegration:"code": params["code"],"grant_type": "authorization_code",},+ timeout=10,)else:redirect_uri = OauthIntegration.redirect_uri(kind)@@ -825,6 +829,7 @@ class OauthIntegration:"redirect_uri": redirect_uri,"grant_type": "authorization_code",},+ timeout=10,)try:@@ -854,6 +859,7 @@ class OauthIntegration:"redirect_uri": OauthIntegration.redirect_uri(kind),"grant_type": "authorization_code",},+ timeout=10,)try:@@ -888,11 +894,13 @@ class OauthIntegration:oauth_config.token_info_url,headers={"Authorization": f"Bearer {config['access_token']}"},json={"query": oauth_config.token_info_graphql_query},+ timeout=10,)else:token_info_res = requests.get(oauth_config.token_info_url.replace(":access_token", config["access_token"]),headers={"Authorization": f"Bearer {config['access_token']}"},+ timeout=10,)if token_info_res.status_code == 200:@@ -1111,6 +1119,7 @@ class OauthIntegration:},# If I use a standard User-Agent, it will throw a 429 too many requests errorheaders={"User-Agent": "PostHog/1.0 by PostHogTeam"},+ timeout=10,)# Pinterest uses HTTP Basic Auth for token refreshelif self.integration.kind == "pinterest-ads":@@ -1121,6 +1130,7 @@ class OauthIntegration:"refresh_token": self.integration.sensitive_config["refresh_token"],"grant_type": "refresh_token",},+ timeout=10,)elif self.integration.kind == "tiktok-ads":res = requests.post(@@ -1132,6 +1142,7 @@ class OauthIntegration:"grant_type": "refresh_token",},headers={"Content-Type": "application/x-www-form-urlencoded"},+ timeout=10,)elif self.integration.kind == "bing-ads":# Microsoft Azure AD requires scope parameter on token refresh@@ -1144,6 +1155,7 @@ class OauthIntegration:"grant_type": "refresh_token","scope": oauth_config.scope,},+ timeout=10,)elif self.integration.kind == "stripe":# Stripe Apps OAuth: secret as HTTP Basic username, no client_id/client_secret in body.@@ -1154,6 +1166,7 @@ class OauthIntegration:"refresh_token": self.integration.sensitive_config["refresh_token"],"grant_type": "refresh_token",},+ timeout=10,)else:res = requests.post(@@ -1164,6 +1177,7 @@ class OauthIntegration:"refresh_token": self.integration.sensitive_config["refresh_token"],"grant_type": "refresh_token",},+ timeout=10,)config: dict = res.json()@@ -1402,6 +1416,7 @@ class GoogleAdsIntegration:"developer-token": settings.GOOGLE_ADS_DEVELOPER_TOKEN,**({"login-customer-id": parent_id} if parent_id else {}),},+ timeout=10,)if response.status_code == 401:@@ -1442,6 +1457,7 @@ class GoogleAdsIntegration:"Authorization": f"Bearer {self.integration.sensitive_config['access_token']}","developer-token": settings.GOOGLE_ADS_DEVELOPER_TOKEN,},+ timeout=10,)if response.status_code == 401:@@ -1485,6 +1501,7 @@ class GoogleAdsIntegration:"developer-token": settings.GOOGLE_ADS_DEVELOPER_TOKEN,**({"login-customer-id": parent_id} if parent_id else {}),},+ timeout=10,)if response.status_code != 200:@@ -1941,6 +1958,7 @@ class LinkedInAdsIntegration:"Authorization": f"Bearer {self.integration.sensitive_config['access_token']}","LinkedIn-Version": "202508",},+ timeout=10,)self._check_auth_error(response, "listing conversion rules")@@ -1955,6 +1973,7 @@ class LinkedInAdsIntegration:"Authorization": f"Bearer {self.integration.sensitive_config['access_token']}","LinkedIn-Version": "202508",},+ timeout=10,)self._check_auth_error(response, "listing ad accounts")@@ -1997,6 +2016,7 @@ class ClickUpIntegration:"Content-Type": "application/json","Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",},+ timeout=10,)self._check_auth_error(response, "listing spaces")@@ -2014,6 +2034,7 @@ class ClickUpIntegration:"Content-Type": "application/json","Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",},+ timeout=10,)self._check_auth_error(response, "listing lists")@@ -2031,6 +2052,7 @@ class ClickUpIntegration:"Content-Type": "application/json","Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",},+ timeout=10,)self._check_auth_error(response, "listing folders")@@ -2045,6 +2067,7 @@ class ClickUpIntegration:"GET","https://api.clickup.com/api/v2/team",headers={"Authorization": f"Bearer {self.integration.sensitive_config['access_token']}"},+ timeout=10,)self._check_auth_error(response, "listing workspaces")@@ -2248,6 +2271,7 @@ class LinearIntegration:"https://api.linear.app/graphql",headers={"Authorization": f"Bearer {self.integration.sensitive_config['access_token']}"},json={"query": query, "variables": variables or {}},+ timeout=10,)return response.json()@@ -2317,6 +2341,7 @@ class JiraIntegration:"Authorization": f"Bearer {self.integration.sensitive_config['access_token']}","Accept": "application/json",},+ timeout=10,)body = response.json()projects = body.get("values", [])@@ -2361,6 +2386,7 @@ class JiraIntegration:"Content-Type": "application/json",},json=payload,+ timeout=10,)issue = response.json()@@ -2946,6 +2972,7 @@ class GitLabIntegration:headers={"PRIVATE-TOKEN": project_access_token},# disallow redirects to prevent SSRF on redirected hostallow_redirects=False,+ timeout=10,)return response.json()@@ -2963,6 +2990,7 @@ class GitLabIntegration:headers={"PRIVATE-TOKEN": project_access_token},# disallow redirects to prevent SSRF on redirected hostallow_redirects=False,+ timeout=10,)return response.json()@@ -3050,6 +3078,7 @@ class MetaAdsIntegration:"grant_type": "fb_exchange_token","set_token_expires_in_60_days": True,},+ timeout=10,)config: dict = res.json()diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.pyindex 045605fd424c..b669cd470659 100644--- a/posthog/models/remote_config.py+++ b/posthog/models/remote_config.py@@ -467,6 +467,7 @@ class RemoteConfig(UUIDTModel):settings.REMOTE_CONFIG_CDN_PURGE_ENDPOINT,headers={"Authorization": f"Bearer {settings.REMOTE_CONFIG_CDN_PURGE_TOKEN}"},json=data,+ timeout=10,)if res.status_code != 200:@@ -491,6 +492,7 @@ class RemoteConfig(UUIDTModel):settings.REMOTE_CONFIG_CDN_PURGE_ENDPOINT,headers={"Authorization": f"Bearer {settings.REMOTE_CONFIG_CDN_PURGE_TOKEN}"},json=data,+ timeout=10,)if res.status_code != 200:raise Exception(f"Failed to purge CDN by tag {tag}: {res.status_code} {res.text}")diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex f2472bc478bf..912132eaac69 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -470,6 +470,7 @@ class TestOauthIntegrationModel(BaseTest):"client_secret": "hubspot-client-secret","refresh_token": "REFRESH",},+ timeout=10,)assert integration.config["expires_in"] == 1000diff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.pyindex 096df3395288..e4fdc6d24b71 100644--- a/posthog/models/test/test_remote_config.py+++ b/posthog/models/test/test_remote_config.py@@ -607,6 +607,7 @@ class TestRemoteConfigCaching(_RemoteConfigBase):{"url": "https://cdn2.posthog.com/array/phc_12345/config.js"},]},+ timeout=10,)diff --git a/posthog/redis.py b/posthog/redis.pyindex 3e3ec7a6da58..38bc751a694b 100644--- a/posthog/redis.py+++ b/posthog/redis.py@@ -37,7 +37,12 @@ def get_client(redis_url: Optional[str] = None) -> redis.Redis:client: Any = fakeredis.FakeRedis(server=_get_test_fake_server(redis_url))elif redis_url:- client = redis.from_url(redis_url, db=0)+ client = redis.from_url(+ redis_url,+ db=0,+ socket_timeout=settings.REDIS_SOCKET_TIMEOUT_SECONDS,+ socket_connect_timeout=settings.REDIS_SOCKET_CONNECT_TIMEOUT_SECONDS,+ )else:client = None@@ -135,7 +140,12 @@ def get_async_client(redis_url: Optional[str] = None):# Get (or create) the Redis instance for redis_urlclient = pool_map.get(redis_url)if client is None:- client = aioredis.from_url(redis_url, db=0)+ client = aioredis.from_url(+ redis_url,+ db=0,+ socket_timeout=settings.REDIS_SOCKET_TIMEOUT_SECONDS,+ socket_connect_timeout=settings.REDIS_SOCKET_CONNECT_TIMEOUT_SECONDS,+ )pool_map[redis_url] = clientreturn clientdiff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex ffdfc284ef44..9ca7405fb765 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -501,6 +501,13 @@ if not REDIS_URL:"https://posthog.com/docs/deployment/upgrading-posthog#upgrading-from-before-1011")+# Socket timeouts for the central Redis clients (posthog/redis.py). The connect timeout is kept+# small so a dead node fails fast. The read timeout must comfortably exceed the largest server-side+# blocking window on the central client, which is a 15s XREAD BLOCK (notebooks collab_stream);+# 20s leaves margin so blocking stream reads never spuriously time out.+REDIS_SOCKET_CONNECT_TIMEOUT_SECONDS: float = get_from_env("REDIS_SOCKET_CONNECT_TIMEOUT_SECONDS", 3.0, type_cast=float)+REDIS_SOCKET_TIMEOUT_SECONDS: float = get_from_env("REDIS_SOCKET_TIMEOUT_SECONDS", 20.0, type_cast=float)+# Controls whether the ZstdCompressor is used for Redis compression when writing to Redis.# The ZstdCompressor uses zstd compression and can cope with compressed and uncompressed reading at the same timeUSE_REDIS_COMPRESSION = get_from_env("USE_REDIS_COMPRESSION", True, type_cast=str_to_bool)diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 3ae66d07122f..a271f62e2312 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -261,6 +261,9 @@ X_FRAME_OPTIONS = "SAMEORIGIN"SOCIAL_AUTH_JSONFIELD_ENABLED = TrueSOCIAL_AUTH_USER_MODEL = "posthog.User"SOCIAL_AUTH_REDIRECT_IS_HTTPS: bool = get_from_env("SOCIAL_AUTH_REDIRECT_IS_HTTPS", not DEBUG, type_cast=str_to_bool)+# social-auth-core reads REQUESTS_TIMEOUT in BaseAuth.request(); without it a hung self-hosted+# GitLab/OIDC provider can block a web worker forever.+SOCIAL_AUTH_REQUESTS_TIMEOUT: float = get_from_env("SOCIAL_AUTH_REQUESTS_TIMEOUT", 10.0, type_cast=float)SOCIAL_AUTH_PIPELINE = ("social_core.pipeline.social_auth.social_details",diff --git a/posthog/test/test_email.py b/posthog/test/test_email.pyindex b20be26e1718..8fc335268caa 100644--- a/posthog/test/test_email.py+++ b/posthog/test/test_email.py@@ -287,6 +287,7 @@ class TestEmail(BaseTest):"transactional_message_id": CUSTOMER_IO_TEMPLATE_ID_MAP["2fa_enabled"],"message_data": {"utm_tags": "utm_source=posthog&utm_medium=email&utm_campaign=2fa_enabled"},},+ timeout=30,)mock_capture.assert_called_once_with(@@ -333,6 +334,7 @@ class TestEmail(BaseTest):"utm_tags": "utm_source=posthog&utm_medium=email&utm_campaign=2fa_enabled",},},+ timeout=30,)@patch("posthog.email.requests.post")diff --git a/posthog/test/test_redis.py b/posthog/test/test_redis.pyindex 6079734dda33..3a4d24267c1f 100644--- a/posthog/test/test_redis.py+++ b/posthog/test/test_redis.py@@ -2,6 +2,7 @@ import asynciofrom unittest.mock import ANY, AsyncMock, patch+from django.conf import settingsfrom django.test.testcases import TestCaseimport fakeredis@@ -94,8 +95,27 @@ class TestRedis(TestCase):self.assertIsNot(client1, client2)# Should have been called twice (once per loop)self.assertEqual(mock_from_url.call_count, 2)- # Verify the calls were made with correct parameters- mock_from_url.assert_any_call("redis://mocked:6379", db=0)+ # Socket timeouts must be passed through so a hung Redis can't block a worker forever+ mock_from_url.assert_any_call(+ "redis://mocked:6379",+ db=0,+ socket_timeout=settings.REDIS_SOCKET_TIMEOUT_SECONDS,+ socket_connect_timeout=settings.REDIS_SOCKET_CONNECT_TIMEOUT_SECONDS,+ )++ def test_sync_redis_client_passes_socket_timeouts(self):+ # Guard that the sync production client is built with socket timeouts (regression: a hung+ # Redis node blocking a web worker indefinitely)+ with patch("redis.from_url") as mock_from_url:+ with self.settings(TEST=False, REDIS_URL="redis://mocked:6379"):+ get_client()++ mock_from_url.assert_called_once_with(+ "redis://mocked:6379",+ db=0,+ socket_timeout=settings.REDIS_SOCKET_TIMEOUT_SECONDS,+ socket_connect_timeout=settings.REDIS_SOCKET_CONNECT_TIMEOUT_SECONDS,+ )def test_same_loop_returns_cached_client_test_mode(self):"""In test mode, calling get_async_client twice returns the same cached instance."""