:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(dags): mint independent duckgres credentials (#82674)
Benjamin Knofe-Vider60c70f931a52
diff --git a/posthog/dags/README_DUCKLINGS.md b/posthog/dags/README_DUCKLINGS.mdindex f8d9b60691e2..da3f0880fe22 100644--- a/posthog/dags/README_DUCKLINGS.md+++ b/posthog/dags/README_DUCKLINGS.md@@ -155,6 +155,11 @@ class DucklingBackfillConfig:3. To trigger immediate historical backfill, reset the full backfill sensor cursor+Each Dagster backfill session mints a new short-lived Duckgres service credential.+Concurrent sessions use the same `dagster:events-backfill` audit principal but receive+different credential IDs and secrets. A reconnect refreshes only the credential ID held+by that session.+## Troubleshooting### Partition stuck in "Running"diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.pyindex 5060cdaaa977..e02d7f6c450f 100644--- a/posthog/dags/events_backfill_to_duckling.py+++ b/posthog/dags/events_backfill_to_duckling.py@@ -310,15 +310,10 @@ def _mint_backfill_service_credential(target: DucklingTarget) -> ServiceCredenti"""Mint one org-scoped per-credential service credential for this session,or None to fall back.- The CP hands back a fresh (credential_id, credential_secret) pair: reuse- asks for the live grant without rotation (so a concurrent backfill's- own per-credential session is NOT clobbered), and only escalates to- force_rotate when the CP has no usable credential to hand back (fresh- principal entry, grant lapsed, or an operator revoke in-between — all- cases where the reuse path returns no plaintext). With per-credential- grants each mint mints a NEW credential, so an escalation can never- smash another run's open session the way a shared-login rotation once- did.+ The CP creates a fresh grant and returns its credential ID and secret.+ The fixed principal is audit metadata, so concurrent backfills mint+ independent credentials. Reconnects retain the credential ID and refresh+ only the grant owned by this session.Fallback to org-root (None) is deliberate and transitional: a CP that isunreachable, an org whose team row hasn't been created yet, or dev-mode@@ -332,28 +327,17 @@ def _mint_backfill_service_credential(target: DucklingTarget) -> ServiceCredentitarget.organization_id,target.team_id,principal="dagster:events-backfill",- force_rotate=False,)- if not credential.rotated or not credential.credential_secret:- # 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.credential_secret:raise ServiceCredentialUnavailable(f"service credential for org={target.organization_id} team={target.team_id} "- "carries no credential_secret even after force_rotate"+ "carries no credential_secret")logger.info("duckling_service_credential_minted",team_id=target.team_id,organization_id=target.organization_id,credential_id=credential.credential_id,- rotated=credential.rotated,expires_at=credential.expires_at.isoformat(),)return credential@@ -559,13 +543,8 @@ class _DuckgresSession:def __init__(self, context: AssetExecutionContext, target: DucklingTarget) -> None:self._context = contextself._target = 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.+ # Keep one org-scoped credential ID for the session so reconnects+ # refresh that grant instead of minting a different credential.self._service_credential = _mint_backfill_service_credential(target)self._conn = _connect_duckgres(target, service_credential=self._service_credential)@@ -645,11 +624,8 @@ class _DuckgresSession:credential_id=cred.credential_id,expires_at=cred.expires_at.isoformat(),)- # Refresh the SAME credential in place. The refresh endpoint- # always rotates the secret and bumps expires_at; with- # per-credential grants it can't smash any other run's session- # (we OWN this credential_id), so a re-mint would only waste a- # fresh row and mint log for no gain.+ # Refresh by credential ID so reconnects cannot rotate another+ # run's grant, even when both runs share the same audit principal.cred = refresh_service_credential(self._target.organization_id, cred.credential_id)self._service_credential = credself._conn = _connect_duckgres(self._target, service_credential=cred)diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.pyindex 253ed6e04b62..c256552a0e1f 100644--- a/posthog/dags/test_events_backfill_to_duckling.py+++ b/posthog/dags/test_events_backfill_to_duckling.py@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime, timedeltafrom typing import Any, castimport pytest-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, call, patchimport duckdbimport psycopg@@ -1562,12 +1562,6 @@ class TestDuckgresSessionRetry: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)@@ -1575,6 +1569,8 @@ class TestDuckgresSessionServiceCredential:# ahead). Deterministic under any wall clock._STALE_EXPIRY = datetime(2020, 1, 1, tzinfo=UTC)_FRESH_EXPIRY = datetime(2040, 1, 1, tzinfo=UTC)+ _FIRST_CREDENTIAL_ID = "svc_0123456789abcdef01234567"+ _SECOND_CREDENTIAL_ID = "svc_89abcdef0123456789abcdef"_CONNECT = ServiceCredentialConnect(host="019740a8-ac01-0000-cad1-4626cafbc273.dw.us.postwh.com",port=443,@@ -1582,51 +1578,75 @@ class TestDuckgresSessionServiceCredential:sslmode="require",)- def _credential(self, credential_secret: str, *, rotated: bool = True, expires_at: datetime | None = None):+ def _credential(+ self,+ credential_secret: str,+ *,+ credential_id: str,+ expires_at: datetime | None = None,+ ):return ServiceCredential(- credential_id="svc_test_events_backfill",+ credential_id=credential_id,credential_secret=credential_secret,expires_at=expires_at or self._FRESH_EXPIRY,- rotated=rotated,connect=self._CONNECT,)@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)+ def test_mints_once_and_no_refresh_while_fresh(self, mock_connect, mock_mint):+ credential = self._credential("grant", credential_id=self._FIRST_CREDENTIAL_ID)mock_mint.return_value = credentialmock_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)+ mock_mint.assert_called_once_with("org-1", 2, principal="dagster:events-backfill")session._reconnect()assert mock_mint.call_count == 1 # still fresh — no refreshassert mock_connect.call_args_list[1].kwargs["service_credential"] is credential+ @patch("posthog.dags.events_backfill_to_duckling.refresh_service_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.+ def test_concurrent_sessions_with_same_principal_manage_distinct_credentials(+ self, mock_connect, mock_mint, mock_refresh+ ):mock_mint.side_effect = [- self._credential("", rotated=False),- self._credential("escalated", rotated=True),+ self._credential("first-secret", credential_id=self._FIRST_CREDENTIAL_ID, expires_at=self._STALE_EXPIRY),+ self._credential(+ "second-secret",+ credential_id=self._SECOND_CREDENTIAL_ID,+ expires_at=self._STALE_EXPIRY,+ ),+ ]+ mock_refresh.side_effect = [+ self._credential("first-refreshed", credential_id=self._FIRST_CREDENTIAL_ID),+ self._credential("second-refreshed", credential_id=self._SECOND_CREDENTIAL_ID),]mock_connect.return_value = MagicMock()target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="r")- _DuckgresSession(MagicMock(), target)+ first_session = _DuckgresSession(MagicMock(), target)+ second_session = _DuckgresSession(MagicMock(), target)+ first_session._reconnect()+ second_session._reconnect()- 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"].credential_secret == "escalated"+ assert mock_mint.call_args_list == [+ call("org-1", 2, principal="dagster:events-backfill"),+ call("org-1", 2, principal="dagster:events-backfill"),+ ]+ assert [call.kwargs["service_credential"].credential_id for call in mock_connect.call_args_list] == [+ self._FIRST_CREDENTIAL_ID,+ self._SECOND_CREDENTIAL_ID,+ self._FIRST_CREDENTIAL_ID,+ self._SECOND_CREDENTIAL_ID,+ ]+ assert mock_refresh.call_args_list == [+ call("org-1", self._FIRST_CREDENTIAL_ID),+ call("org-1", self._SECOND_CREDENTIAL_ID),+ ]@patch("posthog.dags.events_backfill_to_duckling.refresh_service_credential")@patch("posthog.dags.events_backfill_to_duckling._connect_duckgres")@@ -1637,8 +1657,8 @@ class TestDuckgresSessionServiceCredential:# rotates the SECRET for that credential_id on refresh. The same# identity comes back; with per-credential grants this refresh is# scoped to exactly the credential the session holds.- stale = self._credential("stale", expires_at=self._STALE_EXPIRY)- fresh = self._credential("fresh-secret")+ stale = self._credential("stale", credential_id=self._FIRST_CREDENTIAL_ID, expires_at=self._STALE_EXPIRY)+ fresh = self._credential("fresh-secret", credential_id=self._FIRST_CREDENTIAL_ID)mock_mint.return_value = stalemock_refresh.return_value = freshmock_connect.side_effect = [MagicMock(name="c0"), MagicMock(name="c1")]@@ -1648,7 +1668,7 @@ class TestDuckgresSessionServiceCredential:session._reconnect()assert mock_mint.call_count == 1 # the initial session mint only — NO re-mint- mock_refresh.assert_called_once_with("org-1", "svc_test_events_backfill")+ mock_refresh.assert_called_once_with("org-1", self._FIRST_CREDENTIAL_ID)assert mock_connect.call_args_list[1].kwargs["service_credential"] is fresh@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 771e6fd808cc..a3b6684ec322 100644--- a/products/managed_warehouse/backend/client.py+++ b/products/managed_warehouse/backend/client.py@@ -55,10 +55,7 @@ def make_duckgres_conninfo("omit service_credential to use the dev duckgres defaults")if not service_credential.credential_secret:- raise RuntimeError(- "service_credential carries no secret: the CP reused a live grant. "- "Mint with force_rotate=True (or refresh the credential) when you have no cached credential."- )+ raise RuntimeError("service_credential carries no secret; mint or refresh returned an invalid response")connect = service_credential.connectreturn make_conninfo(host=connect.host,diff --git a/products/managed_warehouse/backend/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.pyindex d700d8d30fde..66504dbc38e4 100644--- a/products/managed_warehouse/backend/facade/contracts.py+++ b/products/managed_warehouse/backend/facade/contracts.py@@ -71,15 +71,12 @@ class ServiceCredential:short-lived, scoped, disposable — see duckgres/CLAUDE.md "ServiceCredentials").- Each minted credential is its own server-side grant row — NOT a rewrite- of a shared team login's hash, so minting never disturbs sessions other- mints created. ``credential_id`` is the CP-generated identifier- (``svc_<24 random hex>``); it is NOT a secret and may be logged.- ``credential_secret`` is empty when the CP REUSED a still-valid grant for- the same (org, principal) (`rotated` is False): callers that already- hold the secret keep using it; callers that don't must re-mint with- ``force_rotate=True``, or call ``refresh_service_credential`` with the- ``credential_id`` (refresh always rotates).+ Each mint creates its own server-side grant row, so minting never+ disturbs sessions created by other mints. ``principal`` is audit metadata+ and does not select an existing grant. ``credential_id`` is the+ CP-generated identifier (``svc_<24 random hex>``); it is not a secret and+ may be logged. Callers retain it to refresh the credential they minted.+ Every successful mint and refresh includes ``credential_secret``.``connect`` carries the CP-issued dial target for the credential and isREQUIRED on every successful mint — a mint response without it is an@@ -91,7 +88,6 @@ class ServiceCredential:# pytest assertion diff, or log line that stringifies the object.credential_secret: str = field(repr=False)expires_at: datetime- rotated: boolconnect: ServiceCredentialConnectdiff --git a/products/managed_warehouse/backend/service_credentials.py b/products/managed_warehouse/backend/service_credentials.pyindex 641f945daa3a..d843a52be588 100644--- a/products/managed_warehouse/backend/service_credentials.py+++ b/products/managed_warehouse/backend/service_credentials.py@@ -13,16 +13,12 @@ wording):- ``POST /api/v1/orgs/{org}/service-credentials``, authed with the existinginternal secret — the same trust class as every other provisioning call.The response's ``credential_id`` is CP-generated (``svc_<24 random hex>``).-- Expiry is enforced by the credential lapsing at ``expires_at``, not by the- caller honoring a rotation schedule: a still-valid grant for the same- (org, principal) is returned WITHOUT a secret (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 secret.- First call of a run must pass it. Alternatively,- ``POST /api/v1/orgs/{org}/service-credentials/refresh`` (via- ``refresh_service_credential``) ALWAYS rotates the secret for a known- ``credential_id`` — there is no "reuse" on that endpoint by explicit- design: each credential is unique, so there is nothing to race.+- Every mint creates a new grant and returns its new ``credential_id`` and+ ``credential_secret``. ``principal`` is audit metadata, so concurrent jobs+ can use the same principal without sharing or rotating each other's grants.+- ``POST /api/v1/orgs/{org}/service-credentials/refresh`` (via+ ``refresh_service_credential``) rotates the secret for one known+ ``credential_id``. Callers retain that ID to manage the grant they minted.- The credential is live ONLY until ``expires_at``; refresh before lapse.Established connections are never killed on expiry (handshake-onlysemantics, RDS-IAM style); only NEW connections need a live credential.@@ -100,9 +96,8 @@ def mint_service_credential(*,principal: str,ttl_seconds: int = DEFAULT_CREDENTIAL_TTL_SECONDS,- force_rotate: bool = False,) -> ServiceCredential:- """Mint-or-reuse an org-scoped service credential for a short-lived job.+ """Mint a new org-scoped service 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@@ -111,7 +106,8 @@ def mint_service_credential(``team_id`` is kept as a parameter purely for backwards compatibilitywith callers that still have it in scope. It is NOT sent on the wire:under the org-scoped per-credential-grant contract the control plane does- not key credentials by team, only by (org, principal).+ not key credentials by team. ``principal`` is audit metadata and does not+ identify or reuse a grant."""# Imported here to avoid an import cycle: presentation.views imports the# facade, the facade (via client.py → service-credential-aware conninfo)@@ -127,7 +123,6 @@ def mint_service_credential(json_body={"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).@@ -146,7 +141,6 @@ def mint_service_credential(team_id=team_id,principal=principal,credential_id=credential.credential_id,- rotated=credential.rotated,expires_at=credential.expires_at.isoformat(),connect_host=credential.connect.host,connect_port=credential.connect.port,@@ -162,14 +156,13 @@ def refresh_service_credential() -> ServiceCredential:"""Rotate the secret on a known credential before it lapses.- Refresh ALWAYS rotates: the response always carries a fresh- ``credential_secret`` (``rotated`` is True). There is no "reuse" on this- endpoint by explicit design — each credential is its own grant row, so- there is nothing to race.+ Refresh always returns a fresh ``credential_secret`` for the supplied+ ``credential_id``. Addressing the grant by ID prevents one caller from+ refreshing another caller's credential.Returns a ``ServiceCredential``. Raises ``ServiceCredentialUnavailable``- on any CP-side failure (unknown credential_id, lapsed credential, 5xx) —- the CP's own error string is propagated verbatim so operators see the+ on any CP-side failure (unknown credential_id, lapsed credential, 5xx).+ The CP's own error string is propagated verbatim so operators see thereal reason."""# See mint_service_credential for the import-cycle note.@@ -209,8 +202,8 @@ def _parse_credential_response(data: dict[str, Any], *, action: str) -> ServiceC"""Parse a successful mint/refresh response into a ``ServiceCredential``.Shared by both endpoints: the response contract is the same shape- (``credential_id``, optional ``credential_secret``, ``expires_at``,- ``connect``); refresh differs only in that the secret is always present.+ (``credential_id``, ``credential_secret``, ``expires_at``, ``connect``).+ Mint and refresh both require a plaintext secret in their response."""credential_id = data.get("credential_id")if not credential_id:@@ -218,6 +211,9 @@ def _parse_credential_response(data: dict[str, Any], *, action: str) -> ServiceC# still carry a live `credential_secret`, and the backfill's broad# fallback handler logs whatever exception text we raise here.raise ServiceCredentialUnavailable(f"{action} returned no credential_id: {_redact_payload(data)!r}")+ credential_secret = data.get("credential_secret")+ if not credential_secret:+ raise ServiceCredentialUnavailable(f"{action} returned no credential_secret: {_redact_payload(data)!r}")expires_raw = data.get("expires_at")try:expires_at = datetime.fromisoformat(str(expires_raw).replace("Z", "+00:00"))@@ -226,9 +222,8 @@ def _parse_credential_response(data: dict[str, Any], *, action: str) -> ServiceCconnect = _parse_connect(data, action=action)return ServiceCredential(credential_id=str(credential_id),- credential_secret=str(data.get("credential_secret") or ""),+ credential_secret=str(credential_secret),expires_at=expires_at,- rotated=bool(data.get("credential_secret")),connect=connect,)diff --git a/products/managed_warehouse/backend/tests/test_client_service_credentials.py b/products/managed_warehouse/backend/tests/test_client_service_credentials.pyindex 0d8ce89c5806..26fdb768a774 100644--- a/products/managed_warehouse/backend/tests/test_client_service_credentials.py+++ b/products/managed_warehouse/backend/tests/test_client_service_credentials.py@@ -15,12 +15,11 @@ _CONNECT = ServiceCredentialConnect()-def _credential(secret: str, *, credential_id: str = "svc_test_a1b2c3d4e5") -> ServiceCredential:+def _credential(secret: str, *, credential_id: str) -> ServiceCredential:return ServiceCredential(credential_id=credential_id,credential_secret=secret,expires_at=datetime(2026, 8, 11, 13, 0, tzinfo=UTC),- rotated=bool(secret),connect=_CONNECT,)@@ -38,10 +37,12 @@ class TestMakeDuckgresConninfoWithServiceCredential:@mock.patch("products.managed_warehouse.backend.client.is_dev_mode", return_value=False)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")+ 7,+ organization_id="org-1",+ service_credential=_credential("minted-plaintext", credential_id="svc_0123456789abcdef01234567"),)- assert "user=svc_test_a1b2c3d4e5" in conninfo+ assert "user=svc_0123456789abcdef01234567" in conninfoassert "password=minted-plaintext" in conninfoassert "host=019740a8-ac01-0000-cad1-4626cafbc273.dw.us.postwh.com" in conninfoassert "port=443" in conninfo@@ -58,10 +59,9 @@ class TestMakeDuckgresConninfoWithServiceCredential:host="h.dw.us.postwh.com", port=443, database="ducklake", sslmode="verify-full")credential = ServiceCredential(- credential_id="svc_test_a1b2c3d4e5",+ credential_id="svc_0123456789abcdef01234567",credential_secret="minted-plaintext",expires_at=datetime(2026, 8, 11, 13, 0, tzinfo=UTC),- rotated=True,connect=connect,)@@ -71,13 +71,17 @@ class TestMakeDuckgresConninfoWithServiceCredential:@mock.patch("products.managed_warehouse.backend.client.is_dev_mode", return_value=False)def test_empty_secret_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.- with pytest.raises(RuntimeError, match="force_rotate"):- make_duckgres_conninfo(7, organization_id="org-1", service_credential=_credential(""))+ with pytest.raises(RuntimeError, match="invalid response"):+ make_duckgres_conninfo(+ 7,+ organization_id="org-1",+ service_credential=_credential("", credential_id="svc_0123456789abcdef01234567"),+ )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("minted-plaintext"))+ make_duckgres_conninfo(+ 7,+ service_credential=_credential("minted-plaintext", credential_id="svc_0123456789abcdef01234567"),+ )diff --git a/products/managed_warehouse/backend/tests/test_service_credentials.py b/products/managed_warehouse/backend/tests/test_service_credentials.pyindex e38f76751946..bda0310c407a 100644--- a/products/managed_warehouse/backend/tests/test_service_credentials.py+++ b/products/managed_warehouse/backend/tests/test_service_credentials.py@@ -51,15 +51,12 @@ class TestMintServiceCredential:with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:mock_request.return_value = _ok_response(_mint_payload())- credential = mint_service_credential(- "org-1", 7, principal="dagster:events-backfill", ttl_seconds=900, force_rotate=True- )+ credential = mint_service_credential("org-1", 7, principal="dagster:events-backfill", ttl_seconds=900)# credential_id is server-generated: svc_-prefixed, non-empty.assert credential.credential_id.startswith("svc_")assert len(credential.credential_id) > len("svc_")assert credential.credential_secret == _FAKE_SECRET- 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"@@ -74,7 +71,6 @@ class TestMintServiceCredential:json_body={"principal": "dagster:events-backfill","ttl_seconds": 900,- "force_rotate": True,},require_enabled=False,)@@ -84,31 +80,22 @@ class TestMintServiceCredential: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(_mint_payload())- mint_service_credential("org-1", 7, principal="d", ttl_seconds=1, force_rotate=True)+ mint_service_credential("org-1", 7, principal="d", ttl_seconds=1)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)+ mint_service_credential("org-1", 7, principal="d", ttl_seconds=100_000)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)+ mint_service_credential("org-1", 7, principal="d")assert mock_request.call_args.kwargs["json_body"]["ttl_seconds"] == DEFAULT_CREDENTIAL_TTL_SECONDS- def test_reuse_path_reports_missing_secret(self):- # When the CP reuses a live grant for the same (org, principal) it- # omits credential_secret — the caller sees credential_secret == ""- # and rotated == False and must mint with force_rotate (or refresh)- # if it has nothing cached. The connect block is present on reuse- # too (every successful mint carries it).+ def test_missing_secret_raises_unavailable(self):payload = _mint_payload()del payload["credential_secret"]with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:mock_request.return_value = _ok_response(payload)- credential = mint_service_credential("org-1", 7, principal="d")-- assert credential.credential_id.startswith("svc_")- assert credential.credential_secret == ""- assert credential.rotated is False- assert credential.connect.host == "org-1.dw.us.postwh.com"+ with pytest.raises(ServiceCredentialUnavailable, match="credential_secret"):+ mint_service_credential("org-1", 7, principal="d")def test_cp_error_raises_unavailable(self):with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:@@ -118,7 +105,7 @@ class TestMintServiceCredential:mock_request.return_value = respwith pytest.raises(ServiceCredentialUnavailable) as exc_info:- mint_service_credential("org-1", 99, principal="d", force_rotate=True)+ mint_service_credential("org-1", 99, principal="d")assert "409" in str(exc_info.value)def test_missing_credential_id_raises_unavailable(self):@@ -127,14 +114,14 @@ class TestMintServiceCredential:with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:mock_request.return_value = _ok_response(payload)with pytest.raises(ServiceCredentialUnavailable) as exc_info:- mint_service_credential("org-1", 7, principal="d", force_rotate=True)+ mint_service_credential("org-1", 7, principal="d")assert "credential_id" in str(exc_info.value)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(_mint_payload(expires_at="not-a-timestamp"))with pytest.raises(ServiceCredentialUnavailable):- mint_service_credential("org-1", 7, principal="d", force_rotate=True)+ mint_service_credential("org-1", 7, principal="d")def test_missing_connect_raises_unavailable(self):# A 2xx without `connect` is an older CP than the contract. The@@ -147,7 +134,7 @@ class TestMintServiceCredential:with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:mock_request.return_value = _ok_response(payload)with pytest.raises(ServiceCredentialUnavailable) as exc_info:- mint_service_credential("org-1", 7, principal="d", force_rotate=True)+ mint_service_credential("org-1", 7, principal="d")assert "connect" in str(exc_info.value)@pytest.mark.parametrize(@@ -165,7 +152,7 @@ class TestMintServiceCredential:with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:mock_request.return_value = _ok_response(_mint_payload(connect=connect))with pytest.raises(ServiceCredentialUnavailable) as exc_info:- mint_service_credential("org-1", 7, principal="d", force_rotate=True)+ mint_service_credential("org-1", 7, principal="d")assert "connect" in str(exc_info.value)def test_malformed_connect_never_leaks_secret_in_exception(self):@@ -179,7 +166,7 @@ class TestMintServiceCredential:with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:mock_request.return_value = _ok_response(payload)with pytest.raises(ServiceCredentialUnavailable) as exc_info:- mint_service_credential("org-1", 7, principal="d", force_rotate=True)+ mint_service_credential("org-1", 7, principal="d")message = str(exc_info.value)assert _FAKE_SECRET not in message@@ -192,7 +179,7 @@ class TestMintServiceCredential:with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:mock_request.return_value = _ok_response(_mint_payload(credential_id=""))with pytest.raises(ServiceCredentialUnavailable) as exc_info:- mint_service_credential("org-1", 7, principal="d", force_rotate=True)+ mint_service_credential("org-1", 7, principal="d")message = str(exc_info.value)assert _FAKE_SECRET not in message@@ -209,7 +196,7 @@ class TestMintServiceCredential:mock_request.return_value = respwith pytest.raises(ServiceCredentialUnavailable) as exc_info:- mint_service_credential("org-1", 7, principal="d", force_rotate=True)+ mint_service_credential("org-1", 7, principal="d")assert _FAKE_SECRET not in str(exc_info.value)@@ -220,7 +207,6 @@ class TestMintServiceCredential:credential_id="svc_a1b2c3d4e5f60718293a4b5c",credential_secret=_FAKE_SECRET,expires_at=datetime(2026, 8, 11, 13, 0, tzinfo=UTC),- rotated=True,connect=ServiceCredentialConnect(host="org-1.dw.us.postwh.com", port=443, database="ducklake", sslmode="require"),@@ -238,9 +224,7 @@ class TestRefreshServiceCredential:credential = refresh_service_credential("org-1", "svc_a1b2c3d4e5f60718293a4b5c", ttl_seconds=600)assert credential.credential_id == "svc_a1b2c3d4e5f60718293a4b5c"- # Refresh ALWAYS rotates: the secret is always present.assert credential.credential_secret == _FAKE_SECRET- 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"