: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(remote-config): guard hypercache reads against bad S3 public endpoint (#64045)
posthog[bot]f14e8a54bc4c
diff --git a/posthog/apps.py b/posthog/apps.pyindex 7d5321572408..0115c5060bb6 100644--- a/posthog/apps.py+++ b/posthog/apps.py@@ -39,6 +39,7 @@ class PostHogConfig(AppConfig):# django.setup(), so a process that never builds the router (celery, temporal, migrate,# shell) would lose them. They live in dedicated import-light modules — never wire# ready() through an API module, even one that looks light today.+ import posthog.storage.checks # noqa: F401, PLC0415import posthog.caching.organization_serializer_cache # noqa: F401, PLC0415import posthog.models.activity_logging.signal_handlers # noqa: F401, PLC0415diff --git a/posthog/storage/checks.py b/posthog/storage/checks.pynew file mode 100644index 000000000000..e59056e93ba1--- /dev/null+++ b/posthog/storage/checks.py@@ -0,0 +1,27 @@+from django.conf import settings+from django.core.checks import Error, register++from posthog.storage.object_storage import is_usable_endpoint+++@register()+def check_object_storage_public_endpoint(app_configs, **kwargs):+ """Catch a misconfigured OBJECT_STORAGE_PUBLIC_ENDPOINT at startup rather than in user traffic.++ An unsubstituted deployment template literal (e.g. `https://${POSTHOG_DOMAIN}`) makes boto3+ raise `ValueError` on client construction, which previously surfaced as 500s on every+ hypercache-backed read. Failing the system check makes the bad rollout obvious immediately.+ """+ errors: list[Error] = []++ endpoint = settings.OBJECT_STORAGE_PUBLIC_ENDPOINT+ if settings.OBJECT_STORAGE_ENABLED and endpoint and not is_usable_endpoint(endpoint):+ errors.append(+ Error(+ f"OBJECT_STORAGE_PUBLIC_ENDPOINT is not a usable URL: {endpoint!r}",+ hint="Check the deployment env — it likely contains an unsubstituted ${...} template placeholder.",+ id="posthog.E004",+ )+ )++ return errorsdiff --git a/posthog/storage/hypercache.py b/posthog/storage/hypercache.pyindex 90f3b9870066..c564836a6abd 100644--- a/posthog/storage/hypercache.py+++ b/posthog/storage/hypercache.py@@ -8,6 +8,7 @@ from django.conf import settingsfrom django.core.cache import cache, cachesimport structlog+from botocore.exceptions import BotoCoreError, ClientErrorfrom posthoganalytics import capture_exceptionfrom prometheus_client import Counter, Histogram@@ -252,8 +253,13 @@ class HyperCache:HYPERCACHE_CACHE_COUNTER.labels(result="hit_s3", namespace=self.namespace, value=self.value).inc()self._set_cache_value_redis(key, response)return response, "s3"- except ObjectStorageError:- pass+ except (ObjectStorageError, BotoCoreError, ClientError, ValueError) as e:+ # Any storage-layer failure here (including a misconfigured S3 endpoint that+ # makes boto3 raise on client construction) must degrade to a cache miss and+ # fall through to load_fn, never bubble a 500 up to the request handler.+ # ValueError also catches json.JSONDecodeError from a corrupt blob, so capture+ # it — otherwise persistent corruption keeps missing silently as a plain hit_db.+ capture_exception(e)# NOTE: This only applies to the django version - the dedicated service will rely entirely on the cachetry:diff --git a/posthog/storage/object_storage.py b/posthog/storage/object_storage.pyindex a0fdda097004..4021b877a931 100644--- a/posthog/storage/object_storage.py+++ b/posthog/storage/object_storage.py@@ -1,6 +1,7 @@import abcimport threadingfrom typing import IO, Any, Optional, Union+from urllib.parse import urlparsefrom django.conf import settings@@ -405,6 +406,14 @@ class ObjectStorage(ObjectStorageClient):_client: ObjectStorageClient = UnavailableStorage()+def is_usable_endpoint(endpoint: str | None) -> bool:+ """A usable endpoint is a syntactically valid URL with no unsubstituted ${...} deployment placeholders."""+ if not endpoint or "${" in endpoint:+ return False+ parsed = urlparse(endpoint)+ return bool(parsed.scheme and parsed.netloc)++def object_storage_client() -> ObjectStorageClient:global _client@@ -425,15 +434,32 @@ def object_storage_client() -> ObjectStorageClient:region_name=settings.OBJECT_STORAGE_REGION,)presigned_client = None- if settings.OBJECT_STORAGE_PUBLIC_ENDPOINT != settings.OBJECT_STORAGE_ENDPOINT:- presigned_client = client(- "s3",- endpoint_url=settings.OBJECT_STORAGE_PUBLIC_ENDPOINT,- aws_access_key_id=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- aws_secret_access_key=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- config=s3_config,- region_name=settings.OBJECT_STORAGE_REGION,- )+ public_endpoint = settings.OBJECT_STORAGE_PUBLIC_ENDPOINT+ if public_endpoint != settings.OBJECT_STORAGE_ENDPOINT:+ # A misconfigured public endpoint (e.g. an unsubstituted `${POSTHOG_DOMAIN}`+ # deployment template literal) must never take down the read path: every reader+ # routes through this factory, and boto3 raises `ValueError` when handed an+ # invalid endpoint. Validate up front and degrade to the internal client so+ # presigned URLs lose their public host but reads keep working.+ if is_usable_endpoint(public_endpoint):+ try:+ presigned_client = client(+ "s3",+ endpoint_url=public_endpoint,+ aws_access_key_id=settings.OBJECT_STORAGE_ACCESS_KEY_ID,+ aws_secret_access_key=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,+ config=s3_config,+ region_name=settings.OBJECT_STORAGE_REGION,+ )+ except Exception as e:+ logger.exception("object_storage.invalid_public_endpoint", endpoint=public_endpoint, error=e)+ capture_exception(e)+ else:+ # The Django system check only fails `manage.py`-style startup; gunicorn/ASGI+ # workers skip it, so capture here too to surface the bad config in Sentry.+ error = ValueError(f"Invalid OBJECT_STORAGE_PUBLIC_ENDPOINT: {public_endpoint!r}")+ logger.error("object_storage.invalid_public_endpoint", endpoint=public_endpoint, error=error)+ capture_exception(error)_client = ObjectStorage(aws_client, presigned_client)return _clientdiff --git a/posthog/storage/test/test_checks.py b/posthog/storage/test/test_checks.pynew file mode 100644index 000000000000..2d8f5b654381--- /dev/null+++ b/posthog/storage/test/test_checks.py@@ -0,0 +1,29 @@+from django.test import SimpleTestCase++from posthog.storage.checks import check_object_storage_public_endpoint+++class TestObjectStoragePublicEndpointCheck(SimpleTestCase):+ def test_no_error_for_valid_endpoint(self) -> None:+ with self.settings(+ OBJECT_STORAGE_ENABLED=True,+ OBJECT_STORAGE_PUBLIC_ENDPOINT="https://public.example.com",+ ):+ assert check_object_storage_public_endpoint(None) == []++ def test_error_for_unsubstituted_placeholder(self) -> None:+ with self.settings(+ OBJECT_STORAGE_ENABLED=True,+ OBJECT_STORAGE_PUBLIC_ENDPOINT="https://${POSTHOG_DOMAIN}",+ ):+ errors = check_object_storage_public_endpoint(None)++ assert len(errors) == 1+ assert errors[0].id == "posthog.E004"++ def test_no_error_when_storage_disabled(self) -> None:+ with self.settings(+ OBJECT_STORAGE_ENABLED=False,+ OBJECT_STORAGE_PUBLIC_ENDPOINT="https://${POSTHOG_DOMAIN}",+ ):+ assert check_object_storage_public_endpoint(None) == []diff --git a/posthog/storage/test/test_hypercache.py b/posthog/storage/test/test_hypercache.pyindex 710c541982ad..0d3cae220051 100644--- a/posthog/storage/test/test_hypercache.py+++ b/posthog/storage/test/test_hypercache.py@@ -7,6 +7,7 @@ from unittest.mock import Mock, patchfrom django.core.cache import cachefrom django.test import override_settings+from botocore.exceptions import BotoCoreError, ClientErrorfrom parameterized import parameterizedfrom posthog.storage import object_storage@@ -106,6 +107,34 @@ class TestHyperCacheGetFromCache(HyperCacheTestBase):assert result == {"default": "data"}assert source == "db"+ @parameterized.expand(+ [+ ("value_error", ValueError("Invalid endpoint: https://${POSTHOG_DOMAIN}")),+ ("object_storage_error", object_storage.ObjectStorageError("read failed")),+ ("boto_core_error", BotoCoreError()),+ ("client_error", ClientError({"Error": {"Code": "AccessDenied"}}, "GetObject")),+ ]+ )+ def test_get_from_cache_s3_exception_falls_back_to_db(self, _name, exception):+ """A storage-layer failure on the S3 read must degrade to a cache miss, not a 500."""+ self.hypercache.clear_cache(self.team_id, kinds=["redis"])++ with patch.object(object_storage, "read", side_effect=exception):+ result, source = self.hypercache.get_from_cache_with_source(self.team_id)++ assert result == {"default": "data"}+ assert source == "db"++ def test_get_from_cache_corrupt_s3_payload_falls_back_to_db(self):+ """A malformed S3 blob (json.JSONDecodeError, a ValueError subclass) must degrade to a cache miss."""+ self.hypercache.clear_cache(self.team_id, kinds=["redis"])++ with patch.object(object_storage, "read", return_value="{not valid json"):+ result, source = self.hypercache.get_from_cache_with_source(self.team_id)++ assert result == {"default": "data"}+ assert source == "db"+def test_get_from_cache_with_source_empty(self):"""Test getting data with source information - Empty result"""diff --git a/posthog/storage/test/test_object_storage.py b/posthog/storage/test/test_object_storage.pyindex f5978fd141ed..acb9451410bd 100644--- a/posthog/storage/test/test_object_storage.py+++ b/posthog/storage/test/test_object_storage.py@@ -4,10 +4,14 @@ import uuidfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from django.test import SimpleTestCase+from boto3 import resourcefrom botocore.client import Configfrom botocore.exceptions import ClientError+from parameterized import parameterized+import posthog.storage.object_storage as object_storage_modulefrom posthog.settings import (OBJECT_STORAGE_ACCESS_KEY_ID,OBJECT_STORAGE_BUCKET,@@ -17,11 +21,14 @@ from posthog.settings import (from posthog.storage.object_storage import (ObjectStorage,ObjectStorageError,+ UnavailableStorage,copy_objects,get_presigned_post,get_presigned_url,health_check,+ is_usable_endpoint,list_objects,+ object_storage_client,read,write,)@@ -228,3 +235,76 @@ class TestStorage(APIBaseTest):assert mock_client.delete_objects.call_count == 2assert len(mock_client.delete_objects.call_args_list[0].kwargs["Delete"]["Objects"]) == 1000assert len(mock_client.delete_objects.call_args_list[1].kwargs["Delete"]["Objects"]) == 1+++class TestObjectStorageClientFactory(SimpleTestCase):+ def setUp(self) -> None:+ object_storage_module._client = UnavailableStorage()+ self.addCleanup(setattr, object_storage_module, "_client", UnavailableStorage())++ @parameterized.expand(+ [+ ("valid_http", "http://objectstorage:19000", True),+ ("valid_https", "https://s3.amazonaws.com", True),+ ("unsubstituted_placeholder", "https://${POSTHOG_DOMAIN}", False),+ ("placeholder_in_path", "https://example.com/${BUCKET}", False),+ ("missing_scheme", "objectstorage:19000", False),+ ("empty", "", False),+ ("none", None, False),+ ]+ )+ def test_is_usable_endpoint(self, _name: str, endpoint: str | None, expected: bool) -> None:+ assert is_usable_endpoint(endpoint) is expected++ @patch("posthog.storage.object_storage.capture_exception")+ @patch("posthog.storage.object_storage.client")+ def test_bad_public_endpoint_does_not_crash_read_path(self, patched_client, patched_capture) -> None:+ # A bad public endpoint must never raise out of the factory — readers route through it.+ with self.settings(+ OBJECT_STORAGE_ENABLED=True,+ OBJECT_STORAGE_ENDPOINT="http://objectstorage:19000",+ OBJECT_STORAGE_PUBLIC_ENDPOINT="https://${POSTHOG_DOMAIN}",+ ):+ storage = object_storage_client()++ assert isinstance(storage, ObjectStorage)+ # Only the internal client is built; presigned degrades to the internal client.+ patched_client.assert_called_once()+ assert storage.presigned_client is storage.aws_client+ # The bad config is surfaced to Sentry even though the read path stays up.+ patched_capture.assert_called_once()++ @patch("posthog.storage.object_storage.capture_exception")+ @patch("posthog.storage.object_storage.client")+ def test_boto_failure_building_presigned_client_degrades(self, patched_client, patched_capture) -> None:+ internal_client = MagicMock()+ patched_client.side_effect = [internal_client, ValueError("Invalid endpoint")]++ with self.settings(+ OBJECT_STORAGE_ENABLED=True,+ OBJECT_STORAGE_ENDPOINT="http://objectstorage:19000",+ OBJECT_STORAGE_PUBLIC_ENDPOINT="https://public.example.com",+ ):+ storage = object_storage_client()++ assert isinstance(storage, ObjectStorage)+ assert storage.aws_client is internal_client+ assert storage.presigned_client is internal_client+ patched_capture.assert_called_once()++ @patch("posthog.storage.object_storage.client")+ def test_valid_public_endpoint_builds_separate_presigned_client(self, patched_client) -> None:+ internal_client = MagicMock()+ presigned_client = MagicMock()+ patched_client.side_effect = [internal_client, presigned_client]++ with self.settings(+ OBJECT_STORAGE_ENABLED=True,+ OBJECT_STORAGE_ENDPOINT="http://objectstorage:19000",+ OBJECT_STORAGE_PUBLIC_ENDPOINT="https://public.example.com",+ ):+ storage = object_storage_client()++ assert isinstance(storage, ObjectStorage)+ assert storage.aws_client is internal_client+ assert storage.presigned_client is presigned_client