: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(data-imports): force virtual-hosted s3 addressing without a proxy (#114849)
Tom Owersae0e220d3439
diff --git a/products/data_warehouse/backend/s3_proxy.py b/products/data_warehouse/backend/s3_proxy.pyindex dd372891c200..92531f383229 100644--- a/products/data_warehouse/backend/s3_proxy.py+++ b/products/data_warehouse/backend/s3_proxy.py@@ -1,4 +1,18 @@-"""Scoped egress-proxy bypass for the warehouse's own S3 traffic.+"""Virtual-hosted S3 addressing, and a scoped egress-proxy bypass, for the warehouse's own S3 traffic.++delta-rs/object_store address S3 path-style by default (``<endpoint>/<bucket>``). AWS still accepts+that for buckets created before it deprecated the style in 2020, but plenty of real S3-compatible+stores refuse it outright (Alibaba OSS returns "please use virtual hosted style to access" on it).+Virtual-hosted addressing (``<bucket>.<endpoint>``) works everywhere a bucket is reachable by a real,+DNS-resolvable hostname, which is every non-local deployment: the in-stack MinIO/SeaweedFS of+USE_LOCAL_SETUP is the only backend here addressed by raw host:port instead, and it takes a separate,+explicit-endpoint code path that never reaches this module. So addressing style is forced below+independent of anything else in this file, not only as a side effect of the proxy bypass that follows.++One exception: a bucket name containing a dot stays on path-style (see+_bucket_supports_virtual_hosted_style) - AWS's wildcard TLS cert for its own S3 endpoints doesn't+cover the extra hostname label a dot introduces, so forcing virtual-hosted addressing there breaks+certificate validation instead of fixing anything.Where HTTP_PROXY/HTTPS_PROXY point at an egress proxy, every S3 request becomes a CONNECT tunnel:two tracked connections on the proxy host (client side and server side) instead of one, each held in@@ -9,12 +23,9 @@ network can already reach S3 directly, that hop buys nothing.The bypass is deliberately scoped to *this bucket's hostname*, not carved out of the process-wideNO_PROXY. Egress to customer-controlled destinations (source APIs, customer databases, and a-customer-configured source that happens to point at S3) has to keep going through the proxy.--That scoping is why virtual-hosted addressing is forced: delta-rs addresses S3 path-style by default-(``s3.<region>.amazonaws.com/<bucket>``), which leaves the bucket out of the hostname, so no-host-based rule can distinguish our traffic from anyone else's. Virtual-hosted addressing-(``<bucket>.s3.<region>.amazonaws.com``) puts it back in.+customer-configured source that happens to point at S3) has to keep going through the proxy. That+scoping relies on virtual-hosted addressing too: path-style leaves the bucket out of the hostname, so+no host-based rule could distinguish our traffic from anyone else's.These options reach deltalite too, without it needing to know about any of this: the write path handsit the same dict, and ``DeltaLiteTable.open`` passes it to ``DeltaTableBuilder::with_storage_options``.@@ -28,9 +39,10 @@ The two clients need different mechanisms:- botocore takes ``proxies={}`` per client, which overrides the environment directly. Those clientsonly ever address this bucket, so no host-level exclusion is needed.-Every failure mode here is fail-safe: unknown region, missing bucket, absent proxy env or a+Every proxy-bypass failure mode is fail-safe: unknown region, missing bucket, absent proxy env or ahostname that doesn't match what the client actually dials all leave the traffic on the proxy,-exactly as it is today.+exactly as it is today. Addressing style carries no such fallback - it does not depend on any of+those - because leaving it unset is exactly the bug this module now avoids."""import os@@ -73,24 +85,59 @@ def warehouse_bucket_host() -> str | None:return f"{bucket}.s3.{region}.amazonaws.com"-def _bypass_enabled() -> bool:- # Local dev and tests talk to MinIO/SeaweedFS over an explicit endpoint with no proxy in front.+def _using_real_bucket() -> bool:+ # Local dev and tests talk to MinIO/SeaweedFS over an explicit endpoint with no proxy in front,+ # and addressed by raw host:port rather than a DNS name a virtual-hosted request could use.return not settings.USE_LOCAL_SETUP-def delta_proxy_storage_options() -> dict[str, str]:- """delta-rs storage options that keep this bucket's traffic off the egress proxy.+def _bucket_supports_virtual_hosted_style() -> bool:+ """False for a bucket name that itself contains a dot.- Empty when the bypass is off or anything it depends on is missing, so callers can merge it- unconditionally.+ AWS's wildcard TLS cert for ``*.s3.<region>.amazonaws.com`` covers exactly one subdomain+ label. A bucket name with a dot in it (a legal, if discouraged, S3 bucket name) produces a+ virtual-hosted hostname with an extra label the cert doesn't cover, so the request fails+ certificate validation - see+ https://docs.aws.amazon.com/AmazonS3/latest/userguide/VirtualHosting.html. Path-style still+ works for those buckets, so they stay on it."""- if not _bypass_enabled():+ bucket = urlparse(settings.BUCKET_URL).netloc+ return bool(bucket) and "." not in bucket+++def _addressing_style_options() -> dict[str, str]:+ if not _using_real_bucket() or not _bucket_supports_virtual_hosted_style():return {}+ return {+ # Two spellings of the same thing, because two libraries read these options. deltalake-aws+ # parses AWS_S3_ADDRESSING_STYLE; object_store's own S3 builder only knows+ # virtual_hosted_style_request. Which one applies depends on whether the AWS storage handler+ # is registered, and deltalite (rust/deltalite, which passes this dict straight to+ # DeltaTableBuilder) links its own delta-rs build. Setting both means the bucket ends up in+ # the hostname either way; they agree, so neither can contradict the other.+ "AWS_S3_ADDRESSING_STYLE": "virtual",+ "virtual_hosted_style_request": "true",+ }+++def delta_proxy_storage_options() -> dict[str, str]:+ """delta-rs storage options for the warehouse bucket: forced virtual-hosted addressing (see+ module docstring), plus keeping this bucket's traffic off the egress proxy where one is+ configured.++ Empty when not using a real bucket, so callers can merge it unconditionally.+ """+ options = _addressing_style_options()+ if not _using_real_bucket() or not _bucket_supports_virtual_hosted_style():+ # A dotted bucket name never gets addressed virtual-hosted (see+ # _bucket_supports_virtual_hosted_style), so a host-based proxy exclusion below would name+ # a hostname delta-rs never actually dials and never bypass anything. Stop here instead.+ return optionsproxy_url = _proxy_url()host = warehouse_bucket_host()if not proxy_url or not host:- return {}+ return options# Setting proxy_url explicitly stops reqwest consulting the environment, which drops the# environment's own NO_PROXY along with its proxy. Fold that list back in so hosts the cluster@@ -100,16 +147,9 @@ def delta_proxy_storage_options() -> dict[str, str]:excludes = ",".join(filter(None, [host, _no_proxy()]))return {+ **options,"proxy_url": proxy_url,"proxy_excludes": excludes,- # Two spellings of the same thing, because two libraries read these options. deltalake-aws- # parses AWS_S3_ADDRESSING_STYLE; object_store's own S3 builder only knows- # virtual_hosted_style_request. Which one applies depends on whether the AWS storage handler- # is registered, and deltalite (rust/deltalite, which passes this dict straight to- # DeltaTableBuilder) links its own delta-rs build. Setting both means the bucket ends up in- # the hostname either way; they agree, so neither can contradict the other.- "AWS_S3_ADDRESSING_STYLE": "virtual",- "virtual_hosted_style_request": "true",}@@ -124,6 +164,6 @@ def boto_proxy_config_kwargs(*, endpoint_url: str | None = None) -> dict[str, obunder the caller's control (a customer S3-compatible source could point at a private address), sothe bypass is withheld and that traffic keeps going through the proxy."""- if not _bypass_enabled() or endpoint_url:+ if not _using_real_bucket() or endpoint_url:return {}return {"proxies": {}}diff --git a/products/data_warehouse/backend/tests/test_s3_proxy.py b/products/data_warehouse/backend/tests/test_s3_proxy.pyindex 141fbaad86c0..f97c41e3c223 100644--- a/products/data_warehouse/backend/tests/test_s3_proxy.py+++ b/products/data_warehouse/backend/tests/test_s3_proxy.py@@ -65,18 +65,59 @@ class TestWarehouseS3ProxyBypass(SimpleTestCase):with override_settings(BUCKET_URL="s3://some-other-bucket/dlt", DATA_WAREHOUSE_S3_REGION="eu-central-1"):assert warehouse_bucket_host() == "some-other-bucket.s3.eu-central-1.amazonaws.com"+ @override_settings(**{**BYPASS_ON, "USE_LOCAL_SETUP": True})+ def test_delta_options_are_empty_for_a_local_setup(self) -> None:+ # The in-stack MinIO/SeaweedFS of USE_LOCAL_SETUP is addressed by raw host:port, not a real+ # DNS name, so neither addressing style nor the proxy bypass apply to it.+ with patch.dict(os.environ, proxy_env(PROXY)):+ assert delta_proxy_storage_options() == {}+@parameterized.expand([- ("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(+ def test_proxy_options_are_absent_unless_the_bucket_host_and_proxy_are_both_known(self, _name: str, settings_override: dict[str, object], proxy_url: str | None) -> None:with override_settings(**{**BYPASS_ON, **settings_override}), patch.dict(os.environ, proxy_env(proxy_url)):+ options = delta_proxy_storage_options()+ assert "proxy_url" not in options+ assert "proxy_excludes" not in options++ @override_settings(**BYPASS_ON)+ def test_addressing_style_is_forced_even_without_a_proxy(self) -> None:+ # Regression: addressing style used to be set only as a side effect of the proxy bypass+ # below, so a deployment with no egress proxy configured (e.g. a dedicated or self-hosted+ # install) fell back to delta-rs's path-style default and 403'd against a store that+ # requires virtual-hosted addressing (e.g. Alibaba OSS's "please use virtual hosted style to+ # access").+ with patch.dict(os.environ, proxy_env(None)):+ options = delta_proxy_storage_options()+ assert options["AWS_S3_ADDRESSING_STYLE"] == "virtual"+ assert options["virtual_hosted_style_request"] == "true"+ assert "proxy_url" not in options++ @parameterized.expand(+ [+ ("no_proxy", None),+ ("with_proxy", PROXY),+ ]+ )+ def test_addressing_style_stays_path_style_for_a_dotted_bucket_name(+ self, _name: str, proxy_url: str | None+ ) -> None:+ # Regression: AWS's wildcard TLS cert for its own S3 endpoints covers exactly one hostname+ # label, so a bucket name with a dot in it (e.g. "warehouse.example") produces a+ # virtual-hosted hostname with an extra label the cert doesn't cover, and forcing virtual+ # addressing there breaks certificate validation instead of fixing anything. Path-style+ # still works for it, so it must stay off the override - with or without a proxy configured.+ with (+ override_settings(**{**BYPASS_ON, "BUCKET_URL": "s3://warehouse.example/dlt"}),+ patch.dict(os.environ, proxy_env(proxy_url)),+ ):assert delta_proxy_storage_options() == {}@parameterized.expand(