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): mint org-scoped service credentials as per-credential grants (#82438)

Benjamin Knofe-Vider8466d482d50e
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.py
index 5e9a026942e1..5060cdaaa977 100644
--- a/posthog/dags/events_backfill_to_duckling.py
+++ b/posthog/dags/events_backfill_to_duckling.py
@@ -97,6 +97,7 @@ from products.managed_warehouse.backend.facade.client import (
ServiceCredentialUnavailable,
make_duckgres_conninfo,
mint_service_credential,
+ refresh_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
@@ -306,20 +307,18 @@ 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.
+ """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.
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
@@ -335,7 +334,7 @@ def _mint_backfill_service_credential(target: DucklingTarget) -> ServiceCredenti
principal="dagster:events-backfill",
force_rotate=False,
)
- if not credential.rotated or not credential.password:
+ 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(
@@ -344,16 +343,16 @@ def _mint_backfill_service_credential(target: DucklingTarget) -> ServiceCredenti
principal="dagster:events-backfill",
force_rotate=True,
)
- if not credential.password:
+ if not credential.credential_secret:
raise ServiceCredentialUnavailable(
f"service credential for org={target.organization_id} team={target.team_id} "
- "carries no password even after force_rotate"
+ "carries no credential_secret even after force_rotate"
)
logger.info(
"duckling_service_credential_minted",
team_id=target.team_id,
organization_id=target.organization_id,
- username=credential.username,
+ credential_id=credential.credential_id,
rotated=credential.rotated,
expires_at=credential.expires_at.isoformat(),
)
@@ -643,9 +642,15 @@ class _DuckgresSession:
"duckling_service_credential_refreshing_on_reconnect",
team_id=self._target.team_id,
organization_id=self._target.organization_id,
+ credential_id=cred.credential_id,
expires_at=cred.expires_at.isoformat(),
)
- cred = _mint_backfill_service_credential(self._target)
+ # 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.
+ cred = refresh_service_credential(self._target.organization_id, cred.credential_id)
self._service_credential = cred
self._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.py
index 7bcfc9e20b36..253ed6e04b62 100644
--- a/posthog/dags/test_events_backfill_to_duckling.py
+++ b/posthog/dags/test_events_backfill_to_duckling.py
@@ -1582,10 +1582,10 @@ class TestDuckgresSessionServiceCredential:
sslmode="require",
)
- def _credential(self, password: str, *, rotated: bool = True, expires_at: datetime | None = None):
+ def _credential(self, credential_secret: str, *, rotated: bool = True, expires_at: datetime | None = None):
return ServiceCredential(
- username="posthog_team_2_rw",
- password=password,
+ credential_id="svc_test_events_backfill",
+ credential_secret=credential_secret,
expires_at=expires_at or self._FRESH_EXPIRY,
rotated=rotated,
connect=self._CONNECT,
@@ -1626,24 +1626,29 @@ class TestDuckgresSessionServiceCredential:
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"
+ assert mock_connect.call_args_list[0].kwargs["service_credential"].credential_secret == "escalated"
- @patch("posthog.dags.events_backfill_to_duckling.mint_service_credential")
+ @patch("posthog.dags.events_backfill_to_duckling.refresh_service_credential")
@patch("posthog.dags.events_backfill_to_duckling._connect_duckgres")
- def test_reconnect_refreshes_expired_credential(self, mock_connect, mock_mint):
+ @patch("posthog.dags.events_backfill_to_duckling.mint_service_credential")
+ def test_reconnect_refreshes_expired_credential(self, mock_mint, mock_connect, mock_refresh):
# 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.
+ # 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")
- mock_mint.side_effect = [stale, fresh]
+ mock_mint.return_value = stale
+ mock_refresh.return_value = 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_mint.call_count == 1 # the initial session mint only — NO re-mint
+ mock_refresh.assert_called_once_with("org-1", "svc_test_events_backfill")
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.py
index 24b6597bb8e6..771e6fd808cc 100644
--- a/products/managed_warehouse/backend/client.py
+++ b/products/managed_warehouse/backend/client.py
@@ -35,10 +35,9 @@ def make_duckgres_conninfo(
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
+ With ``service_credential``: connect with a CP-issued, org-scoped
+ per-credential grant (``svc_…`` credential_id + secret), short-lived and
+ disposable. This is what background jobs (dagster) should present; see
``products/managed_warehouse/backend/service_credentials.py``.
Host/port/database/sslmode come ENTIRELY from the credential's
CP-issued ``connect`` block — this branch never reads the stored
@@ -55,25 +54,18 @@ def make_duckgres_conninfo(
"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:
+ if not service_credential.credential_secret:
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"
+ "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."
)
connect = service_credential.connect
return make_conninfo(
host=connect.host,
port=connect.port,
dbname=connect.database,
- user=service_credential.username,
- password=service_credential.password,
+ user=service_credential.credential_id,
+ password=service_credential.credential_secret,
sslmode=connect.sslmode,
sslcert="/tmp/no.txt",
sslkey="/tmp/no.txt",
diff --git a/products/managed_warehouse/backend/facade/client.py b/products/managed_warehouse/backend/facade/client.py
index 8e6880b2d174..441fc6471426 100644
--- a/products/managed_warehouse/backend/facade/client.py
+++ b/products/managed_warehouse/backend/facade/client.py
@@ -18,6 +18,7 @@ from products.managed_warehouse.backend.service_credentials import (
ServiceCredential,
ServiceCredentialUnavailable,
mint_service_credential,
+ refresh_service_credential,
)
if TYPE_CHECKING:
@@ -37,6 +38,7 @@ __all__ = [
"execute_ducklake_query",
"make_duckgres_conninfo",
"mint_service_credential",
+ "refresh_service_credential",
]
diff --git a/products/managed_warehouse/backend/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.py
index 242548394ec0..d700d8d30fde 100644
--- a/products/managed_warehouse/backend/facade/contracts.py
+++ b/products/managed_warehouse/backend/facade/contracts.py
@@ -66,23 +66,30 @@ class ServiceCredentialConnect:
@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``.
+ """An org-scoped per-credential grant 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").
+
+ 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).
``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
+ credential_id: 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)
+ credential_secret: str = field(repr=False)
expires_at: datetime
rotated: bool
connect: ServiceCredentialConnect
diff --git a/products/managed_warehouse/backend/service_credentials.py b/products/managed_warehouse/backend/service_credentials.py
index 39b0606761aa..641f945daa3a 100644
--- a/products/managed_warehouse/backend/service_credentials.py
+++ b/products/managed_warehouse/backend/service_credentials.py
@@ -1,29 +1,35 @@
-"""Mint short-lived, team-scoped duckgres service credentials from the control plane.
+"""Mint short-lived, org-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.
+``mint_service_credential`` once per run to get a credential scoped to the
+org's warehouse access — minted as its own server-side grant ROW (not a
+rewrite of a shared team login's hash) — 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
+- ``POST /api/v1/orgs/{org}/service-credentials``, authed with the existing
+ internal 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.
+- The credential is live ONLY until ``expires_at``; refresh before lapse.
+ Established connections are never killed on expiry (handshake-only
semantics, 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
+- Every successful mint/refresh 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
+ ``DuckgresServer`` row; a 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
@@ -52,6 +58,7 @@ __all__ = [
"ServiceCredentialConnect",
"ServiceCredentialUnavailable",
"mint_service_credential",
+ "refresh_service_credential",
]
logger = structlog.get_logger(__name__)
@@ -67,15 +74,19 @@ 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.
+ through this: a malformed mint response can still carry a live secret
+ (e.g. a present-but-empty credential_id alongside a credential_secret),
+ 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))
+ key: (
+ "<redacted>"
+ if any(marker in str(key).lower() for marker in ("password", "secret"))
+ else _redact_payload(value)
+ )
for key, value in data.items()
}
if isinstance(data, list):
@@ -91,11 +102,16 @@ def mint_service_credential(
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.
+ """Mint-or-reuse an 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
- so operators see the real reason (unknown org, disabled team, DB down).
+ so operators see the real reason (unknown org, DB down).
+
+ ``team_id`` is kept as a parameter purely for backwards compatibility
+ with 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).
"""
# Imported here to avoid an import cycle: presentation.views imports the
# facade, the facade (via client.py → service-credential-aware conninfo)
@@ -107,9 +123,8 @@ def mint_service_credential(
response = _request(
"POST",
organization_id,
- f"/teams/{team_id}/service-credentials",
+ "/service-credentials",
json_body={
- "team_id": team_id,
"principal": principal,
"ttl_seconds": ttl_seconds,
"force_rotate": force_rotate,
@@ -120,58 +135,121 @@ def mint_service_credential(
)
if not status.is_success(response.status_code):
raise ServiceCredentialUnavailable(
- f"service credential mint failed for org={organization_id} team={team_id}: "
+ f"service credential mint failed for org={organization_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
- 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,
- )
+ credential = _parse_credential_response(data, action="mint")
logger.info(
"duckgres_service_credential_minted",
organization_id=organization_id,
team_id=team_id,
principal=principal,
+ credential_id=credential.credential_id,
rotated=credential.rotated,
- expires_at=expires_at.isoformat(),
- connect_host=connect.host,
- connect_port=connect.port,
+ expires_at=credential.expires_at.isoformat(),
+ connect_host=credential.connect.host,
+ connect_port=credential.connect.port,
+ )
+ return credential
+
+
+def refresh_service_credential(
+ organization_id: str,
+ credential_id: str,
+ *,
+ ttl_seconds: int = DEFAULT_CREDENTIAL_TTL_SECONDS,
+) -> 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.
+
+ 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
+ real reason.
+ """
+ # See mint_service_credential for the import-cycle note.
+ 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,
+ "/service-credentials/refresh",
+ json_body={
+ "credential_id": credential_id,
+ "ttl_seconds": ttl_seconds,
+ },
+ require_enabled=False,
+ )
+ if not status.is_success(response.status_code):
+ raise ServiceCredentialUnavailable(
+ f"service credential refresh failed for org={organization_id} credential_id={credential_id}: "
+ f"HTTP {response.status_code}: {_redact_payload(response.data)!r}"
+ )
+ data: dict[str, Any] = response.data if isinstance(response.data, dict) else {}
+ credential = _parse_credential_response(data, action="refresh")
+ logger.info(
+ "duckgres_service_credential_refreshed",
+ organization_id=organization_id,
+ credential_id=credential.credential_id,
+ expires_at=credential.expires_at.isoformat(),
+ connect_host=credential.connect.host,
+ connect_port=credential.connect.port,
)
return credential
-def _parse_connect(data: dict[str, Any]) -> ServiceCredentialConnect:
- """Parse the mandatory ``connect`` block from a successful mint response.
+def _parse_credential_response(data: dict[str, Any], *, action: str) -> ServiceCredential:
+ """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 = data.get("credential_id")
+ if not credential_id:
+ # Never stringify the CP payload verbatim: a malformed response can
+ # 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}")
+ 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"{action} returned unparseable expires_at {expires_raw!r}") from exc
+ connect = _parse_connect(data, action=action)
+ return ServiceCredential(
+ credential_id=str(credential_id),
+ credential_secret=str(data.get("credential_secret") or ""),
+ expires_at=expires_at,
+ rotated=bool(data.get("credential_secret")),
+ connect=connect,
+ )
+
+
+def _parse_connect(data: dict[str, Any], *, action: str = "mint") -> ServiceCredentialConnect:
+ """Parse the mandatory ``connect`` block from a successful 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).
+ STRICT: every successful mint/refresh 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}")
+ # still carry a live `credential_secret`, and the caller logs
+ # exception text.
+ raise ServiceCredentialUnavailable(f"{action} returned no connect block: {_redact_payload(data)!r}")
host = raw.get("host")
database = raw.get("database")
sslmode = raw.get("sslmode")
@@ -181,5 +259,5 @@ def _parse_connect(data: dict[str, Any]) -> ServiceCredentialConnect:
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}")
+ 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))
diff --git a/products/managed_warehouse/backend/tests/test_client_service_credentials.py b/products/managed_warehouse/backend/tests/test_client_service_credentials.py
index 9aa432faf71f..0d8ce89c5806 100644
--- a/products/managed_warehouse/backend/tests/test_client_service_credentials.py
+++ b/products/managed_warehouse/backend/tests/test_client_service_credentials.py
@@ -15,21 +15,20 @@ _CONNECT = ServiceCredentialConnect(
)
-def _credential(password: str) -> ServiceCredential:
+def _credential(secret: str, *, credential_id: str = "svc_test_a1b2c3d4e5") -> ServiceCredential:
return ServiceCredential(
- username="posthog_team_7_rw",
- password=password,
+ credential_id=credential_id,
+ credential_secret=secret,
expires_at=datetime(2026, 8, 11, 13, 0, tzinfo=UTC),
- rotated=bool(password),
+ rotated=bool(secret),
connect=_CONNECT,
)
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 — and dials the
- CP-issued `connect` target, never the row's host/port/database.
+ """client.make_duckgres_conninfo with a service_credential dials the
+ server-issued credential pair (svc_<id> + plaintext) and the CP-issued
+ `connect` target — never the DuckgresServer row stored in Django.
"""
@mock.patch(
@@ -42,7 +41,7 @@ class TestMakeDuckgresConninfoWithServiceCredential:
7, organization_id="org-1", service_credential=_credential("minted-plaintext")
)
- assert "user=posthog_team_7_rw" in conninfo
+ assert "user=svc_test_a1b2c3d4e5" in conninfo
assert "password=minted-plaintext" in conninfo
assert "host=019740a8-ac01-0000-cad1-4626cafbc273.dw.us.postwh.com" in conninfo
assert "port=443" in conninfo
@@ -59,8 +58,8 @@ class TestMakeDuckgresConninfoWithServiceCredential:
host="h.dw.us.postwh.com", port=443, database="ducklake", sslmode="verify-full"
)
credential = ServiceCredential(
- username="posthog_team_7_rw",
- password="minted-plaintext",
+ credential_id="svc_test_a1b2c3d4e5",
+ credential_secret="minted-plaintext",
expires_at=datetime(2026, 8, 11, 13, 0, tzinfo=UTC),
rotated=True,
connect=connect,
@@ -71,7 +70,7 @@ class TestMakeDuckgresConninfoWithServiceCredential:
assert "sslmode=verify-full" in conninfo
@mock.patch("products.managed_warehouse.backend.client.is_dev_mode", return_value=False)
- def test_empty_password_credential_is_rejected_loudly(self, _dev):
+ 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.
diff --git a/products/managed_warehouse/backend/tests/test_service_credentials.py b/products/managed_warehouse/backend/tests/test_service_credentials.py
index d06e74c397bd..e38f76751946 100644
--- a/products/managed_warehouse/backend/tests/test_service_credentials.py
+++ b/products/managed_warehouse/backend/tests/test_service_credentials.py
@@ -9,11 +9,17 @@ from products.managed_warehouse.backend.service_credentials import (
DEFAULT_CREDENTIAL_TTL_SECONDS,
MAX_CREDENTIAL_TTL_SECONDS,
MIN_CREDENTIAL_TTL_SECONDS,
+ ServiceCredential,
ServiceCredentialConnect,
ServiceCredentialUnavailable,
mint_service_credential,
+ refresh_service_credential,
)
+# Never a real secret: test payloads use this sentinel so assertion failures
+# can be checked for containment/redaction without a live grant in the tree.
+_FAKE_SECRET = "test-plaintext-sentinel-not-a-real-grant"
+
_CONNECT = {
"host": "org-1.dw.us.postwh.com",
"port": 443,
@@ -29,53 +35,55 @@ def _ok_response(data: dict) -> mock.MagicMock:
return resp
+def _mint_payload(**overrides: object) -> dict:
+ payload: dict = {
+ "credential_id": "svc_a1b2c3d4e5f60718293a4b5c",
+ "credential_secret": _FAKE_SECRET,
+ "expires_at": "2026-08-11T13:00:00Z",
+ "connect": _CONNECT,
+ }
+ payload.update(overrides)
+ return payload
+
+
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",
- "connect": _CONNECT,
- }
- )
+ 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
)
- assert credential.username == "posthog_team_7_rw"
- assert credential.password == "minted-plaintext"
+ # 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 True
assert 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"
)
+ # Org-scoped route, org-scoped body: team_id is absorbed by the
+ # signature for backwards compat but must NOT cross the wire.
mock_request.assert_called_once_with(
"POST",
"org-1",
- "/teams/7/service-credentials",
+ "/service-credentials",
json_body={
- "team_id": 7,
"principal": "dagster:events-backfill",
"ttl_seconds": 900,
"force_rotate": True,
},
require_enabled=False,
)
+ assert "team_id" not in mock_request.call_args.kwargs["json_body"]
+ assert "team_id" not in mock_request.call_args.args[2]
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",
- "connect": _CONNECT,
- }
- )
+ mock_request.return_value = _ok_response(_mint_payload())
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
@@ -85,23 +93,20 @@ class TestMintServiceCredential:
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. 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,
- }
- )
+ 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).
+ 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.password == ""
+ 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"
@@ -109,24 +114,25 @@ class TestMintServiceCredential:
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"}
+ resp.data = {"error": "org warehouse is not provisioned"}
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):
+ def test_missing_credential_id_raises_unavailable(self):
+ payload = _mint_payload()
+ del payload["credential_id"]
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", "connect": _CONNECT})
- with pytest.raises(ServiceCredentialUnavailable):
+ 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)
+ 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(
- {"username": "u", "password": "p", "expires_at": "not-a-timestamp", "connect": _CONNECT}
- )
+ 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)
@@ -136,10 +142,10 @@ class TestMintServiceCredential:
# 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).
+ payload = _mint_payload()
+ del payload["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"}
- )
+ 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)
assert "connect" in str(exc_info.value)
@@ -157,59 +163,166 @@ class TestMintServiceCredential:
)
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}
- )
+ 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)
assert "connect" in str(exc_info.value)
- def test_malformed_connect_never_leaks_password_in_exception(self):
+ def test_malformed_connect_never_leaks_secret_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.
+ # `credential_secret`, and the backfill's broad fallback logs
+ # exception text. Assert via the redacted shape, never the raw
+ # payload string.
+ payload = _mint_payload()
+ del payload["connect"]
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"}
- )
+ 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)
message = str(exc_info.value)
- assert "live-grant-plaintext" not in message
+ assert _FAKE_SECRET not in message
assert "<redacted>" in message
- def test_malformed_response_never_leaks_password_in_exception(self):
+ def test_malformed_response_never_leaks_secret_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",
- "connect": _CONNECT,
- }
- )
+ # CP payload that still carries a live `credential_secret` must not
+ # surface it there.
+ 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)
message = str(exc_info.value)
- assert "live-grant-plaintext" not in message
+ assert _FAKE_SECRET not in message
assert "<redacted>" in message
# ...while keeping the shape visible for debugging.
- assert "password" in message
+ assert "credential_secret" 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"}
+ resp.data = {"error": "boom", "credential_secret": _FAKE_SECRET}
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)
+ assert _FAKE_SECRET not in str(exc_info.value)
+
+ def test_credential_dataclass_repr_never_shows_secret(self):
+ # A dataclass repr lands in any traceback, pytest diff, or log line
+ # that stringifies the object: the secret must be repr=False.
+ credential = ServiceCredential(
+ 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"
+ ),
+ )
+ rendered = repr(credential)
+ assert _FAKE_SECRET not in rendered
+ assert "svc_a1b2c3d4e5f60718293a4b5c" in rendered # the id is not a secret
+
+
+class TestRefreshServiceCredential:
+ 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(_mint_payload())
+
+ 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 True
+ assert 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",
+ "org-1",
+ "/service-credentials/refresh",
+ json_body={
+ "credential_id": "svc_a1b2c3d4e5f60718293a4b5c",
+ "ttl_seconds": 600,
+ },
+ require_enabled=False,
+ )
+
+ def test_ttl_is_clamped_and_defaults(self):
+ with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:
+ mock_request.return_value = _ok_response(_mint_payload())
+ refresh_service_credential("org-1", "svc_x", ttl_seconds=1)
+ assert mock_request.call_args.kwargs["json_body"]["ttl_seconds"] == MIN_CREDENTIAL_TTL_SECONDS
+
+ refresh_service_credential("org-1", "svc_x", ttl_seconds=100_000)
+ assert mock_request.call_args.kwargs["json_body"]["ttl_seconds"] == MAX_CREDENTIAL_TTL_SECONDS
+
+ refresh_service_credential("org-1", "svc_x")
+ assert mock_request.call_args.kwargs["json_body"]["ttl_seconds"] == DEFAULT_CREDENTIAL_TTL_SECONDS
+
+ 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_404_NOT_FOUND
+ resp.data = {"error": "unknown or lapsed credential"}
+ mock_request.return_value = resp
+
+ with pytest.raises(ServiceCredentialUnavailable) as exc_info:
+ refresh_service_credential("org-1", "svc_gone")
+ assert "404" in str(exc_info.value)
+ # credential_id is not a secret; naming it in the error is fine.
+ assert "svc_gone" in str(exc_info.value)
+
+ def test_missing_credential_id_raises_unavailable(self):
+ payload = _mint_payload()
+ del payload["credential_id"]
+ with mock.patch("products.managed_warehouse.backend.presentation.views._request") as mock_request:
+ mock_request.return_value = _ok_response(payload)
+ with pytest.raises(ServiceCredentialUnavailable):
+ refresh_service_credential("org-1", "svc_x")
+
+ 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):
+ refresh_service_credential("org-1", "svc_x")
+
+ def test_missing_connect_raises_unavailable(self):
+ payload = _mint_payload()
+ del payload["connect"]
+ 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:
+ refresh_service_credential("org-1", "svc_x")
+ assert "connect" in str(exc_info.value)
+
+ 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", "credential_secret": _FAKE_SECRET}
+ mock_request.return_value = resp
+
+ with pytest.raises(ServiceCredentialUnavailable) as exc_info:
+ refresh_service_credential("org-1", "svc_x")
+
+ assert _FAKE_SECRET not in str(exc_info.value)
+
+ def test_malformed_response_never_leaks_secret_in_exception(self):
+ 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:
+ refresh_service_credential("org-1", "svc_x")
+
+ message = str(exc_info.value)
+ assert _FAKE_SECRET not in message
+ assert "<redacted>" in message