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.

fix(warehouse): bypass environment proxies for managed trino (#104804)

Eric Duongf33f39a0a4ba
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.md
index daa59154ace6..5340c24bc281 100644
--- a/docs/internal/hogql-trino-compiler.md
+++ b/docs/internal/hogql-trino-compiler.md
@@ -76,6 +76,11 @@ Call `resolve_managed_warehouse_trino_connection(...)` through the managed-wareh
Call `connect_managed_warehouse_trino(...)` to open the Python Trino client with basic authentication, HTTPS, certificate verification, and a bounded request timeout. The connector has no Duckgres fallback. A disabled target, non-ready state, organization mismatch, malformed endpoint, or missing stored credential fails before opening a socket.
+The managed connector uses a dedicated HTTP session that bypasses environment proxies only for known PostHog-hosted Trino endpoints on port 443.
+It uses the same hosted endpoint check as direct Trino connections.
+Other destinations retain proxy settings.
+The connector keeps certificate verification enabled and closes the session when the connection scope exits.
+
The Django `DuckgresServer` row remains the transitional owner of the existing root secret; it does not become the source of truth for Trino placement. Trino cell assignment, endpoint identity, and catalog naming stay in the control plane. No second Django model or copied control-plane status is required.
For supported string, array, and map arguments, `empty(x)` returns true when the value is NULL or has zero length. `notEmpty(x)` requires a non-NULL value with nonzero length. String predicates use an empty-string comparison; arrays and maps use `cardinality`.
diff --git a/products/managed_warehouse/backend/tests/test_trino_connection.py b/products/managed_warehouse/backend/tests/test_trino_connection.py
index d3dc66157652..f1bccc6a75d3 100644
--- a/products/managed_warehouse/backend/tests/test_trino_connection.py
+++ b/products/managed_warehouse/backend/tests/test_trino_connection.py
@@ -1,6 +1,9 @@
+import os
+
import pytest
from unittest import mock
+import requests
from rest_framework.response import Response
from products.managed_warehouse.backend.facade.contracts import (
@@ -150,5 +153,48 @@ def test_connect_managed_warehouse_trino_enforces_verified_https_and_closes() ->
auth=authentication,
request_timeout=60,
verify=True,
+ http_session=mock.ANY,
)
driver_connection.close.assert_called_once_with()
+
+
+ "host,port,bypass_proxy",
+ [
+ ("trino.dw.us.postwh.com", 443, True),
+ ("TRINO.DW.US.POSTWH.COM.", 443, True),
+ ("trino.dw.us.postwh.com", 8443, False),
+ ("trino.example.com", 443, False),
+ ],
+)
+def test_managed_trino_requests_bypass_environment_proxies_only_for_known_hosts(
+ host: str, port: int, bypass_proxy: bool
+) -> None:
+ proxy_url = "http://proxy.example.com:4750"
+ with (
+ mock.patch.dict(os.environ, {"HTTPS_PROXY": proxy_url, "NO_PROXY": ""}, clear=True),
+ mock.patch(
+ "products.managed_warehouse.backend.presentation.views._request",
+ return_value=_ready_response(host=host, port=port),
+ ),
+ mock.patch(
+ "products.managed_warehouse.backend.trino_connection.get_duckgres_query_server_config",
+ return_value=_root_connection(),
+ ),
+ mock.patch("requests.adapters.HTTPAdapter.send", side_effect=RuntimeError("network boundary")) as send,
+ ):
+ with pytest.raises(RuntimeError, match="network boundary"):
+ with connect_managed_warehouse_trino("org-1") as connection:
+ connection.cursor().execute("SELECT 1")
+
+ send.assert_called_once()
+ request = send.call_args.args[0]
+ assert request.url == f"https://{host.lower()}:{port}/v1/statement"
+ assert request.headers["Authorization"].startswith("Basic ")
+ assert send.call_args.kwargs["proxies"].get("https") == (None if bypass_proxy else proxy_url)
+ assert send.call_args.kwargs["verify"] is True
+ assert send.call_args.kwargs["timeout"] == 60
+
+ with requests.Session() as ordinary_session:
+ settings = ordinary_session.merge_environment_settings("https://example.com", {}, False, True, None)
+ assert settings["proxies"]["https"] == proxy_url
diff --git a/products/managed_warehouse/backend/trino_connection.py b/products/managed_warehouse/backend/trino_connection.py
index 8df1a231c138..05e1de0ca06d 100644
--- a/products/managed_warehouse/backend/trino_connection.py
+++ b/products/managed_warehouse/backend/trino_connection.py
@@ -4,12 +4,15 @@ from collections.abc import Iterator
from contextlib import contextmanager
from typing import TYPE_CHECKING
+import requests
+
from products.managed_warehouse.backend.facade.api import get_duckgres_query_server_config
from products.managed_warehouse.backend.facade.contracts import (
ManagedWarehouseTrinoConnection,
ManagedWarehouseTrinoConnectionUnavailable,
)
from products.managed_warehouse.backend.trino_target import get_ready_trino_connection_target
+from products.warehouse_sources.backend.facade import source_management
if TYPE_CHECKING:
from trino.dbapi import Connection
@@ -48,17 +51,22 @@ def connect_managed_warehouse_trino(organization_id: str) -> Iterator[Connection
from trino.dbapi import connect # noqa: PLC0415 -- keeps the optional driver off startup paths
config = resolve_managed_warehouse_trino_connection(organization_id)
- connection = connect(
- host=config.host,
- port=config.port,
- user=config.username,
- catalog=config.catalog,
- http_scheme="https",
- auth=BasicAuthentication(config.username, config.password),
- request_timeout=60,
- verify=True,
- )
- try:
- yield connection
- finally:
- connection.close()
+ with requests.Session() as http_session:
+ # Only known hosted Trino endpoints bypass the proxy's private-IP restrictions.
+ if source_management.is_posthog_managed_trino_host(config.host) and config.port == 443:
+ http_session.trust_env = False
+ connection = connect(
+ host=config.host,
+ port=config.port,
+ user=config.username,
+ catalog=config.catalog,
+ http_scheme="https",
+ auth=BasicAuthentication(config.username, config.password),
+ request_timeout=60,
+ verify=True,
+ http_session=http_session,
+ )
+ try:
+ yield connection
+ finally:
+ connection.close()
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.py
index 1191ceeaa321..1f26e4405bcd 100644
--- a/products/warehouse_sources/backend/facade/source_management.py
+++ b/products/warehouse_sources/backend/facade/source_management.py
@@ -86,6 +86,7 @@ _LAZY = {
"RedshiftSource": "sources.redshift.source",
"SnowflakeSource": "sources.snowflake.source",
"connect_trino": "sources.trino.trino",
+ "is_posthog_managed_trino_host": "sources.trino.trino",
"trino_error_to_message": "sources.trino.trino",
}
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.py
index 74fc81a9d610..7a2493b890c2 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
@@ -59,7 +59,7 @@ POSTHOG_MANAGED_TRINO_HOSTS = frozenset(
TRINO_COLUMN_DISCOVERY_TABLE_BATCH_SIZE = 100
-def _is_posthog_managed_trino_host(host: str) -> bool:
+def is_posthog_managed_trino_host(host: str) -> bool:
return host.lower().rstrip(".") in POSTHOG_MANAGED_TRINO_HOSTS
@@ -160,7 +160,7 @@ def connect_trino(config: TrinoSourceConfig) -> Iterator[Connection]:
value for value in (config.auth_type.password, config.auth_type.token) if isinstance(value, str) and value
)
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:
+ if is_posthog_managed_trino_host(config.host) and config.port == 443 and config.use_ssl and config.verify_ssl:
session.trust_env = False
session.verify = config.verify_ssl
log_connection_open(db_host=config.host, via="trino_https" if config.use_ssl else "trino_http")