: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
feat(managed-warehouse): use service credentials for trino (#106197)
Eric Duong6d4621a9ea16
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex 11f59d54f78d..0decc4d56793 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -72,16 +72,36 @@ The integration does not provision catalogs, alter deployments, or make source-o## Managed Trino connections-Call `resolve_managed_warehouse_trino_connection(...)` through the managed-warehouse client facade when a backend job needs a live Trino target. The resolver accepts a target only when the control plane reports the organization as enabled and ready. It reads the catalog plus non-secret host, port, and username from `status.connection`, then uses the encrypted `DuckgresServer.trino_password` when one is configured. Existing rows fall back to the stored Duckgres password until a Trino password is set. Staff can set or replace the Trino password in the Duckgres server Django admin form; the saved value is never displayed there. The connection contract redacts that password from its representation.--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.+Call `connect_managed_warehouse_trino(...)` for internal Trino work.+It mints an organization-scoped service grant through the existing control-plane credential API and uses the returned `trino_connect` host, port, catalog and username.+Shadow materialization and alias reconciliation supply distinct audit principals that identify their team and operation.+The grant secret exists only in process memory; these paths never read `DuckgresServer.password` or `trino_password` and have no stored-password fallback.+The standalone `resolve_managed_warehouse_trino_connection(...)` helper returns a short-lived snapshot; callers executing queries must use the context manager to get refresh behavior.++The 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` or `dw.dev.postwh.com`, on port 443.+Customer-configured external sources retain the separate fixed-host allowlist (`trino.dw.us.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.+HTTP sends run outside the renewal lock so cancellation can proceed while a poll is blocked.+Renewal uses `rotate_secret=false` on the existing refresh endpoint and retains both the grant ID and secret.+The gateway binds query ownership to the full credential, so rotating its secret during an active query would break polling and cancellation.+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.++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.+If renewal includes a target, it must match the original target.+An older or unconfigured control plane can still serve Duckgres callers, but internal Trino callers fail before sending SQL.+Trino revalidates grants on every HTTP request, including expiry and revocation, unlike Duckgres's handshake-only expiry.+Revocation prevents subsequent polling and cancellation; it does not itself terminate an already running query.+External Trino sources continue to use their configured persistent user credentials.++Trino placement, catalog naming, service-grant issuance and authorization remain owned by the control plane.+The encrypted password fields remain available for existing persistent-user integrations but are not part of internal Trino shadow authentication.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/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.pyindex 52b06319dc40..d1b58a7826e7 100644--- a/products/managed_warehouse/backend/facade/contracts.py+++ b/products/managed_warehouse/backend/facade/contracts.py@@ -15,7 +15,7 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom datetime import date, datetimefrom enum import StrEnum-from typing import Any+from typing import Any, Literalfrom uuid import UUIDfrom posthog.dataclasses import frozen@@ -45,6 +45,7 @@ __all__ = ["ManagedWarehouseTeamMembership","ServiceCredential","ServiceCredentialConnect",+ "ServiceCredentialTrinoConnect","ServiceCredentialUnavailable","TrinoCompiledQuery","TrinoExpansionMode",@@ -73,6 +74,15 @@ class ServiceCredentialConnect:sslmode: str+@frozen+class ServiceCredentialTrinoConnect:+ host: str+ port: int+ catalog: str+ username: str+ http_scheme: Literal["https"]++@dataclass(frozen=True)class ServiceCredential:"""An org-scoped per-credential grant minted by the duckgres control@@ -98,6 +108,7 @@ class ServiceCredential:credential_secret: str = field(repr=False)expires_at: datetimeconnect: ServiceCredentialConnect+ trino_connect: ServiceCredentialTrinoConnect | None = Noneclass ServiceCredentialUnavailable(RuntimeError):@@ -118,13 +129,15 @@ class ManagedWarehousePostgresConnection:@frozenclass ManagedWarehouseTrinoConnection:- """A ready managed Trino target with the existing organization root secret."""+ """A minted Trino connection snapshot; use the connection context manager for refresh."""host: strport: intcatalog: strusername: strpassword: str = field(repr=False)+ credential_id: str+ expires_at: datetimeclass ManagedWarehouseTrinoConnectionUnavailable(RuntimeError):diff --git a/products/managed_warehouse/backend/service_credentials.py b/products/managed_warehouse/backend/service_credentials.pyindex 2429cabe26ea..b44432f33471 100644--- a/products/managed_warehouse/backend/service_credentials.py+++ b/products/managed_warehouse/backend/service_credentials.py@@ -43,6 +43,7 @@ from rest_framework import statusfrom products.managed_warehouse.backend.facade.contracts import (ServiceCredential,ServiceCredentialConnect,+ ServiceCredentialTrinoConnect,ServiceCredentialUnavailable,)@@ -55,6 +56,7 @@ __all__ = ["ServiceCredentialUnavailable","mint_service_credential","refresh_service_credential",+ "renew_service_credential",]logger = structlog.get_logger(__name__)@@ -92,7 +94,7 @@ def _redact_payload(data: Any) -> Any:def mint_service_credential(organization_id: str,- team_id: int,+ team_id: int | None = None,*,principal: str,ttl_seconds: int = DEFAULT_CREDENTIAL_TTL_SECONDS,@@ -160,6 +162,7 @@ def refresh_service_credential(credential_id: str,*,ttl_seconds: int = DEFAULT_CREDENTIAL_TTL_SECONDS,+ timeout_seconds: int | None = None,) -> ServiceCredential:"""Rotate the secret on a known credential before it lapses.@@ -177,6 +180,10 @@ def refresh_service_credential(ttl_seconds = max(MIN_CREDENTIAL_TTL_SECONDS, min(ttl_seconds, MAX_CREDENTIAL_TTL_SECONDS))+ request_kwargs: dict[str, Any] = {}+ if timeout_seconds is not None:+ request_kwargs["timeout"] = timeout_seconds+response = _request("POST",organization_id,@@ -186,6 +193,7 @@ def refresh_service_credential("ttl_seconds": ttl_seconds,},require_enabled=False,+ **request_kwargs,)if not status.is_success(response.status_code):raise ServiceCredentialUnavailable(@@ -205,6 +213,47 @@ def refresh_service_credential(return credential+def renew_service_credential(+ organization_id: str,+ credential_id: str,+ *,+ credential_secret: str,+ ttl_seconds: int = DEFAULT_CREDENTIAL_TTL_SECONDS,+ timeout_seconds: int = 10,+) -> ServiceCredential:+ """Extend a Trino grant without changing the gateway's query-owner credential."""+ from products.managed_warehouse.backend.presentation.views import (+ _request, # noqa: PLC0415 -- breaks the provisioning facade import cycle+ )++ response = _request(+ "POST",+ organization_id,+ "/service-credentials/refresh",+ json_body={+ "credential_id": credential_id,+ "ttl_seconds": max(MIN_CREDENTIAL_TTL_SECONDS, min(ttl_seconds, MAX_CREDENTIAL_TTL_SECONDS)),+ "rotate_secret": False,+ },+ require_enabled=False,+ timeout=timeout_seconds,+ )+ if not status.is_success(response.status_code) or not isinstance(response.data, dict):+ raise ServiceCredentialUnavailable("Trino service credential renewal failed")+ data = response.data+ # Older control planes ignore rotate_secret and rotate; never silently switch query ownership.+ if data.get("secret_rotated") is not False or data.get("credential_secret"):+ raise ServiceCredentialUnavailable("The control plane does not support Trino service credential renewal")+ credential = _parse_credential_response({**data, "credential_secret": credential_secret}, action="renew")+ logger.info(+ "trino_service_credential_renewed",+ organization_id=organization_id,+ credential_id=credential_id,+ expires_at=credential.expires_at.isoformat(),+ )+ return credential++def _parse_credential_response(data: dict[str, Any], *, action: str) -> ServiceCredential:"""Parse a successful mint/refresh response into a ``ServiceCredential``.@@ -232,6 +281,7 @@ def _parse_credential_response(data: dict[str, Any], *, action: str) -> ServiceCcredential_secret=str(credential_secret),expires_at=expires_at,connect=connect,+ trino_connect=_parse_trino_connect(data),)@@ -262,3 +312,27 @@ def _parse_connect(data: dict[str, Any], *, action: str = "mint") -> ServiceCredif not host or not database or not sslmode or port <= 0:raise ServiceCredentialUnavailable(f"{action} returned incomplete connect block: {_redact_payload(data)!r}")return ServiceCredentialConnect(host=str(host), port=port, database=str(database), sslmode=str(sslmode))+++def _parse_trino_connect(data: dict[str, Any]) -> ServiceCredentialTrinoConnect | None:+ raw = data.get("trino_connect")+ if raw is None:+ return None+ if not isinstance(raw, dict):+ raise ServiceCredentialUnavailable("Invalid Trino service credential target")+ host, catalog, username = raw.get("host"), raw.get("catalog"), raw.get("username")+ port = raw.get("port")+ if (+ not isinstance(host, str)+ or not host.strip()+ or not isinstance(catalog, str)+ or not catalog.strip()+ or not isinstance(username, str)+ or not username.strip()+ or isinstance(port, bool)+ or not isinstance(port, int)+ or not 1 <= port <= 65535+ or raw.get("http_scheme") != "https"+ ):+ raise ServiceCredentialUnavailable("Invalid Trino service credential target")+ return ServiceCredentialTrinoConnect(host=host, port=port, catalog=catalog, username=username, http_scheme="https")diff --git a/products/managed_warehouse/backend/tests/test_trino_connection.py b/products/managed_warehouse/backend/tests/test_trino_connection.pyindex b32128b5ba0e..5a51c4704b85 100644--- a/products/managed_warehouse/backend/tests/test_trino_connection.py+++ b/products/managed_warehouse/backend/tests/test_trino_connection.py@@ -1,4 +1,8 @@import os+import base64+from concurrent.futures import ThreadPoolExecutor+from datetime import UTC, datetime, timedelta+from threading import Eventimport pytestfrom unittest import mock@@ -12,175 +16,323 @@ from products.managed_warehouse.backend.trino_connection import (resolve_managed_warehouse_trino_connection,)+CREDENTIAL_ID = "svc_0123456789abcdef01234567"-def _ready_response(**connection_overrides: object) -> Response:++def _mint_response(**target_overrides: object) -> Response:return Response({- "enabled": True,- "status": {- "org": "org-1",- "state": "ready",- "trino_catalog_name": "org_catalog",- "connection": {- "host": "trino.postwh.com",- "port": 8443,- "username": "org_database",- **connection_overrides,- },+ "credential_id": CREDENTIAL_ID,+ "credential_secret": "example-secret",+ "expires_at": (datetime.now(UTC) + timedelta(minutes=15)).isoformat(),+ "connect": {"host": "warehouse.example.com", "port": 5432, "database": "ducklake", "sslmode": "require"},+ "trino_connect": {+ "host": "tenant.dw.us.postwh.com",+ "port": 443,+ "catalog": "org_example",+ "username": CREDENTIAL_ID,+ "http_scheme": "https",+ **target_overrides,},- },- status=200,+ })-class TestResolveManagedWarehouseTrinoConnection:- def test_combines_the_control_plane_target_with_the_stored_trino_secret(self) -> None:- with (- mock.patch(- "products.managed_warehouse.backend.presentation.views._request",- return_value=_ready_response(),- ) as request,- mock.patch(- "products.managed_warehouse.backend.trino_connection.get_managed_warehouse_trino_password",- return_value="trino-secret",- ),- ):- connection = resolve_managed_warehouse_trino_connection("org-1")-- assert connection.host == "trino.postwh.com"- assert connection.port == 8443- assert connection.catalog == "org_catalog"- assert connection.username == "org_database"- assert connection.password == "trino-secret"- assert "trino-secret" not in repr(connection)- request.assert_called_once_with("GET", "org-1", "/trino", require_enabled=False)-- @pytest.mark.parametrize(- "response",- [- Response({"enabled": False}, status=200),- Response({"enabled": True, "status": {"org": "org-1", "state": "pending"}}, status=200),- Response(- {- "enabled": True,- "status": {- "state": "ready",- "trino_catalog_name": "catalog",- "connection": {"host": "trino.postwh.com", "port": 8443, "username": "org_database"},- },- },- status=200,- ),- Response(- {- "enabled": True,- "status": {- "org": "another-org",- "state": "ready",- "trino_catalog_name": "catalog",- "connection": {"host": "trino.postwh.com", "port": 8443, "username": "org_database"},- },- },- status=200,- ),- _ready_response(host=""),- _ready_response(port=0),- _ready_response(username=""),- ],- )- def test_rejects_an_unusable_or_cross_organization_target(self, response: Response) -> None:- with mock.patch("products.managed_warehouse.backend.presentation.views._request", return_value=response):- with pytest.raises(ManagedWarehouseTrinoConnectionUnavailable, match="ready managed Trino connection"):- resolve_managed_warehouse_trino_connection("org-1")-- def test_rejects_a_missing_stored_trino_secret(self) -> None:- with (- mock.patch(- "products.managed_warehouse.backend.presentation.views._request",- return_value=_ready_response(),- ),- mock.patch(- "products.managed_warehouse.backend.trino_connection.get_managed_warehouse_trino_password",- return_value="",- ),- ):- with pytest.raises(ManagedWarehouseTrinoConnectionUnavailable, match="stored managed warehouse credential"):- resolve_managed_warehouse_trino_connection("org-1")---def test_connect_managed_warehouse_trino_enforces_verified_https_and_closes() -> None:- driver_connection = mock.MagicMock()- authentication = mock.sentinel.authentication+def _http_response(request: requests.PreparedRequest, **payload: object) -> requests.Response:+ import json++ response = requests.Response()+ response.status_code = 200+ response.request = request+ response._content = json.dumps(payload).encode()+ response.headers["Content-Type"] = "application/json"+ return response+++def test_resolves_a_minted_credential_without_reading_stored_passwords() -> None:+ with mock.patch(+ "products.managed_warehouse.backend.presentation.views._request", return_value=_mint_response()+ ) as cp:+ connection = resolve_managed_warehouse_trino_connection("org-1")+ assert connection.username == CREDENTIAL_ID+ assert connection.password == "example-secret"+ assert connection.catalog == "org_example"+ assert "example-secret" not in repr(connection)+ assert cp.call_args.args == ("POST", "org-1", "/service-credentials")+++ "change",+ [+ {"trino_connect": None},+ {"expires_at": "2000-01-01T00:00:00Z"},+ {"expires_at": "2000-01-01T00:00:00"},+ {"credential_id": "root"},+ {"credential_secret": ""},+ ],+)+def test_rejects_unusable_service_credentials(change: dict[str, object]) -> None:+ response = _mint_response()+ response.data.update(change)+ with mock.patch("products.managed_warehouse.backend.presentation.views._request", return_value=response):+ with pytest.raises(ManagedWarehouseTrinoConnectionUnavailable):+ resolve_managed_warehouse_trino_connection("org-1")+++ "target",+ [+ {"host": ""},+ {"port": 0},+ {"port": True},+ {"port": 65536},+ {"catalog": ""},+ {"username": "root"},+ {"http_scheme": "http"},+ ],+)+def test_rejects_invalid_trino_targets(target: dict[str, object]) -> None:+ with mock.patch(+ "products.managed_warehouse.backend.presentation.views._request", return_value=_mint_response(**target)+ ):+ with pytest.raises(ManagedWarehouseTrinoConnectionUnavailable):+ resolve_managed_warehouse_trino_connection("org-1")++[email protected]("renewal_target", ["included", "omitted", "null"])+def test_polling_renews_the_grant_and_preserves_cancellation_ownership(renewal_target: str) -> None:+ minted = _mint_response()+ refreshed = _mint_response()+ refreshed.data.pop("credential_secret")+ refreshed.data["secret_rotated"] = False+ if renewal_target == "omitted":+ refreshed.data.pop("trino_connect")+ elif renewal_target == "null":+ refreshed.data["trino_connect"] = None+ refreshed.data["expires_at"] = (datetime.now(UTC) + timedelta(minutes=29)).isoformat()+ issued_at = datetime.now(UTC)+ sent: list[requests.PreparedRequest] = []++ def send(request: requests.PreparedRequest, **kwargs: object) -> requests.Response:+ sent.append(request)+ if request.method == "POST":+ return _http_response(+ request,+ id="query-1",+ infoUri="https://tenant.dw.us.postwh.com/query-1",+ nextUri="https://tenant.dw.us.postwh.com/v1/statement/query-1",+ stats={},+ )+ if request.method == "GET":+ return _http_response(+ request,+ id="query-1",+ infoUri="https://tenant.dw.us.postwh.com/query-1",+ nextUri="https://tenant.dw.us.postwh.com/v1/statement/query-1",+ columns=[{"name": "value", "type": "bigint", "typeSignature": {"rawType": "bigint", "arguments": []}}],+ data=[[1]],+ stats={},+ )+ response = _http_response(request)+ response.status_code = 204+ return responsewith (mock.patch(- "products.managed_warehouse.backend.trino_connection.resolve_managed_warehouse_trino_connection",- return_value=mock.Mock(- host="trino.postwh.com",- port=8443,- catalog="org_catalog",- username="org_database",- password="root-secret",- ),- ),- mock.patch("trino.auth.BasicAuthentication", return_value=authentication) as basic_authentication,- mock.patch("trino.dbapi.connect", return_value=driver_connection) as connect,+ "products.managed_warehouse.backend.presentation.views._request", side_effect=[minted, refreshed]+ ) as cp,+ mock.patch("products.managed_warehouse.backend.trino_connection._utcnow", return_value=issued_at) as now,+ mock.patch("requests.adapters.HTTPAdapter.send", side_effect=send),):with connect_managed_warehouse_trino("org-1") as connection:- assert connection is driver_connection-- basic_authentication.assert_called_once_with("org_database", "root-secret")- connect.assert_called_once_with(- host="trino.postwh.com",- port=8443,- user="org_database",- catalog="org_catalog",- http_scheme="https",- auth=authentication,- request_timeout=60,- verify=True,- http_session=mock.ANY,+ cursor = connection.cursor()+ cursor.execute("SELECT 1")+ now.return_value = issued_at + timedelta(minutes=14)+ cursor.cancel()+ assert cp.call_count == 2+ assert cp.call_args.args == ("POST", "org-1", "/service-credentials/refresh")+ assert cp.call_args.kwargs["json_body"]["credential_id"] == CREDENTIAL_ID+ assert cp.call_args.kwargs["json_body"]["rotate_secret"] is False+ assert [r.method for r in sent] == ["POST", "GET", "DELETE"]+ assert (+ sent[-1].headers["Authorization"]+ == "Basic " + base64.b64encode(f"{CREDENTIAL_ID}:example-secret".encode()).decode())- driver_connection.close.assert_called_once_with()+ assert all(r.headers["X-Trino-User"] == CREDENTIAL_ID for r in sent)+++ "refresh_response",+ ["unavailable", "target_changed", "identity_changed", "old_control_plane", "rotated", "expired", "naive_expiry"],+)+def test_failed_refresh_does_not_send_a_request(refresh_response: str) -> None:+ minted = _mint_response()+ issued_at = datetime.now(UTC)+ response = _mint_response()+ response.data.pop("credential_secret")+ response.data["secret_rotated"] = False+ response.data["expires_at"] = (datetime.now(UTC) + timedelta(minutes=29)).isoformat()+ if refresh_response == "unavailable":+ response = Response({"error": "unavailable"}, status=503)+ elif refresh_response == "target_changed":+ response.data["trino_connect"]["host"] = "other.example.com"+ elif refresh_response == "old_control_plane":+ response.data.pop("secret_rotated")+ response.data["credential_secret"] = "unexpected-rotated-secret"+ elif refresh_response == "rotated":+ response.data["credential_secret"] = "unexpected-rotated-secret"+ elif refresh_response in {"expired", "naive_expiry"}:+ response.data.pop("trino_connect")+ response.data["expires_at"] = "2000-01-01T00:00:00Z" if refresh_response == "expired" else "2099-01-01T00:00:00"+ else:+ response.data["credential_id"] = "svc_111111111111111111111111"+ response.data["trino_connect"]["username"] = response.data["credential_id"]+ with (+ mock.patch("products.managed_warehouse.backend.presentation.views._request", side_effect=[minted, response]),+ mock.patch("products.managed_warehouse.backend.trino_connection._utcnow", return_value=issued_at) as now,+ mock.patch("requests.adapters.HTTPAdapter.send") as send,+ ):+ with connect_managed_warehouse_trino("org-1") as connection:+ now.return_value = issued_at + timedelta(minutes=14)+ with pytest.raises(ManagedWarehouseTrinoConnectionUnavailable):+ connection.cursor().execute("SELECT 1")+ send.assert_not_called()@pytest.mark.parametrize("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),+ ("tenant.dw.us.postwh.com", 443, True),+ ("TENANT.DW.DEV.POSTWH.COM.", 443, True),+ ("tenant.dw.us.postwh.com", 8443, False),("trino.example.com", 443, False),+ ("nested.tenant.dw.us.postwh.com", 443, False),+ ("dw.us.postwh.com", 443, False),+ ("tenant.dw.us.postwh.com.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"+def test_connection_keeps_verified_tls_and_scoped_proxy_bypass(host: str, port: int, bypass_proxy: bool) -> None:+ proxy = "http://proxy.example.com:4750"with (- mock.patch.dict(os.environ, {"HTTPS_PROXY": proxy_url, "NO_PROXY": ""}, clear=True),+ mock.patch.dict(os.environ, {"HTTPS_PROXY": proxy, "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_managed_warehouse_trino_password",- return_value="root-secret",+ return_value=_mint_response(host=host, port=port),),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")+ assert send.call_args.kwargs["verify"] is True+ assert send.call_args.kwargs["timeout"] == 60+ assert send.call_args.kwargs["proxies"].get("https") == (None if bypass_proxy else proxy)++[email protected]("response_kind", ["foreign_next_uri", "redirect"])+def test_service_secret_is_never_sent_to_a_redirect_or_foreign_poll_target(response_kind: str) -> None:+ sent: list[requests.PreparedRequest] = []++ def send(request: requests.PreparedRequest, **kwargs: object) -> requests.Response:+ sent.append(request)+ response = _http_response(+ request,+ id="query-1",+ infoUri="https://tenant.dw.us.postwh.com/query-1",+ nextUri="https://other.example.com/v1/statement/query-1",+ stats={},+ )+ if response_kind == "redirect":+ response.status_code = 307+ response.headers["Location"] = "https://other.example.com/v1/statement"+ return response++ with (+ mock.patch("products.managed_warehouse.backend.presentation.views._request", return_value=_mint_response()),+ mock.patch("requests.adapters.HTTPAdapter.send", side_effect=send),+ ):+ with connect_managed_warehouse_trino("org-1") as connection:+ with pytest.raises(ManagedWarehouseTrinoConnectionUnavailable):+ connection.cursor().execute("SELECT 1")+ assert len(sent) == 1+ assert sent[0].url == "https://tenant.dw.us.postwh.com:443/v1/statement"++[email protected]("verify", [True, "example-ca.pem"])+def test_a_prepared_request_renews_expiry_at_send_time(verify: bool | str) -> None:+ from products.managed_warehouse.backend.trino_connection import _TrinoServiceSession- 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+ minted = _mint_response()+ refreshed = _mint_response()+ issued_at = datetime.now(UTC)+ refreshed.data.pop("credential_secret")+ refreshed.data["secret_rotated"] = False+ refreshed.data["expires_at"] = (issued_at + timedelta(minutes=29)).isoformat()+ with (+ mock.patch.dict(os.environ, {"HTTPS_PROXY": "http://proxy.example.com:4750", "NO_PROXY": ""}, clear=True),+ mock.patch(+ "products.managed_warehouse.backend.presentation.views._request", side_effect=[minted, refreshed]+ ) as cp,+ mock.patch("products.managed_warehouse.backend.trino_connection._utcnow", return_value=issued_at) as now,+ mock.patch(+ "requests.adapters.HTTPAdapter.send", side_effect=lambda request, **kwargs: _http_response(request)+ ) as send,+ ):+ config = resolve_managed_warehouse_trino_connection("org-1")+ with _TrinoServiceSession("org-1", config) as session:+ session.verify = verify+ session.cert = ("client.crt", "client.key")+ session.stream = True+ prepared = session.prepare_request(+ requests.Request("GET", "https://tenant.dw.us.postwh.com/v1/statement/query-1")+ )+ now.return_value = issued_at + timedelta(minutes=14)+ session.send(prepared)+ session.send(prepared)+ assert send.call_args.kwargs["verify"] == verify+ assert send.call_args.kwargs["cert"] == ("client.crt", "client.key")+ assert send.call_args.kwargs["stream"] is True+ assert send.call_args.kwargs["proxies"]["https"] == "http://proxy.example.com:4750"+ assert cp.call_count == 2+ assert (+ prepared.headers["Authorization"]+ == "Basic " + base64.b64encode(f"{CREDENTIAL_ID}:example-secret".encode()).decode()+ )+++def test_cancellation_does_not_wait_for_a_blocked_poll() -> None:+ from products.managed_warehouse.backend.trino_connection import _TrinoServiceSession++ poll_started, release_poll = Event(), Event()+ minted, refreshed = _mint_response(), _mint_response()+ issued_at = datetime.now(UTC)+ refreshed.data.pop("credential_secret")+ refreshed.data["secret_rotated"] = False+ refreshed.data["expires_at"] = (issued_at + timedelta(minutes=29)).isoformat()++ def send(request: requests.PreparedRequest, **kwargs: object) -> requests.Response:+ if request.method == "GET":+ poll_started.set()+ assert release_poll.wait(10)+ return _http_response(request)++ with (+ mock.patch(+ "products.managed_warehouse.backend.presentation.views._request", side_effect=[minted, refreshed]+ ) as cp,+ mock.patch("products.managed_warehouse.backend.trino_connection._utcnow", return_value=issued_at) as now,+ mock.patch("requests.adapters.HTTPAdapter.send", side_effect=send),+ ):+ config = resolve_managed_warehouse_trino_connection("org-1")+ with _TrinoServiceSession("org-1", config) as session, ThreadPoolExecutor(max_workers=2) as executor:+ now.return_value = issued_at + timedelta(minutes=14)+ poll = executor.submit(session.get, "https://tenant.dw.us.postwh.com/v1/statement/query-1")+ try:+ assert poll_started.wait(5)+ cancel = executor.submit(session.delete, "https://tenant.dw.us.postwh.com/v1/statement/query-1")+ assert cancel.result(timeout=5).status_code == 200+ assert not poll.done()+ finally:+ release_poll.set()+ assert poll.result(timeout=5).status_code == 200+ assert cp.call_count == 2diff --git a/products/managed_warehouse/backend/tests/test_trino_materialization.py b/products/managed_warehouse/backend/tests/test_trino_materialization.pyindex d4eb9d459ca7..9c0dab04d7b5 100644--- a/products/managed_warehouse/backend/tests/test_trino_materialization.py+++ b/products/managed_warehouse/backend/tests/test_trino_materialization.py@@ -79,7 +79,10 @@ class TestTrinoShadowMaterialization(BaseTest):assert result.schema_name == f"posthog_data_modeling_team_{self.team.pk}"assert result.table_name == f"model_{self.saved_query_id.hex}"- connect.assert_called_once_with(str(self.organization.pk))+ connect.assert_called_once_with(+ str(self.organization.pk),+ principal=f"posthog:trino-materialization:team:{self.team.pk}:view:{self.saved_query_id}",+ )assert self.cursor.execute.call_args_list[0].args == (f'CREATE SCHEMA IF NOT EXISTS "org_""catalog"."posthog_data_modeling_team_{self.team.pk}"',)diff --git a/products/managed_warehouse/backend/tests/test_trino_model_aliases.py b/products/managed_warehouse/backend/tests/test_trino_model_aliases.pyindex 1c2651710ede..312fd7946e10 100644--- a/products/managed_warehouse/backend/tests/test_trino_model_aliases.py+++ b/products/managed_warehouse/backend/tests/test_trino_model_aliases.py@@ -144,7 +144,9 @@ class TestModelAliasScoping(BaseTest):patch("posthog.ph_client.feature_enabled_or_false", return_value=True),):reconcile_trino_model_aliases(self.team.pk, lambda: None)- connect.assert_called_once_with(str(self.organization.id))+ connect.assert_called_once_with(+ str(self.organization.id), principal=f"posthog:trino-model-aliases:team:{self.team.pk}"+ )publish.assert_called_once_with([alias("reporting.orders")], None)connect.return_value.__enter__.return_value.cursor.return_value.execute.assert_not_called()diff --git a/products/managed_warehouse/backend/trino_connection.py b/products/managed_warehouse/backend/trino_connection.pyindex ed15a808f579..e7ac8d6bf1ce 100644--- a/products/managed_warehouse/backend/trino_connection.py+++ b/products/managed_warehouse/backend/trino_connection.py@@ -1,59 +1,185 @@from __future__ import annotations-from collections.abc import Iterator+import re+from collections.abc import Iterator, MutableMappingfrom contextlib import contextmanager+from dataclasses import replace+from datetime import UTC, datetime, timedelta+from threading import Lockfrom typing import TYPE_CHECKING+from urllib.parse import urlsplitimport requests+from requests.auth import HTTPBasicAuth+from requests.utils import resolve_proxies-from products.managed_warehouse.backend.facade.api import get_managed_warehouse_trino_passwordfrom products.managed_warehouse.backend.facade.contracts import (ManagedWarehouseTrinoConnection,ManagedWarehouseTrinoConnectionUnavailable,+ ServiceCredential,+ ServiceCredentialTrinoConnect,+ ServiceCredentialUnavailable,)-from products.managed_warehouse.backend.trino_target import get_ready_trino_connection_target-from products.warehouse_sources.backend.facade import source_management+from products.managed_warehouse.backend.service_credentials import mint_service_credential, renew_service_credentialif TYPE_CHECKING:from trino.dbapi import Connection+_CREDENTIAL_REFRESH_MARGIN = timedelta(minutes=2)+_CREDENTIAL_REQUEST_TIMEOUT_SECONDS = 10-def resolve_managed_warehouse_trino_connection(organization_id: str) -> ManagedWarehouseTrinoConnection:- target = get_ready_trino_connection_target(organization_id)- if target is None:- raise ManagedWarehouseTrinoConnectionUnavailable(- "The organization does not have a ready managed Trino connection"- )- try:- password = get_managed_warehouse_trino_password(organization_id)- except ValueError as error:- raise ManagedWarehouseTrinoConnectionUnavailable(- "The organization does not have a stored managed warehouse credential"- ) from error- if not password:+def _utcnow() -> datetime:+ return datetime.now(UTC)+++def _is_hosted_service_target(host: str) -> bool:+ # Tenant endpoints are trusted only when issued by the control plane, never from external-source configuration.+ label, _, domain = host.lower().removesuffix(".").partition(".")+ return (+ domain in {"dw.us.postwh.com", "dw.dev.postwh.com"}+ and re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", label) is not None+ )+++def _connection_from_credential(credential: ServiceCredential) -> ManagedWarehouseTrinoConnection:+ target = credential.trino_connect+ if (+ target is None+ or not re.fullmatch(r"svc_[0-9a-f]{24}", credential.credential_id)+ or not credential.credential_secret+ or credential.expires_at.tzinfo is None+ or credential.expires_at <= _utcnow() + _CREDENTIAL_REFRESH_MARGIN+ or not (target.username == credential.credential_id or target.username.endswith("." + credential.credential_id))+ ):raise ManagedWarehouseTrinoConnectionUnavailable(- "The organization does not have a stored managed warehouse credential"+ "The control plane did not return a usable Trino service credential. Check Trino service authentication readiness.")-return ManagedWarehouseTrinoConnection(host=target.host,port=target.port,catalog=target.catalog,username=target.username,- password=password,+ password=credential.credential_secret,+ credential_id=credential.credential_id,+ expires_at=credential.expires_at,)+def resolve_managed_warehouse_trino_connection(+ organization_id: str, *, principal: str = "posthog:trino"+) -> ManagedWarehouseTrinoConnection:+ try:+ credential = mint_service_credential(+ organization_id,+ principal=principal,+ timeout_seconds=_CREDENTIAL_REQUEST_TIMEOUT_SECONDS,+ )+ return _connection_from_credential(credential)+ except ServiceCredentialUnavailable as error:+ raise ManagedWarehouseTrinoConnectionUnavailable("Could not mint a Trino service credential") from error+++class _TrinoServiceSession(requests.Session):+ def __init__(self, organization_id: str, connection: ManagedWarehouseTrinoConnection) -> None:+ super().__init__()+ self._organization_id = organization_id+ self._connection = connection+ self._lock = Lock()+ # Defer authentication until send so queued requests also check credential expiry.+ self.auth = self._defer_authentication++ @staticmethod+ def _defer_authentication(request: requests.PreparedRequest) -> requests.PreparedRequest:+ return request++ def send(+ self,+ request: requests.PreparedRequest,+ *,+ stream: bool | None = None,+ verify: bool | str | None = None,+ proxies: MutableMapping[str, str] | None = None,+ cert: str | tuple[str, str] | None = None,+ timeout: float | tuple[float, float] | tuple[float, None] | None = None,+ allow_redirects: bool = True,+ **kwargs: object,+ ) -> requests.Response:+ if kwargs:+ raise TypeError("Unsupported Trino HTTP transport options")+ # Serialize renewal so polling and cancellation share one grant expiry.+ with self._lock:+ connection = self._connection+ destination = urlsplit(request.url or "")+ if (+ destination.scheme != "https"+ or (destination.hostname or "").lower().removesuffix(".") != connection.host.lower().removesuffix(".")+ or (destination.port or 443) != connection.port+ or destination.username is not None+ or destination.password is not None+ ):+ raise ManagedWarehouseTrinoConnectionUnavailable(+ "Trino returned a different service credential destination"+ )+ if connection.expires_at <= _utcnow() + _CREDENTIAL_REFRESH_MARGIN:+ try:+ credential = renew_service_credential(+ self._organization_id,+ connection.credential_id,+ credential_secret=connection.password,+ timeout_seconds=_CREDENTIAL_REQUEST_TIMEOUT_SECONDS,+ )+ if credential.trino_connect is None:+ # Readiness can hide dial targets during renewal without invalidating an existing query's grant.+ credential = replace(+ credential,+ trino_connect=ServiceCredentialTrinoConnect(+ host=connection.host,+ port=connection.port,+ catalog=connection.catalog,+ username=connection.username,+ http_scheme="https",+ ),+ )+ refreshed = _connection_from_credential(credential)+ except ServiceCredentialUnavailable as error:+ raise ManagedWarehouseTrinoConnectionUnavailable(+ "Could not renew the Trino service credential"+ ) from error+ if (+ refreshed.credential_id != connection.credential_id+ or refreshed.host != connection.host+ or refreshed.port != connection.port+ or refreshed.catalog != connection.catalog+ or refreshed.username != connection.username+ ):+ raise ManagedWarehouseTrinoConnectionUnavailable(+ "Trino service credential target changed during the query"+ )+ connection = self._connection = refreshed+ HTTPBasicAuth(connection.username, connection.password)(request)+ response = super().send(+ request,+ stream=self.stream if stream is None else stream,+ verify=self.verify if verify is None else verify,+ proxies=resolve_proxies(request, self.proxies, self.trust_env) if proxies is None else proxies,+ cert=self.cert if cert is None else cert,+ timeout=timeout,+ allow_redirects=False,+ )+ if 300 <= response.status_code < 400:+ response.close()+ raise ManagedWarehouseTrinoConnectionUnavailable("Trino redirected a service-authenticated request")+ return response++@contextmanager-def connect_managed_warehouse_trino(organization_id: str) -> Iterator[Connection]:- from trino.auth import BasicAuthentication # noqa: PLC0415 -- keeps the optional driver off startup paths+def connect_managed_warehouse_trino(organization_id: str, *, principal: str = "posthog:trino") -> Iterator[Connection]:from trino.dbapi import connect # noqa: PLC0415 -- keeps the optional driver off startup paths- config = resolve_managed_warehouse_trino_connection(organization_id)- 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:+ config = resolve_managed_warehouse_trino_connection(organization_id, principal=principal)+ with _TrinoServiceSession(organization_id, config) as http_session:+ if _is_hosted_service_target(config.host) and config.port == 443:http_session.trust_env = Falseconnection = connect(host=config.host,@@ -61,7 +187,6 @@ def connect_managed_warehouse_trino(organization_id: str) -> Iterator[Connectionuser=config.username,catalog=config.catalog,http_scheme="https",- auth=BasicAuthentication(config.username, config.password),request_timeout=60,verify=True,http_session=http_session,diff --git a/products/managed_warehouse/backend/trino_materialization.py b/products/managed_warehouse/backend/trino_materialization.pyindex aacc7c04d205..2997143c41ea 100644--- a/products/managed_warehouse/backend/trino_materialization.py+++ b/products/managed_warehouse/backend/trino_materialization.py@@ -37,7 +37,9 @@ def execute_trino_shadow_materialization(schema_name = ducklake_data_modeling_schema(team_id)query_id = UUID(str(saved_query_id))table_name = get_data_modeling_table_names(team_id, [query_id])[query_id]- with connect_managed_warehouse_trino(organization_id) as connection:+ with connect_managed_warehouse_trino(+ organization_id, principal=f"posthog:trino-materialization:team:{team_id}:view:{saved_query_id}"+ ) as connection:schema = f"{escape_trino_identifier(connection.catalog)}.{escape_trino_identifier(schema_name)}"table = f"{schema}.{escape_trino_identifier(table_name)}"cursor = connection.cursor()diff --git a/products/managed_warehouse/backend/trino_model_aliases.py b/products/managed_warehouse/backend/trino_model_aliases.pyindex 5efa0427f1e7..3b27f6c52588 100644--- a/products/managed_warehouse/backend/trino_model_aliases.py+++ b/products/managed_warehouse/backend/trino_model_aliases.py@@ -226,7 +226,9 @@ def reconcile_trino_model_aliases(if not enabled:return ModelAliasReconciliation(active=False)models = _load_models(team_id, saved_query_ids)- with connect_managed_warehouse_trino(str(organization_id)) as connection:+ with connect_managed_warehouse_trino(+ str(organization_id), principal=f"posthog:trino-model-aliases:team:{team_id}"+ ) as connection:cursor = connection.cursor()if control:control.attach(cursor)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 471043e75eea..ca3ba6ca465f 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@@ -88,6 +88,10 @@ def test_connect_trino_uses_tracked_session_and_closes_resources() -> None:("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),