: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): consume CP connect block for service-credential connections (#81655)
Benjamin Knofe-Viderfb576897097b
diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.pyindex 022217acd127..7bcfc9e20b36 100644--- a/posthog/dags/test_events_backfill_to_duckling.py+++ b/posthog/dags/test_events_backfill_to_duckling.py@@ -67,6 +67,7 @@ from products.managed_warehouse.backend.facade.client import ServiceCredential,from products.managed_warehouse.backend.facade.contracts import (ManagedWarehouseTableNames,ManagedWarehouseTeamMembership,+ ServiceCredentialConnect,)@@ -1574,6 +1575,12 @@ class TestDuckgresSessionServiceCredential:# ahead). Deterministic under any wall clock._STALE_EXPIRY = datetime(2020, 1, 1, tzinfo=UTC)_FRESH_EXPIRY = datetime(2040, 1, 1, tzinfo=UTC)+ _CONNECT = ServiceCredentialConnect(+ host="019740a8-ac01-0000-cad1-4626cafbc273.dw.us.postwh.com",+ port=443,+ database="ducklake",+ sslmode="require",+ )def _credential(self, password: str, *, rotated: bool = True, expires_at: datetime | None = None):return ServiceCredential(@@ -1581,6 +1588,7 @@ class TestDuckgresSessionServiceCredential:password=password,expires_at=expires_at or self._FRESH_EXPIRY,rotated=rotated,+ connect=self._CONNECT,)@patch("posthog.dags.events_backfill_to_duckling.mint_service_credential")diff --git a/products/managed_warehouse/backend/client.py b/products/managed_warehouse/backend/client.pyindex ea7d69170d48..24b6597bb8e6 100644--- a/products/managed_warehouse/backend/client.py+++ b/products/managed_warehouse/backend/client.py@@ -40,9 +40,12 @@ def make_duckgres_conninfo(scoped to exactly the team's warehouse schemas). This is what backgroundjobs (dagster) should present; see``products/managed_warehouse/backend/service_credentials.py``.- ``organization_id`` must be provided in that mode — service credentials- are only mintable for a provisioned production warehouse, so dev-mode is- rejected loudly rather than silently downgraded to root.+ Host/port/database/sslmode come ENTIRELY from the credential's+ CP-issued ``connect`` block — this branch never reads the stored+ ``DuckgresServer`` row (the row is being deleted as a host store).+ Service credentials are only mintable for a provisioned production+ warehouse, so dev-mode is rejected loudly rather than silently+ downgraded to root."""from products.managed_warehouse.backend.common import _duckgres_dev_config, _get_org_id_for_team@@ -64,14 +67,14 @@ def make_duckgres_conninfo(f"canonical login {expected_username!r} for team {team_id}: the credential belongs ""to a different team/org than the connection being built")- config = get_duckgres_config_for_org(organization_id or _get_org_id_for_team(team_id))+ connect = service_credential.connectreturn make_conninfo(- host=config["DUCKGRES_HOST"],- port=int(config["DUCKGRES_PORT"]),- dbname=config["DUCKGRES_DATABASE"],+ host=connect.host,+ port=connect.port,+ dbname=connect.database,user=service_credential.username,password=service_credential.password,- sslmode="require",+ sslmode=connect.sslmode,sslcert="/tmp/no.txt",sslkey="/tmp/no.txt",sslrootcert="/tmp/no.txt",diff --git a/products/managed_warehouse/backend/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.pyindex 53c763e486ab..242548394ec0 100644--- a/products/managed_warehouse/backend/facade/contracts.py+++ b/products/managed_warehouse/backend/facade/contracts.py@@ -18,6 +18,8 @@ from enum import StrEnumfrom typing import Anyfrom uuid import UUID+from posthog.dataclasses import frozen+__all__ = ["CPUnavailableError","DuckgresQueryServerConfig",@@ -35,6 +37,7 @@ __all__ = ["ManagedWarehouseTableNames","ManagedWarehouseTeamMembership","ServiceCredential",+ "ServiceCredentialConnect","ServiceCredentialUnavailable",]@@ -43,6 +46,24 @@ class CPUnavailableError(RuntimeError):pass+@frozen+class ServiceCredentialConnect:+ """Where to dial for a minted service credential, returned by the CP on+ every successful mint (see duckgres/CLAUDE.md "Service Credentials").++ The host is the TLS-pinned per-org ingress (``<org-id>.dw.us.postwh.com``);+ the caller's network resolves it (AWS PrivateLink for dagster) — duckgres+ is never in the resolution path. Carrying these on the credential is what+ lets service-credential connections stop reading host/port/database from+ the stored ``DuckgresServer`` row.+ """++ host: str+ port: int+ database: str+ sslmode: str++@dataclass(frozen=True)class ServiceCredential:"""A team-scoped credential minted by the duckgres control plane, for one@@ -52,6 +73,10 @@ class ServiceCredential:``password`` is empty when the CP REUSED a still-valid grant (`rotated`is False): callers that already hold the credential keep using it;callers that don't must re-mint with ``force_rotate=True``.++ ``connect`` carries the CP-issued dial target for the credential and is+ REQUIRED on every successful mint — a mint response without it is an+ older CP than the contract and must be rejected at mint time."""username: str@@ -60,6 +85,7 @@ class ServiceCredential:password: str = field(repr=False)expires_at: datetimerotated: bool+ connect: ServiceCredentialConnectclass ServiceCredentialUnavailable(RuntimeError):diff --git a/products/managed_warehouse/backend/service_credentials.py b/products/managed_warehouse/backend/service_credentials.pyindex 2eb0a3c80ece..39b0606761aa 100644--- a/products/managed_warehouse/backend/service_credentials.py+++ b/products/managed_warehouse/backend/service_credentials.py@@ -20,6 +20,11 @@ wording):First call of a run must pass it.- Established connections are never killed on expiry (handshake-onlysemantics, RDS-IAM style); only NEW connections need a live credential.+- Every successful mint carries a ``connect`` block (host, port, database,+ sslmode) — the dial target for the credential. Service-credential+ connections are built ENTIRELY from it, never from the stored+ ``DuckgresServer`` row; a mint response without it is an older CP than the+ contract and is rejected as unavailable.Keep this module's request/response shapes byte-compatible with``controlplane/provisioning/service_credential.go``.@@ -33,13 +38,18 @@ from typing import Anyimport structlogfrom rest_framework import status-from products.managed_warehouse.backend.facade.contracts import ServiceCredential, ServiceCredentialUnavailable+from products.managed_warehouse.backend.facade.contracts import (+ ServiceCredential,+ ServiceCredentialConnect,+ ServiceCredentialUnavailable,+)__all__ = ["DEFAULT_CREDENTIAL_TTL_SECONDS","MAX_CREDENTIAL_TTL_SECONDS","MIN_CREDENTIAL_TTL_SECONDS","ServiceCredential",+ "ServiceCredentialConnect","ServiceCredentialUnavailable","mint_service_credential",]@@ -125,11 +135,13 @@ def mint_service_credential(expires_at = datetime.fromisoformat(str(expires_raw).replace("Z", "+00:00"))except (ValueError, TypeError) as exc:raise ServiceCredentialUnavailable(f"mint returned unparseable expires_at {expires_raw!r}") from exc+ connect = _parse_connect(data)credential = ServiceCredential(username=str(username),password=str(data.get("password") or ""),expires_at=expires_at,rotated=bool(data.get("password")),+ connect=connect,)logger.info("duckgres_service_credential_minted",@@ -138,5 +150,36 @@ def mint_service_credential(principal=principal,rotated=credential.rotated,expires_at=expires_at.isoformat(),+ connect_host=connect.host,+ connect_port=connect.port,)return credential+++def _parse_connect(data: dict[str, Any]) -> ServiceCredentialConnect:+ """Parse the mandatory ``connect`` block from a successful mint response.++ STRICT: every successful mint must carry ``connect`` with all four fields+ (host, port, database, sslmode) — the CP contract since the connect-bundle+ change. A 2xx without it means the CP is older than the contract; the+ service-credential conninfo builder no longer reads the ``DuckgresServer``+ row, so there is nothing to fall back to here and we raise+ ``ServiceCredentialUnavailable`` (the caller's broad fallback to root+ engages — the established transitional degradation).+ """+ raw = data.get("connect")+ if not isinstance(raw, dict):+ # Redact, as everywhere else in this module: the malformed payload can+ # still carry a live `password`, and the caller logs exception text.+ raise ServiceCredentialUnavailable(f"mint returned no connect block: {_redact_payload(data)!r}")+ host = raw.get("host")+ database = raw.get("database")+ sslmode = raw.get("sslmode")+ port_raw: Any = raw.get("port")+ try:+ port = int(port_raw)+ except (TypeError, ValueError):+ port = 0+ if not host or not database or not sslmode or port <= 0:+ raise ServiceCredentialUnavailable(f"mint returned incomplete connect block: {_redact_payload(data)!r}")+ return ServiceCredentialConnect(host=str(host), port=port, database=str(database), sslmode=str(sslmode))diff --git a/products/managed_warehouse/backend/tests/test_client_service_credentials.py b/products/managed_warehouse/backend/tests/test_client_service_credentials.pyindex ef57428cd1cd..9aa432faf71f 100644--- a/products/managed_warehouse/backend/tests/test_client_service_credentials.py+++ b/products/managed_warehouse/backend/tests/test_client_service_credentials.py@@ -4,60 +4,81 @@ import pytestfrom unittest import mockfrom products.managed_warehouse.backend.client import make_duckgres_conninfo+from products.managed_warehouse.backend.facade.contracts import ServiceCredentialConnectfrom products.managed_warehouse.backend.service_credentials import ServiceCredential+_CONNECT = ServiceCredentialConnect(+ host="019740a8-ac01-0000-cad1-4626cafbc273.dw.us.postwh.com",+ port=443,+ database="ducklake",+ sslmode="require",+)-def _credential(password: str = "minted-plaintext") -> ServiceCredential:++def _credential(password: str) -> ServiceCredential:return ServiceCredential(username="posthog_team_7_rw",password=password,expires_at=datetime(2026, 8, 11, 13, 0, tzinfo=UTC),rotated=bool(password),+ connect=_CONNECT,)class TestMakeDuckgresConninfoWithServiceCredential:"""client.make_duckgres_conninfo with a service_credential presents theteam's canonical project_user login (CP-issued, team-scoped), NOT the- org-root credential stored in the DuckgresServer row.+ org-root credential stored in the DuckgresServer row — and dials the+ CP-issued `connect` target, never the row's host/port/database."""+ @mock.patch(+ "products.managed_warehouse.backend.client.get_duckgres_config_for_org",+ side_effect=AssertionError("DuckgresServer row must not be consulted on the service-credential path"),+ )@mock.patch("products.managed_warehouse.backend.client.is_dev_mode", return_value=False)- @mock.patch("products.managed_warehouse.backend.client.get_duckgres_config_for_org")- def test_uses_service_credential_username_and_password(self, mock_config, _dev):- mock_config.return_value = {- "DUCKGRES_HOST": "wh.duckgres.local",- "DUCKGRES_PORT": "5432",- "DUCKGRES_DATABASE": "ducklake",- "DUCKGRES_USERNAME": "root",- "DUCKGRES_PASSWORD": "root-secret",- }-- conninfo = make_duckgres_conninfo(7, organization_id="org-1", service_credential=_credential())+ def test_uses_service_credential_and_connect_block(self, _dev, _config):+ conninfo = make_duckgres_conninfo(+ 7, organization_id="org-1", service_credential=_credential("minted-plaintext")+ )assert "user=posthog_team_7_rw" in conninfoassert "password=minted-plaintext" in conninfo- assert "root-secret" not in conninfo+ assert "host=019740a8-ac01-0000-cad1-4626cafbc273.dw.us.postwh.com" in conninfo+ assert "port=443" in conninfo+ assert "dbname=ducklake" in conninfoassert "sslmode=require" in conninfo+ @mock.patch(+ "products.managed_warehouse.backend.client.get_duckgres_config_for_org",+ side_effect=AssertionError("DuckgresServer row must not be consulted on the service-credential path"),+ )+ @mock.patch("products.managed_warehouse.backend.client.is_dev_mode", return_value=False)+ def test_sslmode_comes_from_connect_block(self, _dev, _config):+ connect = ServiceCredentialConnect(+ host="h.dw.us.postwh.com", port=443, database="ducklake", sslmode="verify-full"+ )+ credential = ServiceCredential(+ username="posthog_team_7_rw",+ password="minted-plaintext",+ expires_at=datetime(2026, 8, 11, 13, 0, tzinfo=UTC),+ rotated=True,+ connect=connect,+ )++ conninfo = make_duckgres_conninfo(7, organization_id="org-1", service_credential=credential)++ assert "sslmode=verify-full" in conninfo+@mock.patch("products.managed_warehouse.backend.client.is_dev_mode", return_value=False)- @mock.patch("products.managed_warehouse.backend.client.get_duckgres_config_for_org")- def test_empty_password_credential_is_rejected_loudly(self, mock_config, _dev):+ def test_empty_password_credential_is_rejected_loudly(self, _dev):# A reuse-path credential (CP returned no plaintext) must fail HERE —# a fresh fetcher with nothing cached needs to mint with force_rotate,# not connect with a blank password and get a cryptic 28P01.- mock_config.return_value = {- "DUCKGRES_HOST": "h",- "DUCKGRES_PORT": "5432",- "DUCKGRES_DATABASE": "ducklake",- "DUCKGRES_USERNAME": "root",- "DUCKGRES_PASSWORD": "root-secret",- }-with pytest.raises(RuntimeError, match="force_rotate"):- make_duckgres_conninfo(7, organization_id="org-1", service_credential=_credential(password=""))+ make_duckgres_conninfo(7, organization_id="org-1", service_credential=_credential(""))def test_dev_mode_rejects_service_credential_loudly(self):with mock.patch("products.managed_warehouse.backend.client.is_dev_mode", return_value=True):with pytest.raises(RuntimeError, match="dev mode"):- make_duckgres_conninfo(7, service_credential=_credential())+ make_duckgres_conninfo(7, service_credential=_credential("minted-plaintext"))diff --git a/products/managed_warehouse/backend/tests/test_service_credentials.py b/products/managed_warehouse/backend/tests/test_service_credentials.pyindex e67223d8f032..d06e74c397bd 100644--- a/products/managed_warehouse/backend/tests/test_service_credentials.py+++ b/products/managed_warehouse/backend/tests/test_service_credentials.py@@ -9,10 +9,18 @@ from products.managed_warehouse.backend.service_credentials import (DEFAULT_CREDENTIAL_TTL_SECONDS,MAX_CREDENTIAL_TTL_SECONDS,MIN_CREDENTIAL_TTL_SECONDS,+ ServiceCredentialConnect,ServiceCredentialUnavailable,mint_service_credential,)+_CONNECT = {+ "host": "org-1.dw.us.postwh.com",+ "port": 443,+ "database": "ducklake",+ "sslmode": "require",+}+def _ok_response(data: dict) -> mock.MagicMock:resp = mock.MagicMock()@@ -29,6 +37,7 @@ class TestMintServiceCredential:"username": "posthog_team_7_rw","password": "minted-plaintext","expires_at": "2026-08-11T13:00:00Z",+ "connect": _CONNECT,})@@ -40,6 +49,9 @@ class TestMintServiceCredential:assert credential.password == "minted-plaintext"assert credential.rotated is Trueassert credential.expires_at == datetime(2026, 8, 11, 13, 0, tzinfo=UTC)+ assert credential.connect == ServiceCredentialConnect(+ host="org-1.dw.us.postwh.com", port=443, database="ducklake", sslmode="require"+ )mock_request.assert_called_once_with("POST",@@ -61,6 +73,7 @@ class TestMintServiceCredential:"username": "posthog_team_7_rw","password": "p","expires_at": "2026-08-11T13:00:00Z",+ "connect": _CONNECT,})mint_service_credential("org-1", 7, principal="d", ttl_seconds=1, force_rotate=True)@@ -75,19 +88,22 @@ class TestMintServiceCredential:def test_reuse_path_reports_missing_password(self):# When the CP reuses a live grant it omits the password — the caller# sees credential.password == "" and rotated == False and must mint- # with force_rotate if it has nothing cached.+ # with force_rotate if it has nothing cached. The connect block is+ # present on reuse too (every successful mint carries it).with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:mock_request.return_value = _ok_response({"username": "posthog_team_7_rw",# no "password" key — what the CP actually returns on reuse"expires_at": "2026-08-11T13:00:00Z",+ "connect": _CONNECT,})credential = mint_service_credential("org-1", 7, principal="d")assert credential.password == ""assert credential.rotated is False+ assert credential.connect.host == "org-1.dw.us.postwh.com"def test_cp_error_raises_unavailable(self):with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:@@ -102,25 +118,79 @@ class TestMintServiceCredential:def test_missing_username_raises_unavailable(self):with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:- mock_request.return_value = _ok_response({"expires_at": "2026-08-11T13:00:00Z"})+ mock_request.return_value = _ok_response({"expires_at": "2026-08-11T13:00:00Z", "connect": _CONNECT})with pytest.raises(ServiceCredentialUnavailable):mint_service_credential("org-1", 7, principal="d", force_rotate=True)def test_bad_expires_at_raises_unavailable(self):with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:mock_request.return_value = _ok_response(- {"username": "u", "password": "p", "expires_at": "not-a-timestamp"}+ {"username": "u", "password": "p", "expires_at": "not-a-timestamp", "connect": _CONNECT})with pytest.raises(ServiceCredentialUnavailable):mint_service_credential("org-1", 7, principal="d", force_rotate=True)+ def test_missing_connect_raises_unavailable(self):+ # A 2xx without `connect` is an older CP than the contract. The+ # conninfo builder no longer reads the DuckgresServer row on the+ # service-credential path, so there is nothing to fall back to HERE —+ # raise unavailable; the caller's broad fallback to root engages (the+ # established transitional degradation).+ with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:+ mock_request.return_value = _ok_response(+ {"username": "u", "password": "p", "expires_at": "2026-08-11T13:00:00Z"}+ )+ with pytest.raises(ServiceCredentialUnavailable) as exc_info:+ mint_service_credential("org-1", 7, principal="d", force_rotate=True)+ assert "connect" in str(exc_info.value)++ @pytest.mark.parametrize(+ "connect",+ [+ {"port": 443, "database": "ducklake", "sslmode": "require"}, # no host+ {"host": "org-1.dw.us.postwh.com", "database": "ducklake", "sslmode": "require"}, # no port+ {"host": "org-1.dw.us.postwh.com", "port": "not-a-port", "database": "ducklake", "sslmode": "require"},+ {"host": "org-1.dw.us.postwh.com", "port": 443, "sslmode": "require"}, # no database+ {"host": "org-1.dw.us.postwh.com", "port": 443, "database": "ducklake"}, # no sslmode+ "not-a-dict",+ ],+ )+ def test_partial_connect_raises_unavailable(self, connect):+ with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:+ mock_request.return_value = _ok_response(+ {"username": "u", "password": "p", "expires_at": "2026-08-11T13:00:00Z", "connect": connect}+ )+ with pytest.raises(ServiceCredentialUnavailable) as exc_info:+ mint_service_credential("org-1", 7, principal="d", force_rotate=True)+ assert "connect" in str(exc_info.value)++ def test_malformed_connect_never_leaks_password_in_exception(self):+ # Same redaction guarantee as the other malformed-response paths: a+ # payload rejected for its connect block can still carry a live+ # `password`, and the backfill's broad fallback logs exception text.+ with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:+ mock_request.return_value = _ok_response(+ {"username": "u", "password": "live-grant-plaintext", "expires_at": "2026-08-11T13:00:00Z"}+ )+ with pytest.raises(ServiceCredentialUnavailable) as exc_info:+ mint_service_credential("org-1", 7, principal="d", force_rotate=True)++ message = str(exc_info.value)+ assert "live-grant-plaintext" not in message+ assert "<redacted>" in message+def test_malformed_response_never_leaks_password_in_exception(self):# The backfill's broad fallback logs the exception text — a malformed# CP payload that still carries a live `password` must not surface it# there (review follow-up on #81289).with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:mock_request.return_value = _ok_response(- {"username": "", "password": "live-grant-plaintext", "expires_at": "2026-08-11T13:00:00Z"}+ {+ "username": "",+ "password": "live-grant-plaintext",+ "expires_at": "2026-08-11T13:00:00Z",+ "connect": _CONNECT,+ })with pytest.raises(ServiceCredentialUnavailable) as exc_info:mint_service_credential("org-1", 7, principal="d", force_rotate=True)