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.

feat(data-warehouse): always keep warehouse bucket S3 traffic off the egress proxy (#109056)

Tom Owersb7c47b7de8ca
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index 1a622ef3f601..7c1d5342f2da 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -68,7 +68,7 @@ from products.data_modeling.backend.facade.models import DataModelingJob, DataWa
from products.data_modeling.backend.facade.system_tables import DATA_MODELING_ALLOWED_SYSTEM_TABLES
from products.data_quality.backend.facade import api as data_quality_facade
from products.data_quality.backend.facade.contracts import QUALITY_AUDIT_SKIP, QualityAuditMode
-from products.data_warehouse.backend.facade.api import ensure_bucket_exists, get_s3_client
+from products.data_warehouse.backend.facade.api import delta_proxy_storage_options, ensure_bucket_exists, get_s3_client
from products.endpoints.backend.facade.temporal import prepare_executable_query
from products.warehouse_sources.backend.facade.hooks import saved_query_binding
from products.warehouse_sources.backend.facade.pipelines import CDPProducer
@@ -417,6 +417,7 @@ def get_aws_storage_options() -> dict[str, str]:
}
return {
+ **delta_proxy_storage_options(),
"AWS_S3_ALLOW_UNSAFE_RENAME": "true",
}
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index ef48aaa1f854..2f5a2359be7a 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -2139,3 +2139,23 @@ class TestMaterializeViewStagesAccountPropertyRows:
staged_object = await minio_client.get_object(Bucket=bucket_name, Key=keys[0])
table = pq.read_table(BytesIO(await staged_object["Body"].read()))
assert table.column_names == ["mrr", "organization_id"]
+
+
+class TestAwsStorageOptions:
+ @override_settings(
+ USE_LOCAL_SETUP=False,
+ BUCKET_URL="s3://posthog-s3-datawarehouse-us-east-1/dlt",
+ DATA_WAREHOUSE_S3_REGION="us-east-1",
+ )
+ def test_deployed_options_keep_warehouse_bucket_traffic_off_the_egress_proxy(self) -> None:
+ with (
+ unittest.mock.patch("posthog.temporal.data_modeling.activities.materialize_view.TEST", False),
+ unittest.mock.patch.dict(
+ "os.environ", {"HTTPS_PROXY": "http://egress-proxy.svc.cluster.local:4750/", "NO_PROXY": ""}
+ ),
+ ):
+ options = get_aws_storage_options()
+
+ assert options["proxy_excludes"] == "posthog-s3-datawarehouse-us-east-1.s3.us-east-1.amazonaws.com"
+ assert options["AWS_S3_ADDRESSING_STYLE"] == "virtual"
+ assert options["AWS_S3_ALLOW_UNSAFE_RENAME"] == "true"
diff --git a/products/data_warehouse/backend/s3_proxy.py b/products/data_warehouse/backend/s3_proxy.py
index e1100d1d69cb..dd372891c200 100644
--- a/products/data_warehouse/backend/s3_proxy.py
+++ b/products/data_warehouse/backend/s3_proxy.py
@@ -34,31 +34,15 @@ exactly as it is today.
"""
import os
-import time
-from functools import lru_cache
from urllib.parse import urlparse
from django.conf import settings
-import posthoganalytics
-
-from posthog.utils import get_instance_region, get_machine_id
-
# Read at call time rather than reconstructed: the URL can carry per-process auth that whatever
# injected it has already expanded.
_PROXY_ENV_VARS = ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy")
_NO_PROXY_ENV_VARS = ("NO_PROXY", "no_proxy")
-WAREHOUSE_S3_PROXY_BYPASS_FLAG = "data-warehouse-s3-proxy-bypass"
-
-# Evaluated per process, not per team: which route a pod's S3 packets take is a property of where the
-# pod runs. The flag is keyed on the machine id so a percentage rollout ramps whole pods at a time,
-# which is also what makes a canary meaningful, because half a pod's requests taking each route would
-# tell us nothing. Re-read on this interval so the flag stays a live kill switch: storage options are
-# rebuilt constantly, but warehouse activities can run for hours, so caching for the process lifetime
-# would mean a flip only lands on the next restart.
-_FLAG_CACHE_SECONDS = 60
-
def _proxy_url() -> str | None:
for var in _PROXY_ENV_VARS:
@@ -89,39 +73,9 @@ def warehouse_bucket_host() -> str | None:
return f"{bucket}.s3.{region}.amazonaws.com"
-@lru_cache(maxsize=4)
-def _flag_enabled(_interval: int) -> bool:
- """Evaluate the rollout flag, keyed on a time bucket so the cache expires on its own.
-
- Any evaluation failure returns False (fail closed): a flags
- -service blip leaves traffic on the proxy rather than silently rerouting it.
- """
- try:
- return bool(
- posthoganalytics.feature_enabled(
- WAREHOUSE_S3_PROXY_BYPASS_FLAG,
- get_machine_id(),
- # Surfaced so release conditions can scope the flag to the warehouse workers in a
- # given cloud region, rather than every pod that shares this project token (web,
- # celery, and self-hosted installs all evaluate the same flag). Both values are the
- # ones posthog/apps.py already stamps onto super_properties.
- person_properties={
- "region": get_instance_region() or "",
- "service": settings.OTEL_SERVICE_NAME or "",
- },
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
- )
- except Exception:
- return False
-
-
def _bypass_enabled() -> bool:
# Local dev and tests talk to MinIO/SeaweedFS over an explicit endpoint with no proxy in front.
- if settings.USE_LOCAL_SETUP:
- return False
- return _flag_enabled(int(time.monotonic() // _FLAG_CACHE_SECONDS))
+ return not settings.USE_LOCAL_SETUP
def delta_proxy_storage_options() -> dict[str, str]:
diff --git a/products/data_warehouse/backend/tests/test_s3_proxy.py b/products/data_warehouse/backend/tests/test_s3_proxy.py
index f8ea024cdd13..141fbaad86c0 100644
--- a/products/data_warehouse/backend/tests/test_s3_proxy.py
+++ b/products/data_warehouse/backend/tests/test_s3_proxy.py
@@ -6,7 +6,6 @@ from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
-from products.data_warehouse.backend import s3_proxy
from products.data_warehouse.backend.s3_proxy import (
boto_proxy_config_kwargs,
delta_proxy_storage_options,
@@ -34,18 +33,10 @@ def proxy_env(url: str | None, no_proxy: str | None = None) -> dict[str, str]:
return env
-def flag(enabled: bool):
- return patch.object(s3_proxy.posthoganalytics, "feature_enabled", return_value=enabled)
-
-
class TestWarehouseS3ProxyBypass(SimpleTestCase):
- def setUp(self) -> None:
- # The flag result is cached per time bucket, so it has to be dropped between cases.
- s3_proxy._flag_enabled.cache_clear()
-
@override_settings(**BYPASS_ON)
def test_scopes_the_bypass_to_the_warehouse_bucket_host(self) -> None:
- with flag(True), patch.dict(os.environ, proxy_env(PROXY)):
+ with patch.dict(os.environ, proxy_env(PROXY)):
options = delta_proxy_storage_options()
assert options["proxy_excludes"] == "posthog-s3-datawarehouse-us-east-1.s3.us-east-1.amazonaws.com"
@@ -61,7 +52,7 @@ class TestWarehouseS3ProxyBypass(SimpleTestCase):
# Setting proxy_url stops reqwest reading the env, dropping its NO_PROXY with it, so the
# cluster's existing exemptions (here IMDS and in-cluster services) have to be carried over
# or they would start transiting the proxy the moment the bypass turns on.
- with flag(True), patch.dict(os.environ, proxy_env(PROXY, no_proxy="169.254.169.254,.svc.cluster.local")):
+ with patch.dict(os.environ, proxy_env(PROXY, no_proxy="169.254.169.254,.svc.cluster.local")):
options = delta_proxy_storage_options()
assert (
@@ -76,34 +67,28 @@ class TestWarehouseS3ProxyBypass(SimpleTestCase):
@parameterized.expand(
[
- ("local_setup", {"USE_LOCAL_SETUP": True}, True, PROXY),
- ("flag_off", {}, False, PROXY),
- ("region_unknown", {"DATA_WAREHOUSE_S3_REGION": ""}, True, PROXY),
- ("bucket_unknown", {"BUCKET_URL": ""}, True, PROXY),
- ("no_proxy_in_environment", {}, True, None),
+ ("local_setup", {"USE_LOCAL_SETUP": True}, PROXY),
+ ("region_unknown", {"DATA_WAREHOUSE_S3_REGION": ""}, PROXY),
+ ("bucket_unknown", {"BUCKET_URL": ""}, PROXY),
+ ("no_proxy_in_environment", {}, None),
]
)
def test_delta_options_are_empty_unless_everything_is_known(
- self, _name: str, settings_override: dict[str, object], flag_enabled: bool, proxy_url: str | None
+ self, _name: str, settings_override: dict[str, object], proxy_url: str | None
) -> None:
- with (
- override_settings(**{**BYPASS_ON, **settings_override}),
- flag(flag_enabled),
- patch.dict(os.environ, proxy_env(proxy_url)),
- ):
+ with override_settings(**{**BYPASS_ON, **settings_override}), patch.dict(os.environ, proxy_env(proxy_url)):
assert delta_proxy_storage_options() == {}
@parameterized.expand(
[
- ("enabled", {}, True, {"proxies": {}}),
- ("flag_off", {}, False, {}),
- ("local_setup", {"USE_LOCAL_SETUP": True}, True, {}),
+ ("deployed", {}, {"proxies": {}}),
+ ("local_setup", {"USE_LOCAL_SETUP": True}, {}),
]
)
- def test_boto_clients_drop_the_proxy_only_when_the_bypass_is_on(
- self, _name: str, settings_override: dict[str, object], flag_enabled: bool, expected: dict[str, object]
+ def test_boto_clients_drop_the_proxy_outside_local_setup(
+ self, _name: str, settings_override: dict[str, object], expected: dict[str, object]
) -> None:
- with override_settings(**{**BYPASS_ON, **settings_override}), flag(flag_enabled):
+ with override_settings(**{**BYPASS_ON, **settings_override}):
assert boto_proxy_config_kwargs() == expected
@override_settings(**BYPASS_ON)
@@ -111,25 +96,5 @@ class TestWarehouseS3ProxyBypass(SimpleTestCase):
# A caller-supplied endpoint puts the host under the caller's control, so the proxy must stay
# in front of it even with the bypass on, or a private-address S3-compatible source would be
# dialed direct.
- with flag(True):
- assert boto_proxy_config_kwargs() == {"proxies": {}}
- assert boto_proxy_config_kwargs(endpoint_url="http://10.0.0.5/") == {}
-
- # A flags-service outage must not reroute production traffic on its own.
- @override_settings(**BYPASS_ON)
- def test_flag_evaluation_failure_leaves_traffic_on_the_proxy(self) -> None:
- with (
- patch.object(s3_proxy.posthoganalytics, "feature_enabled", side_effect=Exception("flags down")),
- patch.dict(os.environ, proxy_env(PROXY)),
- ):
- assert delta_proxy_storage_options() == {}
-
- # The options are rebuilt on every table open; evaluating the flag each time would put a network
- # call on that path.
- @override_settings(**BYPASS_ON)
- def test_flag_is_evaluated_once_per_interval_not_per_call(self) -> None:
- with flag(True) as evaluate, patch.dict(os.environ, proxy_env(PROXY)):
- for _ in range(5):
- delta_proxy_storage_options()
-
- assert evaluate.call_count == 1
+ assert boto_proxy_config_kwargs() == {"proxies": {}}
+ assert boto_proxy_config_kwargs(endpoint_url="http://10.0.0.5/") == {}