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.

feat(managed-warehouse): dagster backfill mints team-scoped service credentials (#81289)

Benjamin Knofe-Viderf081154b701a
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.py
index 369635c9f83d..5e9a026942e1 100644
--- a/posthog/dags/events_backfill_to_duckling.py
+++ b/posthog/dags/events_backfill_to_duckling.py
@@ -40,7 +40,7 @@ import dataclasses
from collections.abc import Callable
from contextlib import closing
from dataclasses import replace
-from datetime import date, datetime, timedelta
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Literal
from django.db import DatabaseError
@@ -92,7 +92,12 @@ from products.managed_warehouse.backend.facade.api import (
get_stored_bucket_config,
resolve_team_earliest_event_date,
)
-from products.managed_warehouse.backend.facade.client import make_duckgres_conninfo
+from products.managed_warehouse.backend.facade.client import (
+ ServiceCredential,
+ ServiceCredentialUnavailable,
+ make_duckgres_conninfo,
+ mint_service_credential,
+)
from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseTeamMembership
from products.managed_warehouse.backend.facade.metrics import record_duckling_backfill_workload, track_duckling_backfill
from products.managed_warehouse.backend.facade.team_state import (
@@ -300,6 +305,75 @@ def _resolve_duckling_target(team_id: int) -> DucklingTarget:
)
+def _mint_backfill_service_credential(target: DucklingTarget) -> ServiceCredential | None:
+ """Mint one team-scoped service credential for this session, or None to fall back.
+
+ Mint ORDER matters more than mint success: two backfill ops for the SAME
+ team routinely run concurrently (two partitions, or a daily + a full
+ backfill), and the CP's rotation is a shared, handshake-invalidating
+ operation on the team's login. Always force-rotating here would make
+ every session clobber every other in-flight session's credential — the
+ first worker drop thereafter fails that whole partition for good. So the
+ mint is reuse-FIRST: ask for the live grant with no rotation, and only
+ escalate to force_rotate when the CP has no usable credential to hand
+ back (fresh team, grant lapsed, or an admin rotation in-between — all
+ cases where CP returns no plaintext on the reuse path). Per the CP
+ contract (duckgres/CLAUDE.md "Service Credentials") a rotation inside the
+ TTL window is reserved for exactly that "nothing usable exists" case.
+
+ Fallback to org-root (None) is deliberate and transitional: a CP that is
+ unreachable, an org whose team row hasn't been created yet, or dev-mode
+ env-var duckgres all degrade to the legacy root credential so the backfill
+ keeps working while the service-credential path rolls out. Log loudly on
+ every fallback — this is exactly the drift we want visible during the
+ transition (the end state is root-access removed from Django entirely).
+ """
+ try:
+ credential = mint_service_credential(
+ target.organization_id,
+ target.team_id,
+ principal="dagster:events-backfill",
+ force_rotate=False,
+ )
+ if not credential.rotated or not credential.password:
+ # CP reused a live grant but hands us no plaintext — we hold
+ # nothing, so we are in the "nothing usable exists" case: rotate.
+ credential = mint_service_credential(
+ target.organization_id,
+ target.team_id,
+ principal="dagster:events-backfill",
+ force_rotate=True,
+ )
+ if not credential.password:
+ raise ServiceCredentialUnavailable(
+ f"service credential for org={target.organization_id} team={target.team_id} "
+ "carries no password even after force_rotate"
+ )
+ logger.info(
+ "duckling_service_credential_minted",
+ team_id=target.team_id,
+ organization_id=target.organization_id,
+ username=credential.username,
+ rotated=credential.rotated,
+ expires_at=credential.expires_at.isoformat(),
+ )
+ return credential
+ except Exception as exc:
+ # Broad on purpose: the rollout policy is "keep the backfill working,"
+ # and the failure modes a rollout actually hits (new CP deploys,
+ # settings/import hiccups, unexpected error shapes) are precisely the
+ # ones that don't arrive as ServiceCredentialUnavailable. The loud
+ # event name is the alert handle for this transitional period.
+ logger.warning(
+ "duckling_service_credential_unavailable_falling_back_to_root",
+ team_id=target.team_id,
+ organization_id=target.organization_id,
+ error=str(exc),
+ error_type=type(exc).__name__,
+ )
+ return None
+
+
@retry(
# The duckgres CP absorbs a warm-pool miss by blocking the connect itself for
# up to the outer workerQueueTimeout (5m) waiting for a colocated worker — so a
@@ -308,14 +382,16 @@ def _resolve_duckling_target(team_id: int) -> DucklingTarget:
# or the CP giving up after its block): the delay cap must exceed one full
# attempt so a second one can actually run, hence 780s (~2 attempts) rather
# than 360s (which a single 360s attempt would exhaust, making retries a no-op).
- # This guards only the initial connect; a worker that drops mid-statement is
+ # This guards only the initial connect; a worker that drops mid-session is
# handled separately by _DuckgresSession's reconnect-and-retry.
stop=stop_after_delay(780) | stop_after_attempt(12),
wait=wait_exponential(multiplier=1, min=5, max=60),
retry=retry_if_exception_type((psycopg.OperationalError, OSError)),
reraise=True,
)
-def _connect_duckgres(target: DucklingTarget) -> psycopg.Connection[Any]:
+def _connect_duckgres(
+ target: DucklingTarget, service_credential: ServiceCredential | None = None
+) -> psycopg.Connection[Any]:
"""Open a psycopg connection to the org's duckgres server.
Each org runs its own duckgres process on the duckling side; it auto-attaches
@@ -329,10 +405,16 @@ def _connect_duckgres(target: DucklingTarget) -> psycopg.Connection[Any]:
connect_timeout to become ready (worker pod may need a fresh node), so we
retry the connect rather than failing the partition on the first timeout.
`psycopg.errors.ConnectionTimeout` is an `OperationalError` subclass.
+
+ When `service_credential` is provided the connection authenticates as the
+ team's canonical ``posthog_team_<id>_rw`` project_user login (team-scoped)
+ rather than the org-root credential. See
+ ``products/managed_warehouse/backend/service_credentials.py``.
"""
conninfo = make_duckgres_conninfo(
target.team_id,
organization_id=target.organization_id,
+ service_credential=service_credential,
)
conn = psycopg.connect(
conninfo,
@@ -478,7 +560,15 @@ class _DuckgresSession:
def __init__(self, context: AssetExecutionContext, target: DucklingTarget) -> None:
self._context = context
self._target = target
- self._conn = _connect_duckgres(target)
+ # Mint ONE team-scoped credential and present it on every connect of
+ # this session. Two classes of event can still invalidate it mid-run:
+ # (a) its TTL lapses and any other mint touch rotates the CP-side hash,
+ # (b) a CONCURRENT session for the same team rotates (backfill ops for
+ # one team run in parallel). Open connections are unaffected either
+ # way (expiry is handshake-only on the CP), but a _reconnect must
+ # refresh the credential once it's clearly stale — see _reconnect.
+ self._service_credential = _mint_backfill_service_credential(target)
+ self._conn = _connect_duckgres(target, service_credential=self._service_credential)
@property
def conn(self) -> psycopg.Connection[Any]:
@@ -537,12 +627,27 @@ class _DuckgresSession:
assert last_exc is not None # only reached after a recoverable-error break
raise last_exc
+ # Reconnects refresh the held credential when it is (nearly) expired — a
+ # long-running session's TTL may lapse mid-run, and the CP rotates the
+ # hash on the first mint touch after lapse.
+ _CREDENTIAL_REFRESH_WINDOW = timedelta(minutes=2)
+
def _reconnect(self) -> None:
try:
self._conn.close()
except Exception:
pass
- self._conn = _connect_duckgres(self._target)
+ cred = self._service_credential
+ if cred is not None and cred.expires_at - datetime.now(UTC) < self._CREDENTIAL_REFRESH_WINDOW:
+ logger.info(
+ "duckling_service_credential_refreshing_on_reconnect",
+ team_id=self._target.team_id,
+ organization_id=self._target.organization_id,
+ expires_at=cred.expires_at.isoformat(),
+ )
+ cred = _mint_backfill_service_credential(self._target)
+ self._service_credential = cred
+ self._conn = _connect_duckgres(self._target, service_credential=cred)
def close(self) -> None:
try:
diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.py
index a9985304c350..022217acd127 100644
--- a/posthog/dags/test_events_backfill_to_duckling.py
+++ b/posthog/dags/test_events_backfill_to_duckling.py
@@ -1,5 +1,5 @@
import os
-from datetime import date, datetime, timedelta
+from datetime import UTC, date, datetime, timedelta
from typing import Any, cast
import pytest
@@ -63,6 +63,7 @@ from posthog.dags.events_backfill_to_duckling import (
from products.data_warehouse.backend.facade.backfill_status import BackfillOutcome, get_months_in_range
from products.managed_warehouse.backend.facade.api import EARLIEST_BACKFILL_DATE, NO_HISTORY_SENTINEL
+from products.managed_warehouse.backend.facade.client import ServiceCredential, ServiceCredentialUnavailable
from products.managed_warehouse.backend.facade.contracts import (
ManagedWarehouseTableNames,
ManagedWarehouseTeamMembership,
@@ -1559,6 +1560,109 @@ class TestDuckgresSessionRetry:
assert mock_connect.call_count == 1 # never reconnects for an S3 hiccup
+class TestDuckgresSessionServiceCredential:
+ """The session mints reuse-FIRST (no rotation when a usable grant exists —
+ that's what keeps same-team concurrent runs/partitions from clobbering
+ each other's credentials), escalates to force_rotate only when the CP
+ hands back nothing usable, and refreshes a (nearly) expired credential on
+ reconnect."""
+
+ # Fixed datetimes, never datetime.now(): these payloads are what the CP
+ # hands a session, and the session's refresh decision is "expiry vs now"
+ # — so a stale credential is one expired in the PAST (fixed: far behind)
+ # and a fresh credential is one comfortably in the FUTURE (fixed: far
+ # ahead). Deterministic under any wall clock.
+ _STALE_EXPIRY = datetime(2020, 1, 1, tzinfo=UTC)
+ _FRESH_EXPIRY = datetime(2040, 1, 1, tzinfo=UTC)
+
+ def _credential(self, password: str, *, rotated: bool = True, expires_at: datetime | None = None):
+ return ServiceCredential(
+ username="posthog_team_2_rw",
+ password=password,
+ expires_at=expires_at or self._FRESH_EXPIRY,
+ rotated=rotated,
+ )
+
+ @patch("posthog.dags.events_backfill_to_duckling.mint_service_credential")
+ @patch("posthog.dags.events_backfill_to_duckling._connect_duckgres")
+ def test_mint_is_reuse_first_and_no_refresh_while_fresh(self, mock_connect, mock_mint):
+ credential = self._credential("grant", rotated=True)
+ mock_mint.return_value = credential
+ mock_connect.return_value = MagicMock()
+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="r")
+
+ session = _DuckgresSession(MagicMock(), target)
+
+ # First mint asks for NO rotation — a concurrent same-team run's
+ # working credential must not be clobbered by every session init.
+ mock_mint.assert_called_once_with("org-1", 2, principal="dagster:events-backfill", force_rotate=False)
+ session._reconnect()
+ assert mock_mint.call_count == 1 # still fresh — no refresh
+ assert mock_connect.call_args_list[1].kwargs["service_credential"] is credential
+
+ @patch("posthog.dags.events_backfill_to_duckling.mint_service_credential")
+ @patch("posthog.dags.events_backfill_to_duckling._connect_duckgres")
+ def test_escalates_to_force_rotate_when_reuse_returns_no_plaintext(self, mock_connect, mock_mint):
+ # The realistic first-fetch shape: CP reuses a live grant → no
+ # plaintext → must escalate to force_rotate to get one.
+ mock_mint.side_effect = [
+ self._credential("", rotated=False),
+ self._credential("escalated", rotated=True),
+ ]
+ mock_connect.return_value = MagicMock()
+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="r")
+
+ _DuckgresSession(MagicMock(), target)
+
+ assert mock_mint.call_args_list[0].kwargs["force_rotate"] is False
+ assert mock_mint.call_args_list[1].kwargs["force_rotate"] is True
+ # ...and the connect uses the ESCALATED credential (the one with a
+ # password), not the empty reuse response.
+ assert mock_connect.call_args_list[0].kwargs["service_credential"].password == "escalated"
+
+ @patch("posthog.dags.events_backfill_to_duckling.mint_service_credential")
+ @patch("posthog.dags.events_backfill_to_duckling._connect_duckgres")
+ def test_reconnect_refreshes_expired_credential(self, mock_connect, mock_mint):
+ # A session whose TTL lapses mid-run (long export, worker drops at
+ # t+2h) must NOT present the dead credential on reconnect — the CP
+ # rotates the hash on the first mint touch after lapse.
+ stale = self._credential("stale", expires_at=self._STALE_EXPIRY)
+ fresh = self._credential("fresh-secret")
+ mock_mint.side_effect = [stale, fresh]
+ mock_connect.side_effect = [MagicMock(name="c0"), MagicMock(name="c1")]
+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="r")
+
+ session = _DuckgresSession(MagicMock(), target)
+ session._reconnect()
+
+ assert mock_mint.call_count == 2
+ assert mock_connect.call_args_list[1].kwargs["service_credential"] is fresh
+
+ @patch("posthog.dags.events_backfill_to_duckling.mint_service_credential")
+ @patch("posthog.dags.events_backfill_to_duckling._connect_duckgres")
+ def test_falls_back_to_root_when_mint_unavailable(self, mock_connect, mock_mint):
+ mock_mint.side_effect = ServiceCredentialUnavailable("cp down")
+ mock_connect.return_value = MagicMock()
+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="r")
+
+ _DuckgresSession(MagicMock(), target)
+ # The CP being down must not fail the run while root still works —
+ # transitional path until DuckgresServer dies entirely.
+ assert mock_connect.call_args_list[0].kwargs["service_credential"] is None
+
+ @patch("posthog.dags.events_backfill_to_duckling.mint_service_credential")
+ @patch("posthog.dags.events_backfill_to_duckling._connect_duckgres")
+ def test_falls_back_to_root_on_unexpected_error(self, mock_connect, mock_mint):
+ # Rollout reality: unexpected error SHAPES (import hiccups, settings
+ # errors), not just the typed unavailable, degrade to root.
+ mock_mint.side_effect = ValueError("weird cp response")
+ mock_connect.return_value = MagicMock()
+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="r")
+
+ _DuckgresSession(MagicMock(), target)
+ assert mock_connect.call_args_list[0].kwargs["service_credential"] is None
+
+
class TestDuckgresBackfillOptions:
"""_duckgres_backfill_options() builds the libpq startup `options` string that
sizes/schedules the duckgres worker; it must request a small colocated worker
diff --git a/products/managed_warehouse/backend/client.py b/products/managed_warehouse/backend/client.py
index 2f4d2fae5fce..ea7d69170d48 100644
--- a/products/managed_warehouse/backend/client.py
+++ b/products/managed_warehouse/backend/client.py
@@ -13,6 +13,7 @@ from products.managed_warehouse.backend.common import (
sanitize_ducklake_identifier,
)
from products.managed_warehouse.backend.facade.contracts import DuckLakeQueryResult, DuckLakeTableResult
+from products.managed_warehouse.backend.service_credentials import ServiceCredential
from products.managed_warehouse.backend.table_binding import bind_tables_to_ducklake
if TYPE_CHECKING:
@@ -22,9 +23,60 @@ if TYPE_CHECKING:
from posthog.models.team.team import Team
-def make_duckgres_conninfo(team_id: int, *, organization_id: str | None = None) -> str:
+def make_duckgres_conninfo(
+ team_id: int,
+ *,
+ organization_id: str | None = None,
+ service_credential: ServiceCredential | None = None,
+) -> str:
+ """Build a psycopg conninfo for a team's duckgres server.
+
+ Default (no ``service_credential``): the org-root username/password from
+ the stored ``DuckgresServer`` row — the transitional path used by the SQL
+ editor and materialization until they move to minted credentials.
+
+ With ``service_credential``: connect as the team's canonical
+ ``posthog_team_<id>_rw`` project_user login (CP-issued, short-lived,
+ scoped to exactly the team's warehouse schemas). This is what background
+ jobs (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.
+ """
from products.managed_warehouse.backend.common import _duckgres_dev_config, _get_org_id_for_team
+ if service_credential is not None:
+ if is_dev_mode():
+ raise RuntimeError(
+ "service credentials are not available in dev mode (no CP to mint against); "
+ "omit service_credential to use the dev duckgres defaults"
+ )
+ if not service_credential.password:
+ raise RuntimeError(
+ "service_credential carries no password: the CP reused a live grant. "
+ "Mint with force_rotate=True when you have no cached credential."
+ )
+ expected_username = f"posthog_team_{team_id}_rw"
+ if service_credential.username != expected_username:
+ raise RuntimeError(
+ f"service_credential username {service_credential.username!r} does not match the "
+ 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))
+ return make_conninfo(
+ host=config["DUCKGRES_HOST"],
+ port=int(config["DUCKGRES_PORT"]),
+ dbname=config["DUCKGRES_DATABASE"],
+ user=service_credential.username,
+ password=service_credential.password,
+ sslmode="require",
+ sslcert="/tmp/no.txt",
+ sslkey="/tmp/no.txt",
+ sslrootcert="/tmp/no.txt",
+ )
+
if is_dev_mode():
config = _duckgres_dev_config()
else:
diff --git a/products/managed_warehouse/backend/facade/client.py b/products/managed_warehouse/backend/facade/client.py
index eda0e60c7356..8e6880b2d174 100644
--- a/products/managed_warehouse/backend/facade/client.py
+++ b/products/managed_warehouse/backend/facade/client.py
@@ -14,6 +14,11 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from products.managed_warehouse.backend import client
+from products.managed_warehouse.backend.service_credentials import (
+ ServiceCredential,
+ ServiceCredentialUnavailable,
+ mint_service_credential,
+)
if TYPE_CHECKING:
from posthog.schema import HogQLQuery
@@ -22,17 +27,30 @@ if TYPE_CHECKING:
from posthog.models.user import User
from products.managed_warehouse.backend.facade.contracts import DuckLakeQueryResult, DuckLakeTableResult
+ from products.managed_warehouse.backend.service_credentials import ServiceCredential
__all__ = [
+ "ServiceCredential",
+ "ServiceCredentialUnavailable",
"compile_hogql_to_ducklake_sql",
"execute_ducklake_create_table",
"execute_ducklake_query",
"make_duckgres_conninfo",
+ "mint_service_credential",
]
-def make_duckgres_conninfo(team_id: int, *, organization_id: str | None = None) -> str:
- return client.make_duckgres_conninfo(team_id, organization_id=organization_id)
+def make_duckgres_conninfo(
+ team_id: int,
+ *,
+ organization_id: str | None = None,
+ service_credential: ServiceCredential | None = None,
+) -> str:
+ return client.make_duckgres_conninfo(
+ team_id,
+ organization_id=organization_id,
+ service_credential=service_credential,
+ )
def compile_hogql_to_ducklake_sql(
diff --git a/products/managed_warehouse/backend/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.py
index ad481c1b936b..53c763e486ab 100644
--- a/products/managed_warehouse/backend/facade/contracts.py
+++ b/products/managed_warehouse/backend/facade/contracts.py
@@ -12,7 +12,7 @@ behavior change, not a contract improvement.
from __future__ import annotations
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from datetime import date, datetime
from enum import StrEnum
from typing import Any
@@ -34,6 +34,8 @@ __all__ = [
"ManagedWarehouseSourceJobWorkflow",
"ManagedWarehouseTableNames",
"ManagedWarehouseTeamMembership",
+ "ServiceCredential",
+ "ServiceCredentialUnavailable",
]
@@ -41,6 +43,31 @@ class CPUnavailableError(RuntimeError):
pass
+@dataclass(frozen=True)
+class ServiceCredential:
+ """A team-scoped credential minted by the duckgres control plane, for one
+ run's new duckgres connections (RDS-IAM pattern: short-lived, scoped,
+ disposable — see duckgres/CLAUDE.md "Service Credentials").
+
+ ``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``.
+ """
+
+ username: str
+ # repr=False: a dataclass repr lands credentials into any traceback,
+ # pytest assertion diff, or log line that stringifies the object.
+ password: str = field(repr=False)
+ expires_at: datetime
+ rotated: bool
+
+
+class ServiceCredentialUnavailable(RuntimeError):
+ """The control plane couldn't issue a service credential (unreachable,
+ org/team not provisioned, or a 5xx). Callers decide whether to fall back
+ to stored org-root credentials (transitional) or fail the run."""
+
+
@dataclass(frozen=True, kw_only=True)
class ManagedWarehouseProvisionStatus:
"""Whether an organization has a stored managed-warehouse connection."""
diff --git a/products/managed_warehouse/backend/service_credentials.py b/products/managed_warehouse/backend/service_credentials.py
new file mode 100644
index 000000000000..2eb0a3c80ece
--- /dev/null
+++ b/products/managed_warehouse/backend/service_credentials.py
@@ -0,0 +1,142 @@
+"""Mint short-lived, team-scoped duckgres service credentials from the control plane.
+
+This is the PostHog-side half of the duckgres "Service Credentials" contract
+(see duckgres/CLAUDE.md). A background job (dagster today) calls
+``mint_service_credential`` once per run to get a credential bound to the
+team's canonical ``posthog_team_<id>_rw`` project_user login — scoped to
+exactly that team's warehouse schemas — instead of reading the org-wide root
+credential out of a ``DuckgresServer`` row.
+
+Contract essentials mirrored here (read the CP side for the authoritative
+wording):
+
+- ``POST /api/v1/orgs/{org}/teams/{team}/service-credentials``, authed with
+ the existing internal secret — the same trust class as every other
+ provisioning call.
+- Expiry is enforced by ROTATION on the CP, not by the caller honoring
+ ``expires_at``: a still-valid grant is returned WITHOUT a password (the
+ caller already holds it from a prior fetch — or must ask for a rotation).
+- ``force_rotate=True`` is how a caller with nothing cached gets a password.
+ First call of a run must pass it.
+- Established connections are never killed on expiry (handshake-only
+ semantics, RDS-IAM style); only NEW connections need a live credential.
+
+Keep this module's request/response shapes byte-compatible with
+``controlplane/provisioning/service_credential.go``.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+import structlog
+from rest_framework import status
+
+from products.managed_warehouse.backend.facade.contracts import ServiceCredential, ServiceCredentialUnavailable
+
+__all__ = [
+ "DEFAULT_CREDENTIAL_TTL_SECONDS",
+ "MAX_CREDENTIAL_TTL_SECONDS",
+ "MIN_CREDENTIAL_TTL_SECONDS",
+ "ServiceCredential",
+ "ServiceCredentialUnavailable",
+ "mint_service_credential",
+]
+
+logger = structlog.get_logger(__name__)
+
+# Mirrored from controlplane/provisioning/service_credential.go. Keep these
+# three constants in sync with the CP's clamping policy.
+MIN_CREDENTIAL_TTL_SECONDS = 60
+MAX_CREDENTIAL_TTL_SECONDS = 3600
+DEFAULT_CREDENTIAL_TTL_SECONDS = 900 # 15 min — the RDS-IAM precedent
+
+
+def _redact_payload(data: Any) -> Any:
+ """Shape-preserving copy with credential-bearing values removed.
+
+ Every error path in this module that mentions the CP response must go
+ through this: a malformed mint response can still carry a live
+ ``password`` (e.g. present-but-empty username alongside a password), and
+ the caller's broad fallback logs whatever lands in the exception text.
+ A redacted placeholder keeps the debugging value of seeing the payload's
+ shape without leaking the grant.
+ """
+ if isinstance(data, dict):
+ return {
+ key: ("<redacted>" if "password" in str(key).lower() else _redact_payload(value))
+ for key, value in data.items()
+ }
+ if isinstance(data, list):
+ return [_redact_payload(item) for item in data]
+ return data
+
+
+def mint_service_credential(
+ organization_id: str,
+ team_id: int,
+ *,
+ principal: str,
+ ttl_seconds: int = DEFAULT_CREDENTIAL_TTL_SECONDS,
+ force_rotate: bool = False,
+) -> ServiceCredential:
+ """Mint-or-reuse the team's project_user credential for a short-lived job.
+
+ Returns a ``ServiceCredential``. Raises ``ServiceCredentialUnavailable``
+ on any CP-side failure — the CP's own error string is propagated verbatim
+ so operators see the real reason (unknown org, disabled team, DB down).
+ """
+ # Imported here to avoid an import cycle: presentation.views imports the
+ # facade, the facade (via client.py → service-credential-aware conninfo)
+ # imports this module.
+ from products.managed_warehouse.backend.presentation.views import _request # noqa: PLC0415
+
+ ttl_seconds = max(MIN_CREDENTIAL_TTL_SECONDS, min(ttl_seconds, MAX_CREDENTIAL_TTL_SECONDS))
+
+ response = _request(
+ "POST",
+ organization_id,
+ f"/teams/{team_id}/service-credentials",
+ json_body={
+ "team_id": team_id,
+ "principal": principal,
+ "ttl_seconds": ttl_seconds,
+ "force_rotate": force_rotate,
+ },
+ # Backend caller: never gate on the user-facing data-warehouse feature
+ # flag (a dagster worker may not have the flag definition loaded).
+ require_enabled=False,
+ )
+ if not status.is_success(response.status_code):
+ raise ServiceCredentialUnavailable(
+ f"service credential mint failed for org={organization_id} team={team_id}: "
+ f"HTTP {response.status_code}: {_redact_payload(response.data)!r}"
+ )
+ data: dict[str, Any] = response.data if isinstance(response.data, dict) else {}
+ username = data.get("username")
+ if not username:
+ # Never stringify the CP payload verbatim: a malformed response can
+ # still carry a real `password`, and the backfill's broad fallback
+ # handler logs whatever exception text we raise here.
+ raise ServiceCredentialUnavailable(f"mint returned no username: {_redact_payload(data)!r}")
+ expires_raw = data.get("expires_at")
+ try:
+ 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
+ credential = ServiceCredential(
+ username=str(username),
+ password=str(data.get("password") or ""),
+ expires_at=expires_at,
+ rotated=bool(data.get("password")),
+ )
+ logger.info(
+ "duckgres_service_credential_minted",
+ organization_id=organization_id,
+ team_id=team_id,
+ principal=principal,
+ rotated=credential.rotated,
+ expires_at=expires_at.isoformat(),
+ )
+ return credential
diff --git a/products/managed_warehouse/backend/tests/test_client_service_credentials.py b/products/managed_warehouse/backend/tests/test_client_service_credentials.py
new file mode 100644
index 000000000000..ef57428cd1cd
--- /dev/null
+++ b/products/managed_warehouse/backend/tests/test_client_service_credentials.py
@@ -0,0 +1,63 @@
+from datetime import UTC, datetime
+
+import pytest
+from unittest import mock
+
+from products.managed_warehouse.backend.client import make_duckgres_conninfo
+from products.managed_warehouse.backend.service_credentials import ServiceCredential
+
+
+def _credential(password: str = "minted-plaintext") -> ServiceCredential:
+ return ServiceCredential(
+ username="posthog_team_7_rw",
+ password=password,
+ expires_at=datetime(2026, 8, 11, 13, 0, tzinfo=UTC),
+ rotated=bool(password),
+ )
+
+
+class TestMakeDuckgresConninfoWithServiceCredential:
+ """client.make_duckgres_conninfo with a service_credential presents the
+ team's canonical project_user login (CP-issued, team-scoped), NOT the
+ org-root credential stored in the DuckgresServer row.
+ """
+
+ @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())
+
+ assert "user=posthog_team_7_rw" in conninfo
+ assert "password=minted-plaintext" in conninfo
+ assert "root-secret" not in conninfo
+ assert "sslmode=require" 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):
+ # 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=""))
+
+ 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())
diff --git a/products/managed_warehouse/backend/tests/test_service_credentials.py b/products/managed_warehouse/backend/tests/test_service_credentials.py
new file mode 100644
index 000000000000..e67223d8f032
--- /dev/null
+++ b/products/managed_warehouse/backend/tests/test_service_credentials.py
@@ -0,0 +1,145 @@
+from datetime import UTC, datetime
+
+import pytest
+from unittest import mock
+
+from rest_framework import status
+
+from products.managed_warehouse.backend.service_credentials import (
+ DEFAULT_CREDENTIAL_TTL_SECONDS,
+ MAX_CREDENTIAL_TTL_SECONDS,
+ MIN_CREDENTIAL_TTL_SECONDS,
+ ServiceCredentialUnavailable,
+ mint_service_credential,
+)
+
+
+def _ok_response(data: dict) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status.HTTP_200_OK
+ resp.data = data
+ return resp
+
+
+class TestMintServiceCredential:
+ def test_threads_request_fields_to_cp(self):
+ with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:
+ mock_request.return_value = _ok_response(
+ {
+ "username": "posthog_team_7_rw",
+ "password": "minted-plaintext",
+ "expires_at": "2026-08-11T13:00:00Z",
+ }
+ )
+
+ credential = mint_service_credential(
+ "org-1", 7, principal="dagster:events-backfill", ttl_seconds=900, force_rotate=True
+ )
+
+ assert credential.username == "posthog_team_7_rw"
+ assert credential.password == "minted-plaintext"
+ assert credential.rotated is True
+ assert credential.expires_at == datetime(2026, 8, 11, 13, 0, tzinfo=UTC)
+
+ mock_request.assert_called_once_with(
+ "POST",
+ "org-1",
+ "/teams/7/service-credentials",
+ json_body={
+ "team_id": 7,
+ "principal": "dagster:events-backfill",
+ "ttl_seconds": 900,
+ "force_rotate": True,
+ },
+ require_enabled=False,
+ )
+
+ def test_ttl_is_clamped_to_cp_policy(self):
+ with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:
+ mock_request.return_value = _ok_response(
+ {
+ "username": "posthog_team_7_rw",
+ "password": "p",
+ "expires_at": "2026-08-11T13:00:00Z",
+ }
+ )
+ mint_service_credential("org-1", 7, principal="d", ttl_seconds=1, force_rotate=True)
+ assert mock_request.call_args.kwargs["json_body"]["ttl_seconds"] == MIN_CREDENTIAL_TTL_SECONDS
+
+ mint_service_credential("org-1", 7, principal="d", ttl_seconds=100_000, force_rotate=True)
+ assert mock_request.call_args.kwargs["json_body"]["ttl_seconds"] == MAX_CREDENTIAL_TTL_SECONDS
+
+ mint_service_credential("org-1", 7, principal="d", force_rotate=True)
+ assert mock_request.call_args.kwargs["json_body"]["ttl_seconds"] == DEFAULT_CREDENTIAL_TTL_SECONDS
+
+ 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 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",
+ }
+ )
+ credential = mint_service_credential("org-1", 7, principal="d")
+
+ assert credential.password == ""
+ assert credential.rotated is False
+
+ def test_cp_error_raises_unavailable(self):
+ with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:
+ resp = mock.MagicMock()
+ resp.status_code = status.HTTP_409_CONFLICT
+ resp.data = {"error": "project login requires an enabled org team"}
+ mock_request.return_value = resp
+
+ with pytest.raises(ServiceCredentialUnavailable) as exc_info:
+ mint_service_credential("org-1", 99, principal="d", force_rotate=True)
+ assert "409" in str(exc_info.value)
+
+ 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"})
+ 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"}
+ )
+ with pytest.raises(ServiceCredentialUnavailable):
+ mint_service_credential("org-1", 7, principal="d", force_rotate=True)
+
+ 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"}
+ )
+ 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
+ # ...while keeping the shape visible for debugging.
+ assert "password" in message
+ assert "expires_at" in message
+
+ def test_error_status_body_is_redacted_too(self):
+ with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:
+ resp = mock.MagicMock()
+ resp.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
+ resp.data = {"error": "boom", "password": "leaked-in-error-body"}
+ mock_request.return_value = resp
+
+ with pytest.raises(ServiceCredentialUnavailable) as exc_info:
+ mint_service_credential("org-1", 7, principal="d", force_rotate=True)
+
+ assert "leaked-in-error-body" not in str(exc_info.value)