: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(warehouse): support direct queries through tenant trino hosts (#119573)
Benjamin Knofe-Vider54e5632b82b3
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex e8e1f5483b35..ef1c49b276b1 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -80,7 +80,6 @@ The standalone `resolve_managed_warehouse_trino_connection(...)` helper returnsThe connection uses HTTPS with certificate verification and a 60-second HTTP timeout.Its session bypasses environment proxies only for control-plane-issued targets with a single hostname label under `dw.us.postwh.com`, `dw.eu.postwh.com`, or `dw.dev.postwh.com`, on port 443.-Customer-configured external sources retain the separate fixed-host allowlist (`trino.dw.us.postwh.com`, `trino.dw.eu.postwh.com`, and `trino.dw.dev.postwh.com`).The session checks and renews the same grant before sending POST, polling GET, or cancellation DELETE requests when less than two minutes remain.Mint and renewal calls have a ten-second timeout.Credential renewal is serialized so polling and cancellation share one renewal decision.@@ -91,6 +90,15 @@ Existing Duckgres refresh calls retain their default secret-rotation behavior.A changed endpoint, catalog or username fails closed, as do redirects and polling URLs outside the issued HTTPS origin.The session closes when the connection scope exits.+Customer-configured external Trino sources also bypass environment proxies for these regional tenant hostnames.+This requires HTTPS on port 443 with certificate verification.+Use the same tenant hostname, SQL username, and password as the CLI.+PostHog passes the configured credentials unchanged.+External sources retain the tracked HTTP transport.+They reject redirects or polling URLs outside the configured HTTPS origin.+Other external hosts retain the environment proxy behavior.+Existing shared Trino hostnames remain compatible with their configured usernames.+Deploy the service-grant validator, Trino authenticator, Gateway service-identity routing, and cell-specific validation tokens before deploying this caller.The control plane must return a ready `trino_connect` block on mint and `secret_rotated=false` on renewal.Renewal may omit `trino_connect` while readiness information is unavailable; the session retains its original target and requires the same grant identity and a usable renewed expiry.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.pyindex d6bea32b057a..15ba7fd7634c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.py@@ -1,3 +1,5 @@+import os+import base64import datetime as dtfrom collections.abc import Iterablefrom contextlib import nullcontext@@ -18,6 +20,10 @@ from products.warehouse_sources.backend.presentation.views.external_data_source._classify_refresh_schemas_error,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ ScriptedResponse,+ scripted_network,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputsfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.trino import (TrinoAuthTypeConfig,@@ -34,6 +40,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.trino.trinTRINO_READ_TIMEOUT_ERROR,DiscoveredTrinoTable,TrinoColumn,+ TrinoConfigurationError,TrinoImplementation,TrinoSchemaDiscoveryError,build_trino_select,@@ -85,49 +92,170 @@ def test_connect_trino_uses_tracked_session_and_closes_resources() -> None:session.close.assert_called_once_with()+def _completed_trino_response() -> ScriptedResponse:+ return ScriptedResponse(+ json={+ "id": "example_query",+ "infoUri": "https://example.com/query",+ "stats": {},+ "columns": [{"name": "value", "type": "bigint", "typeSignature": {"rawType": "bigint", "arguments": []}}],+ "data": [[1]],+ }+ )++@pytest.mark.parametrize(- ("host", "port", "use_ssl", "verify_ssl", "expected_trust_env"),+ ("host", "port", "use_ssl", "verify_ssl", "direct"),[- ("trino.dw.us.postwh.com", 443, True, True, False),- ("trino.dw.eu.postwh.com", 443, True, True, False),- ("TRINO.DW.DEV.POSTWH.COM.", 443, True, True, False),- ("trino.example.com", 443, True, True, True),- ("other.dw.us.postwh.com", 443, True, True, True),- ("tenant.dw.dev.postwh.com", 443, True, True, True),- ("nested.tenant.dw.us.postwh.com", 443, True, True, True),- ("dw.us.postwh.com", 443, True, True, True),- ("tenant.dw.us.postwh.com.example.com", 443, True, True, True),- ("trino.dw.us.postwh.com", 8443, True, True, True),- ("trino.dw.us.postwh.com", 443, False, True, True),- ("trino.dw.us.postwh.com", 443, True, False, True),+ ("trino.dw.us.postwh.com", 443, True, True, True),+ ("trino.dw.eu.postwh.com", 443, True, True, True),+ ("TRINO.DW.DEV.POSTWH.COM.", 443, True, True, True),+ ("example.dw.us.postwh.com", 443, True, True, True),+ ("example.dw.eu.postwh.com", 443, True, True, True),+ ("EXAMPLE.DW.DEV.POSTWH.COM.", 443, True, True, True),+ ("example-1.dw.eu.postwh.com", 443, True, True, True),+ ("x.dw.us.postwh.com", 443, True, True, True),+ ("trino.example.com", 443, True, True, False),+ ("nested.example.dw.us.postwh.com", 443, True, True, False),+ ("dw.us.postwh.com", 443, True, True, False),+ ("example.dw.us.postwh.com.example.com", 443, True, True, False),+ ("example.dw.ap.postwh.com", 443, True, True, False),+ ("example_.dw.eu.postwh.com", 443, True, True, False),+ ("-example.dw.eu.postwh.com", 443, True, True, False),+ ("example-.dw.eu.postwh.com", 443, True, True, False),+ ("\u212a.dw.eu.postwh.com", 443, True, True, False),+ ("example.dw.us.postwh.com", 8443, True, True, False),+ ("example.dw.us.postwh.com", 443, False, True, False),+ ("example.dw.us.postwh.com", 443, True, False, False),],)def test_connect_trino_bypasses_proxy_only_for_managed_tls_endpoints(- host: str, port: int, use_ssl: bool, verify_ssl: bool, expected_trust_env: bool+ host: str, port: int, use_ssl: bool, verify_ssl: bool, direct: bool) -> None:- connection = MagicMock()- session = MagicMock(trust_env=True)- auth_type = TrinoAuthTypeConfig(user="posthog", selection="none")-with (- patch("trino.dbapi.connect", return_value=connection),- patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.trino.trino.make_tracked_session",- return_value=session,+ patch.dict(+ os.environ,+ {+ "HTTPS_PROXY": "http://proxy.example.com:4750",+ "HTTP_PROXY": "http://proxy.example.com:4750",+ "NO_PROXY": "",+ },+ clear=True,),+ scripted_network([_completed_trino_response()]) as network,connect_trino(_config(host=host,port=port,use_ssl=use_ssl,verify_ssl=verify_ssl,- auth_type=auth_type,+ auth_type=TrinoAuthTypeConfig(user="sql_reader", selection="none"),)+ ) as connection,+ ):+ cursor = connection.cursor()+ cursor.execute("SELECT 1")+ assert cursor.fetchall() == [[1]]++ assert len(network.requests_log) == 1+ assert ("proxy.example.com" not in network.requests_log[0].origin) is direct+++ ("host", "auth_type", "authorization"),+ [+ (+ "example.dw.us.postwh.com",+ TrinoAuthTypeConfig(user="sql_reader", selection="password", password="example-password"),+ "Basic " + base64.b64encode(b"sql_reader:example-password").decode(),+ ),+ (+ "example.dw.eu.postwh.com",+ TrinoAuthTypeConfig(user="sql_reader", selection="jwt", token="example-token"),+ "Bearer example-token",+ ),+ (+ "trino.dw.dev.postwh.com",+ TrinoAuthTypeConfig(user="example.sql_reader", selection="password", password="example-password"),+ "Basic " + base64.b64encode(b"example.sql_reader:example-password").decode(),),+ ],+)+def test_connect_trino_preserves_credentials_when_polling(+ host: str, auth_type: TrinoAuthTypeConfig, authorization: str+) -> None:+ with (+ patch.dict(os.environ, {"HTTPS_PROXY": "http://proxy.example.com:4750", "NO_PROXY": ""}, clear=True),+ scripted_network(+ [+ ScriptedResponse(+ json={+ "id": "example_query",+ "infoUri": "https://example.com/query",+ "stats": {},+ "nextUri": f"https://{host}:443/v1/statement/example_query",+ }+ ),+ _completed_trino_response(),+ ]+ ) as network,+ connect_trino(_config(host=host, auth_type=auth_type)) as connection,):- pass+ cursor = connection.cursor()+ cursor.execute("SELECT 1")+ assert cursor.fetchall() == [[1]]++ assert [request.method for request in network.requests_log] == ["POST", "GET"]+ assert all("proxy.example.com" not in request.origin for request in network.requests_log)+ assert all(request.headers["authorization"] == authorization for request in network.requests_log)+ assert all(request.headers["x-trino-user"] == auth_type.user for request in network.requests_log)+++ "target",+ [+ "https://other.example.com/v1/statement/example_query",+ "https://other.dw.eu.postwh.com/v1/statement/example_query",+ "http://example.dw.eu.postwh.com/v1/statement/example_query",+ "https://example.dw.eu.postwh.com:444/v1/statement/example_query",+ "https://[email protected]/v1/statement/example_query",+ ],+)+def test_connect_trino_rejects_polling_outside_the_managed_origin(target: str) -> None:+ with (+ patch.dict(os.environ, {}, clear=True),+ scripted_network(+ [+ ScriptedResponse(+ json={"id": "example_query", "infoUri": "https://example.com/query", "stats": {}, "nextUri": target}+ ),+ _completed_trino_response(),+ ]+ ) as network,+ pytest.raises(TrinoConfigurationError, match="connection destination"),+ connect_trino(_config(host="example.dw.eu.postwh.com")) as connection,+ ):+ connection.cursor().execute("SELECT 1")++ assert len(network.requests_log) == 1++[email protected]("status", [301, 302, 303, 307, 308])+def test_connect_trino_does_not_follow_managed_redirects(status: int) -> None:+ with (+ patch.dict(os.environ, {}, clear=True),+ scripted_network(+ [+ ScriptedResponse(status=status, headers={"Location": "https://other.example.com/v1/statement"}),+ _completed_trino_response(),+ ]+ ) as network,+ pytest.raises(TrinoConfigurationError, match="connection destination"),+ connect_trino(_config(host="example.dw.eu.postwh.com")) as connection,+ ):+ connection.cursor().execute("SELECT 1")- assert session.trust_env is expected_trust_env+ assert len(network.requests_log) == 1def test_connect_trino_rejects_credentials_over_http() -> None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.pyindex 3f8e1d046137..bc15875cf607 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py@@ -7,8 +7,10 @@ from collections.abc import Callable, Iterator, Mappingfrom contextlib import contextmanagerfrom itertools import batchedfrom typing import TYPE_CHECKING, Any+from urllib.parse import urlsplitimport pyarrow as pa+from requests.adapters import BaseAdapterfrom requests.exceptions import ConnectTimeout, RequestException, Timeoutfrom posthog.dataclasses import frozen@@ -53,6 +55,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.types import IncrementalFieldTypeif TYPE_CHECKING:+ from requests import PreparedRequest, Responsefrom trino.dbapi import Connection, Cursor@@ -75,6 +78,7 @@ TRINO_TLS_CERTIFICATE_ERROR = ("Check the certificate or turn off certificate verification.")TRINO_CONNECTION_ERROR = "PostHog could not connect to Trino."+TRINO_CONNECTION_DESTINATION_ERROR = "Trino returned an unsupported connection destination. Check the connection host."TRINO_CONNECT_TIMEOUT_ERROR = ("Connection to Trino timed out. Check the host and port, and that PostHog's egress IP addresses are ""allowed through your firewall."@@ -151,20 +155,19 @@ TRINO_PERMANENT_SYNC_ERROR_MESSAGES = frozenset(TRINO_ACCESS_DENIED_ERROR,})-POSTHOG_MANAGED_TRINO_HOSTS = frozenset(- {- "trino.dw.dev.postwh.com",- "trino.dw.eu.postwh.com",- "trino.dw.us.postwh.com",- }-)+POSTHOG_MANAGED_TRINO_HOST_PATTERN = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.dw\.(?:dev|eu|us)\.postwh\.com")# Trino's OPA access control can issue one column-filter request per table, so keep# discovery batches comfortably below the HTTP client's outstanding-request limit.TRINO_COLUMN_DISCOVERY_TABLE_BATCH_SIZE = 100+def _normalize_trino_host(host: str) -> str | None:+ return host.lower().removesuffix(".") if host.isascii() else None++def is_posthog_managed_trino_host(host: str) -> bool:- return host.lower().rstrip(".") in POSTHOG_MANAGED_TRINO_HOSTS+ normalized = _normalize_trino_host(host)+ return normalized is not None and POSTHOG_MANAGED_TRINO_HOST_PATTERN.fullmatch(normalized) is not None@frozen@@ -190,7 +193,49 @@ class TrinoSchemaDiscoveryError(Exception):class TrinoConfigurationError(ValueError):- """A connection setting Trino cannot be reached with, found before PostHog opens the connection."""+ """A connection setting or server response that PostHog cannot use safely."""+++class _TrinoOriginAdapter(BaseAdapter):+ def __init__(self, adapter: BaseAdapter, host: str) -> None:+ self._adapter = adapter+ self._host = _normalize_trino_host(host)++ def send(+ self,+ request: PreparedRequest,+ stream: bool = False,+ timeout: float | tuple[float, float] | tuple[float, None] | None = None,+ verify: bool | str = True,+ cert: bytes | str | tuple[bytes | str, bytes | str] | None = None,+ proxies: Mapping[str, str] | None = None,+ ) -> Response:+ # The driver follows nextUri itself, outside the session's HTTP redirect policy.+ try:+ target = urlsplit(request.url or "")+ allowed = (+ self._host is not None+ and target.scheme == "https"+ and _normalize_trino_host(target.hostname or "") == self._host+ and target.port in (None, 443)+ and target.username is None+ and target.password is None+ )+ except ValueError:+ allowed = False+ if not allowed or verify is not True:+ raise TrinoConfigurationError(TRINO_CONNECTION_DESTINATION_ERROR)++ response = self._adapter.send(+ request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies+ )+ if 300 <= response.status_code < 400:+ response.close()+ raise TrinoConfigurationError(TRINO_CONNECTION_DESTINATION_ERROR)+ return response++ def close(self) -> None:+ self._adapter.close()def _timeout_in_chain(error: BaseException) -> Timeout | None:@@ -287,6 +332,9 @@ def connect_trino(config: TrinoSourceConfig, *, timezone: str | None = None) ->session = make_tracked_session(redact_values=redacted, allow_redirects=False)if is_posthog_managed_trino_host(config.host) and config.port == 443 and config.use_ssl and config.verify_ssl:session.trust_env = False+ adapter = _TrinoOriginAdapter(session.get_adapter("https://"), config.host)+ session.mount("https://", adapter)+ session.mount("http://", adapter)session.verify = config.verify_ssllog_connection_open(db_host=config.host, via="trino_https" if config.use_ssl else "trino_http")connection: Connection | None = None