: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-warehouse): lock read location of node-role warehouse tables (#81559)
Tom Owers4232e910db01
diff --git a/products/data_warehouse/backend/presentation/views/table.py b/products/data_warehouse/backend/presentation/views/table.pyindex a493e1f6954b..8f7df4cabb08 100644--- a/products/data_warehouse/backend/presentation/views/table.py+++ b/products/data_warehouse/backend/presentation/views/table.py@@ -237,17 +237,23 @@ class TableSerializer(UserAccessControlSerializerMixin, serializers.ModelSerialireturn tabledef validate_url_pattern(self, url_pattern):- s3_domain = settings.DATAWAREHOUSE_BUCKET_DOMAIN- if s3_domain in url_pattern:- raise serializers.ValidationError(- "This URL points to PostHog's internal storage and can't be used as a source. "- "Enter the location of your own bucket instead."- )-is_valid, error_message = validate_warehouse_table_url_pattern(url_pattern)if not is_valid:raise serializers.ValidationError(error_message)+ # A table with no credential is read with the ClickHouse node's own role rather than a key+ # the team supplied, so the URL is only trustworthy because PostHog built it. `create`+ # refuses that combination outright, and an update has to hold the same line.+ if (+ self.instance is not None+ and self.instance.credential_id is None+ and url_pattern != self.instance.url_pattern+ ):+ raise serializers.ValidationError(+ "PostHog manages where this table reads from, so its URL can't be changed. "+ "To read from your own bucket, add it as a self-managed source with an access key and secret."+ )+return url_patterndef validate_options(self, options):diff --git a/products/data_warehouse/backend/tests/api/test_table.py b/products/data_warehouse/backend/tests/api/test_table.pyindex 6ae130b8990a..0c08af32394f 100644--- a/products/data_warehouse/backend/tests/api/test_table.py+++ b/products/data_warehouse/backend/tests/api/test_table.py@@ -15,6 +15,8 @@ from products.data_warehouse.backend.direct_postgres import DIRECT_POSTGRES_URL_from products.data_warehouse.backend.presentation.views.table import SimpleTableSerializerfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource+PUBLIC_ADDRINFO = [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("93.184.216.34", 0))]+class TestTable(APIBaseTest):@parameterized.expand(@@ -674,6 +676,64 @@ class TestTable(APIBaseTest):table.refresh_from_db()assert table.url_pattern == "https://your-org.s3.amazonaws.com/bucket/whatever.pqt"+ @parameterized.expand(+ [+ # The path-style endpoint names the same bucket as DATAWAREHOUSE_BUCKET_DOMAIN without+ # containing that domain, which is what made this reachable.+ ("posthog_bucket_path_style", "https://s3.us-east-1.amazonaws.com/ph-warehouse/file_uploads/team_*/*.csv"),+ ("unrelated_bucket", "https://acme-exports.s3.amazonaws.com/exports/*.csv"),+ ]+ )+ @override_settings(+ DATAWAREHOUSE_BUCKET_DOMAIN="warehouse-files.posthog.example", DATAWAREHOUSE_BUCKET="ph-warehouse"+ )+ def test_update_cannot_repoint_a_table_that_reads_with_the_node_role(self, _name: str, target_url: str):+ hosted_url = "https://warehouse-files.posthog.example/file_uploads/team_1/abc/data.csv"+ table = DataWarehouseTable.objects.create(+ name="uploaded_table",+ format="Parquet",+ team=self.team,+ team_id=self.team.pk,+ columns={},+ url_pattern=hosted_url,+ )++ with patch("products.warehouse_sources.backend.models.util.socket.getaddrinfo", return_value=PUBLIC_ADDRINFO):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/warehouse_tables/{table.id}",+ {"url_pattern": target_url},+ )++ assert response.status_code == 400+ table.refresh_from_db()+ assert table.url_pattern == hosted_url++ def test_update_can_repoint_a_table_that_has_its_own_credential(self):+ from products.warehouse_sources.backend.facade.models import DataWarehouseCredential++ credential = DataWarehouseCredential.objects.create(+ team=self.team, access_key="access_key", access_secret="access_secret"+ )+ table = DataWarehouseTable.objects.create(+ name="test_table",+ format="Parquet",+ team=self.team,+ team_id=self.team.pk,+ columns={},+ url_pattern="https://acme-exports.s3.amazonaws.com/old/*.pqt",+ credential=credential,+ )++ with patch("products.warehouse_sources.backend.models.util.socket.getaddrinfo", return_value=PUBLIC_ADDRINFO):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/warehouse_tables/{table.id}",+ {"url_pattern": "https://acme-exports.s3.amazonaws.com/new/*.pqt"},+ )++ assert response.status_code == 200+ table.refresh_from_db()+ assert table.url_pattern == "https://acme-exports.s3.amazonaws.com/new/*.pqt"+def test_update_table_credential_blank_access_key(self):from products.warehouse_sources.backend.facade.models import DataWarehouseCredentialdiff --git a/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py b/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.pyindex 281621ca3bcf..e4f6a8bebc4b 100644--- a/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py+++ b/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py@@ -1,4 +1,5 @@import io+import socketfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch@@ -231,6 +232,30 @@ class TestCreateTableFromUpload(APIBaseTest):# No pipeline source is created — this is the whole point of the self-managed shape.assert ExternalDataSource.objects.count() == 0+ def test_an_uploaded_table_cannot_be_repointed_at_another_location(self) -> None:+ # An uploaded table carries no credential, so it is read with the ClickHouse node's own role+ # rather than a key the team supplied. That only holds while PostHog owns the URL, so a hosted+ # table must not be movable. The target below is an ordinary customer bucket that nothing else+ # in the request would object to, so what this pins is the hosted-table rule itself.+ upload_id = self._upload()+ created = self._create(upload_id=upload_id, filename="orders.csv", file_format="csv", table_name="orders")+ assert created.status_code == status.HTTP_201_CREATED, created.json()+ table = DataWarehouseTable.objects.get(id=created.json()["id"])+ original_url_pattern = table.url_pattern++ with patch(+ "products.warehouse_sources.backend.models.util.socket.getaddrinfo",+ return_value=[(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("93.184.216.34", 0))],+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/warehouse_tables/{table.id}",+ {"url_pattern": "https://acme-exports.s3.amazonaws.com/exports/*.csv"},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ table.refresh_from_db()+ assert table.url_pattern == original_url_pattern+@parameterized.expand([("csv", "CSVWithNames"),diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.pyindex fd9af8f84842..c34c7f5c06aa 100644--- a/products/warehouse_sources/backend/models/util.py+++ b/products/warehouse_sources/backend/models/util.py@@ -5,6 +5,8 @@ from ipaddress import IPv6Address, ip_addressfrom typing import TYPE_CHECKING, Any, Protocol, TypeVar, Unionfrom urllib.parse import urlparse+from django.conf import settings+from posthog.hogql.database.models import (BooleanDatabaseField,DatabaseField,@@ -593,6 +595,71 @@ def _is_safe_public_ip(host: str) -> bool:)+# The AWS half matches the global, regional, dashed-regional, dualstack and accelerate endpoints,+# because a bucket answers on all of them and each one resolves to the same objects.+_STORAGE_ENDPOINT = r"(?:s3[.-][a-z0-9.-]*amazonaws\.com|storage\.googleapis\.com)"+_PATH_STYLE_STORAGE_HOST = re.compile(rf"^{_STORAGE_ENDPOINT}$")+_VIRTUAL_HOSTED_STORAGE_HOST = re.compile(rf"^(?P<bucket>.+?)\.{_STORAGE_ENDPOINT}$")++# ClickHouse expands these in an s3() URL. They belong in the key, never in the bucket position.+_GLOB_METACHARACTERS = frozenset("*?{}[]")++_NOT_OUR_STORAGE = (+ "This URL points to PostHog's internal storage and can't be used as a source. "+ "Enter the location of your own bucket instead."+)+++def _posthog_owned_bucket_names() -> set[str]:+ """Buckets PostHog owns, so a table must never be pointed at one.++ A self-managed table reads through ClickHouse, which falls back to its node IAM role when the+ table carries no credential. These are the buckets that role can reach, and they hold every+ team's data, so reading one across the API would cross the tenant boundary.+ """+ names = {+ settings.DATAWAREHOUSE_BUCKET,+ settings.BUCKET_PATH,+ settings.OBJECT_STORAGE_BUCKET,+ settings.SESSION_RECORDING_V2_S3_BUCKET,+ }+ # A couple of these settings are configured as `bucket/prefix`; only the bucket identifies storage.+ return {str(name).strip("/").split("/", 1)[0] for name in names if name}+++def _validate_url_pattern_is_not_posthog_storage(+ url_pattern: str, normalized_hostname: str, path: str+) -> tuple[bool, str]:+ """Reject a URL that addresses PostHog's own object storage, in any of the forms S3 accepts.++ A bucket answers to both a virtual-hosted host (`<bucket>.s3.<region>.amazonaws.com`) and a+ path-style one (`s3.<region>.amazonaws.com/<bucket>`), so a host check alone leaves the same+ object reachable under a name that doesn't look like ours.+ """+ configured_domain = (settings.DATAWAREHOUSE_BUCKET_DOMAIN or "").lower().strip()+ if configured_domain and configured_domain in url_pattern.lower():+ return False, _NOT_OUR_STORAGE++ owned_buckets = _posthog_owned_bucket_names()++ virtual_hosted = _VIRTUAL_HOSTED_STORAGE_HOST.match(normalized_hostname)+ if virtual_hosted:+ if virtual_hosted.group("bucket") in owned_buckets:+ return False, _NOT_OUR_STORAGE+ return True, ""++ if _PATH_STYLE_STORAGE_HOST.match(normalized_hostname):+ bucket = path.lstrip("/").split("/", 1)[0]+ # A glob here expands across buckets rather than within one, so it can reach ours whatever+ # it looks like. No source needs to pattern-match a bucket name.+ if any(character in _GLOB_METACHARACTERS for character in bucket):+ return False, "The bucket name in a URL pattern must be exact. Wildcards belong in the file path."+ if bucket in owned_buckets:+ return False, _NOT_OUR_STORAGE++ return True, ""++def validate_warehouse_table_url_pattern(url_pattern: str | None) -> tuple[bool, str]:if not url_pattern:return True, ""@@ -605,6 +672,15 @@ def validate_warehouse_table_url_pattern(url_pattern: str | None) -> tuple[bool,return False, "URL pattern must include a valid hostname."normalized_hostname = parsed.hostname.lower().strip().rstrip(".")++ # Runs before the DNS checks below so a URL aimed at our own storage always reports that, rather+ # than whatever the internal hostname happens to resolve to.+ is_valid, error_message = _validate_url_pattern_is_not_posthog_storage(+ url_pattern, normalized_hostname, parsed.path+ )+ if not is_valid:+ return is_valid, error_message+if normalized_hostname in {"localhost"}:return False, "URL pattern hostname is not allowed."diff --git a/products/warehouse_sources/backend/tests/test_util.py b/products/warehouse_sources/backend/tests/test_util.pyindex 41533f6100c2..a29b96dfe6c1 100644--- a/products/warehouse_sources/backend/tests/test_util.py+++ b/products/warehouse_sources/backend/tests/test_util.py@@ -1,15 +1,24 @@+import socket+from posthog.test.base import BaseTest+from unittest.mock import patch-from django.test import SimpleTestCase+from django.test import SimpleTestCase, override_settingsfrom parameterized import parameterizedfrom products.warehouse_sources.backend.models.credential import DataWarehouseCredentialfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable-from products.warehouse_sources.backend.models.util import get_view_or_table_by_name, reconstruct_ordered_columns+from products.warehouse_sources.backend.models.util import (+ get_view_or_table_by_name,+ reconstruct_ordered_columns,+ validate_warehouse_table_url_pattern,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+PUBLIC_ADDRINFO = [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("93.184.216.34", 0))]+class TestReconstructOrderedColumns(SimpleTestCase):@parameterized.expand(@@ -35,6 +44,66 @@ class TestReconstructOrderedColumns(SimpleTestCase):assert dict(result) == columns+@override_settings(+ DATAWAREHOUSE_BUCKET_DOMAIN="warehouse-files.posthog.example",+ DATAWAREHOUSE_BUCKET="ph-warehouse",+ BUCKET_PATH="ph-warehouse",+ OBJECT_STORAGE_BUCKET="ph-objects",+ SESSION_RECORDING_V2_S3_BUCKET="ph-replay",+)+class TestValidateWarehouseTableUrlPattern(SimpleTestCase):+ @parameterized.expand(+ [+ # One bucket answers to several names. Each of these reaches PostHog's own storage, so a+ # check on any single form leaves the rest open.+ ("virtual_hosted_global", "https://ph-warehouse.s3.amazonaws.com/file_uploads/team_2/x.csv"),+ ("virtual_hosted_regional", "https://ph-warehouse.s3.us-east-1.amazonaws.com/file_uploads/x.csv"),+ ("virtual_hosted_dashed_region", "https://ph-warehouse.s3-us-west-2.amazonaws.com/x.csv"),+ ("virtual_hosted_dualstack", "https://ph-warehouse.s3.dualstack.us-east-1.amazonaws.com/x.csv"),+ ("path_style_global", "https://s3.amazonaws.com/ph-warehouse/x.csv"),+ ("path_style_regional", "https://s3.us-east-1.amazonaws.com/ph-warehouse/file_uploads/team_*/*/*.csv"),+ ("gcs_virtual_hosted", "https://ph-warehouse.storage.googleapis.com/x.csv"),+ ("gcs_path_style", "https://storage.googleapis.com/ph-warehouse/x.csv"),+ ("configured_bucket_domain", "https://warehouse-files.posthog.example/file_uploads/team_2/x.csv"),+ # Buckets other than the warehouse one are just as reachable from the ClickHouse node.+ ("object_storage_bucket", "https://s3.us-east-1.amazonaws.com/ph-objects/exports/x.csv"),+ ("session_replay_bucket", "https://ph-replay.s3.eu-central-1.amazonaws.com/x.json"),+ ]+ )+ def test_rejects_urls_that_address_posthog_storage(self, _name: str, url_pattern: str) -> None:+ is_valid, error_message = validate_warehouse_table_url_pattern(url_pattern)++ assert not is_valid+ assert "internal storage" in error_message++ @parameterized.expand(+ [+ ("brace_expansion", "https://s3.us-east-1.amazonaws.com/{ph-warehouse,acme}/x.csv"),+ ("wildcard", "https://s3.us-east-1.amazonaws.com/ph-*/x.csv"),+ ]+ )+ def test_rejects_a_glob_in_the_bucket_position(self, _name: str, url_pattern: str) -> None:+ is_valid, error_message = validate_warehouse_table_url_pattern(url_pattern)++ assert not is_valid+ assert "bucket name" in error_message++ @parameterized.expand(+ [+ ("customer_virtual_hosted", "https://acme-exports.s3.us-east-1.amazonaws.com/warehouse/*.parquet"),+ ("customer_path_style", "https://s3.us-east-1.amazonaws.com/acme-exports/warehouse/*.parquet"),+ # A PostHog bucket name used as a key prefix in someone else's bucket is theirs, not ours.+ ("our_bucket_name_as_a_key_prefix", "https://acme-exports.s3.amazonaws.com/ph-warehouse/*.csv"),+ ("non_storage_host", "https://files.acme.example/exports/*.csv"),+ ]+ )+ def test_allows_a_customers_own_bucket(self, _name: str, url_pattern: str) -> None:+ with patch("products.warehouse_sources.backend.models.util.socket.getaddrinfo", return_value=PUBLIC_ADDRINFO):+ is_valid, error_message = validate_warehouse_table_url_pattern(url_pattern)++ assert is_valid, error_message++class TestGetViewOrTableByName(BaseTest):def _create_warehouse_table(self, *, name, url_pattern, source=None, credential=None) -> DataWarehouseTable:return DataWarehouseTable.objects.create(