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.

fix(managed-warehouse): share service credentials through Redis (#86419)

Benjamin Knofe-Vider5049c633cc37
diff --git a/docs/internal/managed-warehouse-sql-editor.md b/docs/internal/managed-warehouse-sql-editor.md
index c83bcb47bb5f..e927c8f10005 100644
--- a/docs/internal/managed-warehouse-sql-editor.md
+++ b/docs/internal/managed-warehouse-sql-editor.md
@@ -6,7 +6,13 @@ The `managed-warehouse-sql-editor` feature flag controls which managed warehouse
Existing active `project_reader` and static organization-login sources remain byte-for-byte unchanged. Turning the operational gate off leaves a same-generation dynamic source byte-for-byte unchanged and never copies the stored root secret into that row. After a failed cleanup, a genuine reprovision keeps an existing dynamic source but advances its lifecycle marker and makes readers from the old generation unavailable. Without a dynamic source, gate-off reprovision makes stale readers unavailable before creating the static source. Dynamic-mode reconciliation never creates or revives sources. While the operational gate is off, reconciliation may complete generation-fenced static source setup after a successful provision, but it does not revive an unfenced legacy tombstone.
-Dynamic raw queries use the native Duckgres pgwire adapter. At physical connection acquisition, PostHog mints a short-lived organization-root-shaped service credential for a principal containing the project ID and stable PostHog user ID. Email addresses are never used. Schema discovery uses a distinct project-scoped system principal, so background work never impersonates an interactive user. Credentials are cached briefly by organization, principal, and lifecycle generation, with per-key singleflight, early independent replacement, bounded failure backoff, and no shared credential rotation. A rapid deprovision and reprovision therefore cannot reuse a credential from the old generation. An unexpired cached credential can bridge a temporary control-plane outage; an expired credential fails closed. The connection must include `sslmode=require`, and there is no stored-root fallback.
+Dynamic raw queries use the native Duckgres pgwire adapter. At physical connection acquisition, PostHog mints a short-lived organization-root-shaped service credential for a principal containing the project ID and stable PostHog user ID. Email addresses are never used. Schema discovery uses a distinct project-scoped system principal, so background work never impersonates an interactive user.
+
+PostHog application-encrypts credentials in shared Redis. The cache key is a hash of the organization, principal, and lifecycle generation, and the entry expires one minute before the credential. A per-key Redis lock lets query-django and Celery workers share one mint without making unrelated principals wait. Refresh always mints an independent credential and never rotates a cached credential ID. A rapid deprovision and reprovision therefore cannot reuse a credential from the old generation.
+
+Redis is the only credential cache. When Redis cannot be read, locked, or written, the request mints directly and does not retain a process-local copy. A lock wait is bounded to four seconds. After that, the request checks Redis once more and mints directly if the owner did not publish a credential. A valid cached credential can bridge a temporary control-plane outage until its refresh margin. After that, mint failure fails closed. The connection must include `sslmode=require`, and there is no stored-root fallback.
+
+The credential cache uses a dedicated Redis client with no command retries. `MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_CONNECT_TIMEOUT_SECONDS` and `MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_READ_TIMEOUT_SECONDS` both default to 0.5 seconds. Timeout and retry query parameters in `REDIS_URL` are ignored for this client, while authentication, database, TLS, and other Redis options remain intact. These settings do not change the shared Redis client's longer timeout for blocking operations.
Existing project readers retain their stored, project-scoped credential and native-adapter behavior. Existing static organization-login sources retain the PostgreSQL adapter and external-source access controls. Saved connection IDs continue to resolve according to the source's own credential mode even when that mode is not the chooser's preferred entry.
@@ -36,3 +42,5 @@ Dynamic source creation while the gate is enabled, query authentication, schema
If source setup fails after successful provision or onboarding, the versioned retry task uses the original team, organization, and generation. It is safe to retry. If the warehouse was deprovisioned or reprovisioned, the generation check turns the task into a no-op.
If deprovision reports that the control plane accepted deletion but local SQL connection state could not be updated, retry deprovision. PostHog checks authoritative status before changing local state. If source cleanup fails after local deactivation, the versioned cleanup task retries with the exact inactive generation.
+
+If Redis is unavailable, SQL editor queries and managed warehouse schema discovery continue by minting one credential per request. Restore Redis to resume cross-worker reuse. There is no process-local or Postgres credential cache to clear during recovery. Use `posthog_managed_warehouse_service_credential_cache_events_total` to compare cache hits, misses, invalid payloads, Redis errors, lock timeouts, store failures, and direct fallbacks. Its `outcome` label has no tenant or credential identifiers.
diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.py
index 66f70b531fde..f58ba0fa1ba2 100644
--- a/posthog/settings/base_variables.py
+++ b/posthog/settings/base_variables.py
@@ -79,6 +79,12 @@ DUCKGRES_PG_PORT: int = get_from_env("DUCKGRES_PG_PORT", 5432, type_cast=int)
MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED: bool = get_from_env(
"MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED", False, type_cast=str_to_bool
)
+MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_CONNECT_TIMEOUT_SECONDS: float = get_from_env(
+ "MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_CONNECT_TIMEOUT_SECONDS", 0.5, type_cast=float
+)
+MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_READ_TIMEOUT_SECONDS: float = get_from_env(
+ "MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_READ_TIMEOUT_SECONDS", 0.5, type_cast=float
+)
# Bulk deletion operations can be disabled during database migrations
DISABLE_BULK_DELETES: bool = get_from_env("DISABLE_BULK_DELETES", False, type_cast=str_to_bool)
diff --git a/products/managed_warehouse/backend/logic/sql_editor_credentials.py b/products/managed_warehouse/backend/logic/sql_editor_credentials.py
index e18486d350e3..d0db4b6df28e 100644
--- a/products/managed_warehouse/backend/logic/sql_editor_credentials.py
+++ b/products/managed_warehouse/backend/logic/sql_editor_credentials.py
@@ -1,18 +1,33 @@
from __future__ import annotations
-from collections import OrderedDict
+import hmac
+import json
+import math
+import hashlib
from collections.abc import Callable
-from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
-from threading import Condition, Lock
+from functools import lru_cache
+from typing import Literal
+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
from uuid import UUID
+from django.conf import settings
+
+import redis
+from cryptography.fernet import InvalidToken
+from prometheus_client import Counter
+from redis.backoff import NoBackoff
+from redis.retry import Retry
+
from posthog.dataclasses import frozen
+from posthog.helpers.encrypted_fields import EncryptedFieldMixin
+from posthog.redis import get_client
from products.managed_warehouse.backend.facade.contracts import (
ManagedWarehousePostgresConnection,
ManagedWarehouseSourceAuth,
ServiceCredential,
+ ServiceCredentialConnect,
)
from products.managed_warehouse.backend.service_credentials import ServiceCredentialUnavailable, mint_service_credential
from products.warehouse_sources.backend.facade.models import (
@@ -21,12 +36,70 @@ from products.warehouse_sources.backend.facade.models import (
)
SQL_EDITOR_CREDENTIAL_REFRESH_MARGIN = timedelta(minutes=1)
-SQL_EDITOR_CREDENTIAL_RETRY_BACKOFF = timedelta(seconds=5)
SQL_EDITOR_CREDENTIAL_MINT_TIMEOUT_SECONDS = 3
-SQL_EDITOR_CREDENTIAL_CACHE_SIZE = 512
+# The lease safely outlives the mint and bounded Redis operations. Contenders wait only four
+# seconds, so a dead owner cannot hold up a query for the full lease.
+SQL_EDITOR_CREDENTIAL_LOCK_TIMEOUT_SECONDS = 30
+SQL_EDITOR_CREDENTIAL_LOCK_WAIT_SECONDS = SQL_EDITOR_CREDENTIAL_MINT_TIMEOUT_SECONDS + 1
+SQL_EDITOR_CREDENTIAL_CACHE_KEY_VERSION = 2
+
+SERVICE_CREDENTIAL_CACHE_EVENTS = Counter(
+ "posthog_managed_warehouse_service_credential_cache_events_total",
+ "Managed warehouse service credential cache events by low-cardinality outcome.",
+ labelnames=["outcome"],
+)
+CredentialCacheOutcome = Literal[
+ "hit",
+ "miss",
+ "lock_timeout",
+ "invalid_payload",
+ "redis_error",
+ "store_failure",
+ "direct_fallback",
+]
CredentialMint = Callable[[str, int, str], ServiceCredential]
Clock = Callable[[], datetime]
+RedisClient = Callable[[], redis.Redis]
+
+_CREDENTIAL_CACHE_REDIS_URL_POLICY_OPTIONS = {
+ "retry",
+ "retry_on_error",
+ "retry_on_timeout",
+ "socket_connect_timeout",
+ "socket_timeout",
+ "timeout",
+}
+
+
+def _record_cache_event(outcome: CredentialCacheOutcome) -> None:
+ SERVICE_CREDENTIAL_CACHE_EVENTS.labels(outcome=outcome).inc()
+
+
+def _credential_cache_redis_url(redis_url: str) -> str:
+ parsed = urlsplit(redis_url)
+ query = urlencode(
+ [
+ (key, value)
+ for key, value in parse_qsl(parsed.query, keep_blank_values=True)
+ if key.lower() not in _CREDENTIAL_CACHE_REDIS_URL_POLICY_OPTIONS
+ ]
+ )
+ return urlunsplit((parsed.scheme, parsed.netloc, parsed.path, query, parsed.fragment))
+
+
+@lru_cache(maxsize=1)
+def _get_credential_cache_redis_client() -> redis.Redis:
+ if settings.TEST:
+ return get_client()
+ return redis.from_url(
+ _credential_cache_redis_url(settings.REDIS_URL),
+ db=0,
+ socket_connect_timeout=settings.MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_CONNECT_TIMEOUT_SECONDS,
+ socket_timeout=settings.MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_READ_TIMEOUT_SECONDS,
+ retry=Retry(NoBackoff(), 0),
+ retry_on_error=[],
+ )
def _utcnow() -> datetime:
@@ -42,37 +115,86 @@ def _mint_sql_editor_credential(organization_id: str, team_id: int, principal: s
)
-@dataclass(frozen=False)
-class _OrganizationCredentialState:
- condition: Condition = field(default_factory=Condition)
- credential: ServiceCredential | None = None
- refreshing: bool = False
- retry_after: datetime | None = None
- failure_category: str | None = None
- failure_message: str | None = None
- leases: int = 0
-
-
@frozen
class _CredentialCacheKey:
organization_id: str
principal: str
lifecycle_generation: int
+ def canonical_identity(self) -> str:
+ return json.dumps(
+ {
+ "lifecycle_generation": self.lifecycle_generation,
+ "organization_id": self.organization_id,
+ "principal": self.principal,
+ },
+ separators=(",", ":"),
+ sort_keys=True,
+ )
+
+ def redis_key(self) -> str:
+ digest = hashlib.sha256(self.canonical_identity().encode()).hexdigest()
+ return f"managed_warehouse:service_credential:v{SQL_EDITOR_CREDENTIAL_CACHE_KEY_VERSION}:{digest}"
+
+
+class _CredentialPayloadCodec:
+ def __init__(self) -> None:
+ self._cipher = EncryptedFieldMixin()
+
+ def encode(self, credential: ServiceCredential, cache_key: _CredentialCacheKey) -> str:
+ plaintext = json.dumps(
+ {
+ "cache_identity": cache_key.canonical_identity(),
+ "credential_id": credential.credential_id,
+ "credential_secret": credential.credential_secret,
+ "expires_at": credential.expires_at.isoformat(),
+ "connect": {
+ "host": credential.connect.host,
+ "port": credential.connect.port,
+ "database": credential.connect.database,
+ "sslmode": credential.connect.sslmode,
+ },
+ },
+ separators=(",", ":"),
+ )
+ return self._cipher.encrypt(plaintext)
-class ServiceCredentialCache:
+ def decode(self, payload: bytes | str, cache_key: _CredentialCacheKey) -> ServiceCredential | None:
+ try:
+ token = payload.decode() if isinstance(payload, bytes) else payload
+ raw = json.loads(self._cipher.decrypt(token))
+ identity = raw["cache_identity"]
+ if not isinstance(identity, str) or not hmac.compare_digest(identity, cache_key.canonical_identity()):
+ return None
+ connect = raw["connect"]
+ return ServiceCredential(
+ credential_id=raw["credential_id"],
+ credential_secret=raw["credential_secret"],
+ expires_at=datetime.fromisoformat(raw["expires_at"]),
+ connect=ServiceCredentialConnect(
+ host=connect["host"],
+ port=connect["port"],
+ database=connect["database"],
+ sslmode=connect["sslmode"],
+ ),
+ )
+ except (InvalidToken, UnicodeDecodeError, json.JSONDecodeError, KeyError, TypeError, ValueError):
+ return None
+
+
+class RedisServiceCredentialCache:
def __init__(
self,
*,
mint: CredentialMint = _mint_sql_editor_credential,
now: Clock = _utcnow,
- maxsize: int = SQL_EDITOR_CREDENTIAL_CACHE_SIZE,
+ redis_client: RedisClient = _get_credential_cache_redis_client,
+ codec: _CredentialPayloadCodec | None = None,
) -> None:
self._mint = mint
self._now = now
- self._maxsize = maxsize
- self._states: OrderedDict[_CredentialCacheKey, _OrganizationCredentialState] = OrderedDict()
- self._states_lock = Lock()
+ self._redis_client = redis_client
+ self._codec = codec or _CredentialPayloadCodec()
def get(
self,
@@ -87,132 +209,138 @@ class ServiceCredentialCache:
principal=principal,
lifecycle_generation=lifecycle_generation,
)
- state = self._state_for(cache_key)
+ redis_key = cache_key.redis_key()
+
try:
- return self._get_from_state(state, cache_key, team_id)
- finally:
- self._release_state(cache_key, state)
+ client = self._redis_client()
+ cached = self._load_cached(client, redis_key, cache_key)
+ except Exception:
+ return self._mint_fallback(cache_key, team_id, outcome="redis_error")
+ if cached is not None:
+ return cached
- def _get_from_state(
- self, state: _OrganizationCredentialState, cache_key: _CredentialCacheKey, team_id: int
- ) -> ServiceCredential:
- with state.condition:
- now = self._now()
- cached = state.credential
- if cached is not None and cached.expires_at > now + SQL_EDITOR_CREDENTIAL_REFRESH_MARGIN:
+ lock = None
+ acquired = False
+ try:
+ lock = client.lock(
+ f"{redis_key}:lock",
+ timeout=SQL_EDITOR_CREDENTIAL_LOCK_TIMEOUT_SECONDS,
+ blocking_timeout=SQL_EDITOR_CREDENTIAL_LOCK_WAIT_SECONDS,
+ )
+ acquired = lock.acquire()
+ except Exception:
+ return self._mint_fallback(cache_key, team_id, outcome="redis_error")
+
+ if not acquired:
+ _record_cache_event("lock_timeout")
+ try:
+ cached = self._load_cached(client, redis_key, cache_key)
+ except Exception:
+ return self._mint_fallback(cache_key, team_id, outcome="redis_error")
+ if cached is not None:
+ return cached
+ _record_cache_event("direct_fallback")
+ return self._mint_direct(cache_key, team_id)
+
+ try:
+ try:
+ cached = self._load_cached(client, redis_key, cache_key)
+ except Exception:
+ return self._mint_fallback(cache_key, team_id, outcome="redis_error")
+ if cached is not None:
return cached
- if state.retry_after is not None and now < state.retry_after:
- if cached is not None and cached.expires_at > now:
- return cached
- raise self._failure_from_state(state, "service credential mint is backed off")
-
- if state.refreshing:
- if cached is not None and cached.expires_at > now:
- return cached
- refresh_finished = state.condition.wait_for(
- lambda: not state.refreshing,
- timeout=SQL_EDITOR_CREDENTIAL_MINT_TIMEOUT_SECONDS + 1,
- )
- if not refresh_finished:
- raise ServiceCredentialUnavailable("service credential mint timed out")
- now = self._now()
- cached = state.credential
- if cached is not None and cached.expires_at > now:
- return cached
- raise self._failure_from_state(state, "service credential mint failed")
-
- state.refreshing = True
+ minted = self._mint_direct(cache_key, team_id)
+ ttl_seconds = math.floor(
+ (minted.expires_at - self._now() - SQL_EDITOR_CREDENTIAL_REFRESH_MARGIN).total_seconds()
+ )
+ if ttl_seconds <= 0:
+ return minted
+ try:
+ stored = client.set(redis_key, self._codec.encode(minted, cache_key), ex=ttl_seconds)
+ except Exception:
+ _record_cache_event("store_failure")
+ _record_cache_event("direct_fallback")
+ return minted
+ if not stored:
+ _record_cache_event("store_failure")
+ _record_cache_event("direct_fallback")
+ return minted
+ return minted
+ finally:
+ if lock is not None:
+ try:
+ lock.release()
+ except Exception:
+ _record_cache_event("redis_error")
+
+ def _load_cached(
+ self, client: redis.Redis, redis_key: str, cache_key: _CredentialCacheKey
+ ) -> ServiceCredential | None:
+ payload = client.get(redis_key)
+ if payload is None:
+ _record_cache_event("miss")
+ return None
+ credential = self._codec.decode(payload, cache_key)
+ if credential is None:
+ _record_cache_event("invalid_payload")
+ return None
+ try:
+ self._validate_credential(credential)
+ except (ServiceCredentialUnavailable, AttributeError, TypeError):
+ _record_cache_event("invalid_payload")
+ return None
+ if credential.expires_at <= self._now() + SQL_EDITOR_CREDENTIAL_REFRESH_MARGIN:
+ _record_cache_event("miss")
+ return None
+ _record_cache_event("hit")
+ return credential
+
+ def _mint_fallback(
+ self,
+ cache_key: _CredentialCacheKey,
+ team_id: int,
+ *,
+ outcome: Literal["redis_error"],
+ ) -> ServiceCredential:
+ _record_cache_event(outcome)
+ _record_cache_event("direct_fallback")
+ return self._mint_direct(cache_key, team_id)
+ def _mint_direct(self, cache_key: _CredentialCacheKey, team_id: int) -> ServiceCredential:
try:
minted = self._mint(cache_key.organization_id, team_id, cache_key.principal)
- self._validate_minted_credential(minted)
+ self._validate_credential(minted)
+ return minted
except ServiceCredentialUnavailable:
- with state.condition:
- state.refreshing = False
- state.failure_category = "unavailable"
- # The control-plane exception may have parsed response data in its
- # traceback or message. Retain only a fixed, public-safe summary.
- state.failure_message = "service credential mint unavailable"
- state.retry_after = self._now() + SQL_EDITOR_CREDENTIAL_RETRY_BACKOFF
- cached = state.credential
- state.condition.notify_all()
- if cached is not None and cached.expires_at > self._now():
- return cached
- raise ServiceCredentialUnavailable(state.failure_message) from None
+ raise ServiceCredentialUnavailable("service credential mint unavailable") from None
except Exception:
- with state.condition:
- state.refreshing = False
- state.failure_category = "unexpected"
- state.failure_message = "service credential mint failed unexpectedly"
- state.retry_after = self._now() + SQL_EDITOR_CREDENTIAL_RETRY_BACKOFF
- cached = state.credential
- state.condition.notify_all()
- if cached is not None and cached.expires_at > self._now():
- return cached
- raise ServiceCredentialUnavailable(state.failure_message) from None
- except BaseException:
- with state.condition:
- state.refreshing = False
- state.failure_category = "interrupted"
- state.failure_message = "service credential mint was interrupted"
- state.retry_after = self._now() + SQL_EDITOR_CREDENTIAL_RETRY_BACKOFF
- state.condition.notify_all()
- raise
-
- with state.condition:
- state.credential = minted
- state.refreshing = False
- state.retry_after = None
- state.failure_category = None
- state.failure_message = None
- state.condition.notify_all()
- return minted
-
- def _validate_minted_credential(self, credential: ServiceCredential) -> None:
- if credential.expires_at <= self._now():
+ raise ServiceCredentialUnavailable("service credential mint failed unexpectedly") from None
+
+ def _validate_credential(self, credential: ServiceCredential) -> None:
+ now = self._now()
+ if credential.expires_at.tzinfo is None or credential.expires_at.utcoffset() is None:
+ raise ServiceCredentialUnavailable("service credential mint returned an invalid expiry")
+ if credential.expires_at <= now:
raise ServiceCredentialUnavailable("service credential mint returned an expired credential")
if (
- not credential.connect.host
- or credential.connect.port <= 0
+ not isinstance(credential.credential_id, str)
+ or not credential.credential_id
+ or not isinstance(credential.credential_secret, str)
+ or not credential.credential_secret
+ or not isinstance(credential.connect.host, str)
+ or not credential.connect.host
+ or isinstance(credential.connect.port, bool)
+ or not isinstance(credential.connect.port, int)
+ or not 1 <= credential.connect.port <= 65535
+ or not isinstance(credential.connect.database, str)
or not credential.connect.database
or credential.connect.sslmode != "require"
):
raise ServiceCredentialUnavailable("SQL editor service credential requires a complete secure sslmode")
- @staticmethod
- def _failure_from_state(state: _OrganizationCredentialState, fallback: str) -> ServiceCredentialUnavailable:
- return ServiceCredentialUnavailable(state.failure_message or fallback)
-
- def _state_for(self, cache_key: _CredentialCacheKey) -> _OrganizationCredentialState:
- with self._states_lock:
- state = self._states.get(cache_key)
- if state is not None:
- self._states.move_to_end(cache_key)
- state.leases += 1
- return state
-
- if len(self._states) >= self._maxsize:
- eviction_key: _CredentialCacheKey | None = None
- for existing_key, existing_state in self._states.items():
- if existing_state.leases == 0:
- eviction_key = existing_key
- break
- if eviction_key is None:
- raise ServiceCredentialUnavailable("service credential cache is at capacity")
- del self._states[eviction_key]
-
- state = _OrganizationCredentialState(leases=1)
- self._states[cache_key] = state
- return state
-
- def _release_state(self, cache_key: _CredentialCacheKey, state: _OrganizationCredentialState) -> None:
- with self._states_lock:
- if self._states.get(cache_key) is state:
- state.leases -= 1
-
-_service_credential_cache = ServiceCredentialCache()
+_service_credential_cache = RedisServiceCredentialCache()
def _is_dynamic_managed_warehouse_source(source_auth: ManagedWarehouseSourceAuth) -> bool:
@@ -229,7 +357,7 @@ def resolve_managed_warehouse_postgres_connection(
organization_id: str | UUID,
team_id: int,
principal: str,
- credential_cache: ServiceCredentialCache | None = None,
+ credential_cache: RedisServiceCredentialCache | None = None,
) -> ManagedWarehousePostgresConnection | None:
if not _is_dynamic_managed_warehouse_source(source_auth):
return None
diff --git a/products/managed_warehouse/backend/tests/test_sql_editor_credentials.py b/products/managed_warehouse/backend/tests/test_sql_editor_credentials.py
index 83fcadb688a2..8b7a43367bd9 100644
--- a/products/managed_warehouse/backend/tests/test_sql_editor_credentials.py
+++ b/products/managed_warehouse/backend/tests/test_sql_editor_credentials.py
@@ -3,7 +3,12 @@ from datetime import UTC, datetime, timedelta
from threading import Event, Lock
import pytest
-from unittest.mock import patch
+from unittest.mock import Mock, patch
+
+from django.test import override_settings
+
+import fakeredis
+from prometheus_client import REGISTRY
from products.managed_warehouse.backend.facade.contracts import (
ManagedWarehouseSourceAuth,
@@ -13,7 +18,7 @@ from products.managed_warehouse.backend.facade.contracts import (
from products.managed_warehouse.backend.logic import sql_editor_credentials
from products.managed_warehouse.backend.logic.sql_editor_credentials import (
MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
- ServiceCredentialCache,
+ RedisServiceCredentialCache,
resolve_managed_warehouse_postgres_connection,
)
from products.managed_warehouse.backend.service_credentials import ServiceCredentialUnavailable
@@ -28,7 +33,7 @@ def _credential(credential_id: str, expires_at: datetime) -> ServiceCredential:
credential_secret=f"secret-{credential_id}",
expires_at=expires_at,
connect=ServiceCredentialConnect(
- host="warehouse.dw.us.postwh.com",
+ host="warehouse.example.com",
port=5432,
database="ducklake",
sslmode="require",
@@ -36,9 +41,36 @@ def _credential(credential_id: str, expires_at: datetime) -> ServiceCredential:
)
-def test_concurrent_callers_share_one_in_flight_mint() -> None:
+def _redis() -> fakeredis.FakeRedis:
+ return fakeredis.FakeRedis()
+
+
+def _cache(
+ client: fakeredis.FakeRedis,
+ *,
+ mint: sql_editor_credentials.CredentialMint,
+ now: sql_editor_credentials.Clock,
+) -> RedisServiceCredentialCache:
+ return RedisServiceCredentialCache(redis_client=lambda: client, mint=mint, now=now)
+
+
+def _cache_metric(outcome: str) -> float:
+ return (
+ REGISTRY.get_sample_value(
+ "posthog_managed_warehouse_service_credential_cache_events_total",
+ {"outcome": outcome},
+ )
+ or 0
+ )
+
+
+def test_cache_instances_share_one_in_flight_mint() -> None:
now = datetime(2026, 1, 1, tzinfo=UTC)
+ server = fakeredis.FakeServer()
+ owner_client = fakeredis.FakeRedis(server=server)
+ follower_client = fakeredis.FakeRedis(server=server)
mint_started = Event()
+ follower_failed_lock_attempt = Event()
allow_mint = Event()
mint_count = 0
count_lock = Lock()
@@ -51,38 +83,126 @@ def test_concurrent_callers_share_one_in_flight_mint() -> None:
assert allow_mint.wait(timeout=5)
return _credential("svc_one", now + timedelta(minutes=15))
- cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+ first_cache = _cache(owner_client, mint=mint, now=lambda: now)
+ second_cache = _cache(follower_client, mint=mint, now=lambda: now)
+ original_set = follower_client.set
- with ThreadPoolExecutor(max_workers=2) as executor:
- first = executor.submit(cache.get, "org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
- assert mint_started.wait(timeout=5)
- second = executor.submit(cache.get, "org-1", 2, principal=SQL_EDITOR_PRINCIPAL)
- allow_mint.set()
+ def signaling_set(name, *args, **kwargs):
+ result = original_set(name, *args, **kwargs)
+ if str(name).endswith(":lock") and kwargs.get("nx") and not result:
+ follower_failed_lock_attempt.set()
+ return result
+
+ with patch.object(follower_client, "set", side_effect=signaling_set):
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ first = executor.submit(first_cache.get, "org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+ assert mint_started.wait(timeout=5)
+ second = executor.submit(second_cache.get, "org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+ assert follower_failed_lock_attempt.wait(timeout=5)
+ allow_mint.set()
assert first.result().credential_id == "svc_one"
assert second.result().credential_id == "svc_one"
assert mint_count == 1
-def test_principals_never_share_cached_credentials_within_an_organization() -> None:
+ "target",
+ [
+ ("org-2", SQL_EDITOR_PRINCIPAL, 1),
+ ("org-1", "posthog:sql-editor:team:1:user:2", 1),
+ ("org-1", SQL_EDITOR_PRINCIPAL, 2),
+ ],
+)
+def test_encrypted_payload_cannot_be_transplanted_between_cache_identities(target) -> None:
now = datetime(2026, 1, 1, tzinfo=UTC)
- minted_for: list[str] = []
+ client = _redis()
+ minted: list[str] = []
- def mint(_organization_id: str, _team_id: int, principal: str) -> ServiceCredential:
- minted_for.append(principal)
- return _credential(f"svc_{len(minted_for)}", now + timedelta(minutes=15))
+ def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ credential_id = f"svc_{len(minted) + 1}"
+ minted.append(credential_id)
+ return _credential(credential_id, now + timedelta(minutes=15))
+
+ cache = _cache(client, mint=mint, now=lambda: now)
+ cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL, lifecycle_generation=1)
+ source_key = client.keys("*")[0]
+ source_payload = client.get(source_key)
+ assert source_payload is not None
+ cache.get(target[0], 1, principal=target[1], lifecycle_generation=target[2])
+ target_key = next(key for key in client.keys("*") if key != source_key)
+ client.set(target_key, source_payload, ex=60)
- cache = ServiceCredentialCache(mint=mint, now=lambda: now)
- user_one = "posthog:sql-editor:team:1:user:1"
- user_two = "posthog:sql-editor:team:1:user:2"
+ invalid_before = _cache_metric("invalid_payload")
+ replacement = cache.get(target[0], 1, principal=target[1], lifecycle_generation=target[2])
- assert cache.get("org-1", 1, principal=user_one).credential_id == "svc_1"
- assert cache.get("org-1", 1, principal=user_two).credential_id == "svc_2"
- assert cache.get("org-1", 1, principal=user_one).credential_id == "svc_1"
- assert minted_for == [user_one, user_two]
+ assert replacement.credential_id == "svc_3"
+ assert minted == ["svc_1", "svc_2", "svc_3"]
+ assert _cache_metric("invalid_payload") == invalid_before + 2
-def test_lifecycle_generations_never_share_cached_credentials_for_the_same_principal() -> None:
+@override_settings(
+ TEST=False,
+ REDIS_URL="redis://cache.example.com:6379",
+ MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_CONNECT_TIMEOUT_SECONDS=0.25,
+ MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_READ_TIMEOUT_SECONDS=0.5,
+)
+def test_dedicated_redis_client_uses_short_timeouts_without_retries() -> None:
+ sql_editor_credentials._get_credential_cache_redis_client.cache_clear()
+ try:
+ with patch.object(sql_editor_credentials.redis, "from_url") as from_url:
+ sql_editor_credentials._get_credential_cache_redis_client()
+
+ kwargs = from_url.call_args.kwargs
+ assert from_url.call_args.args == ("redis://cache.example.com:6379",)
+ assert kwargs["socket_connect_timeout"] == 0.25
+ assert kwargs["socket_timeout"] == 0.5
+ assert kwargs["retry_on_error"] == []
+ assert kwargs["retry"]._retries == 0
+ finally:
+ sql_editor_credentials._get_credential_cache_redis_client.cache_clear()
+
+
+@override_settings(
+ TEST=False,
+ REDIS_URL=(
+ "redis://cache-user:[email protected]:6379/3"
+ "?socket_timeout=99&socket_connect_timeout=98&timeout=97"
+ "&retry_on_timeout=true&retry_on_error=TimeoutError&retry=unsafe&health_check_interval=7"
+ ),
+ MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_CONNECT_TIMEOUT_SECONDS=0.5,
+ MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_READ_TIMEOUT_SECONDS=0.5,
+)
+def test_dedicated_redis_client_url_cannot_override_timeout_or_retry_policy() -> None:
+ sql_editor_credentials._get_credential_cache_redis_client.cache_clear()
+ try:
+ client = sql_editor_credentials._get_credential_cache_redis_client()
+ connection_kwargs = client.connection_pool.connection_kwargs
+
+ assert connection_kwargs["socket_connect_timeout"] == 0.5
+ assert connection_kwargs["socket_timeout"] == 0.5
+ assert connection_kwargs["retry_on_error"] == []
+ assert connection_kwargs["retry"]._retries == 0
+ assert connection_kwargs["username"] == "cache-user"
+ assert connection_kwargs["password"] == "cache-password"
+ assert connection_kwargs["db"] == 3
+ assert connection_kwargs["health_check_interval"] == 7
+ finally:
+ sql_editor_credentials._get_credential_cache_redis_client.cache_clear()
+
+
+ "first,second",
+ [
+ (("org-1", SQL_EDITOR_PRINCIPAL, 1), ("org-2", SQL_EDITOR_PRINCIPAL, 1)),
+ (
+ ("org-1", "posthog:sql-editor:team:1:user:1", 1),
+ ("org-1", "posthog:sql-editor:team:1:user:2", 1),
+ ),
+ (("org-1", SQL_EDITOR_PRINCIPAL, 1), ("org-1", SQL_EDITOR_PRINCIPAL, 2)),
+ ],
+)
+def test_organization_principal_and_generation_have_independent_credentials(first, second) -> None:
now = datetime(2026, 1, 1, tzinfo=UTC)
minted: list[str] = []
@@ -91,274 +211,326 @@ def test_lifecycle_generations_never_share_cached_credentials_for_the_same_princ
minted.append(credential_id)
return _credential(credential_id, now + timedelta(minutes=15))
- cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+ cache = _cache(_redis(), mint=mint, now=lambda: now)
- first = cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL, lifecycle_generation=3)
- same_generation = cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL, lifecycle_generation=3)
- reprovisioned = cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL, lifecycle_generation=5)
+ first_credential = cache.get(first[0], 1, principal=first[1], lifecycle_generation=first[2])
+ second_credential = cache.get(second[0], 1, principal=second[1], lifecycle_generation=second[2])
+ hits_before = _cache_metric("hit")
+ reused_first = cache.get(first[0], 1, principal=first[1], lifecycle_generation=first[2])
- assert first.credential_id == "svc_1"
- assert same_generation.credential_id == "svc_1"
- assert reprovisioned.credential_id == "svc_2"
+ assert first_credential.credential_id == "svc_1"
+ assert second_credential.credential_id == "svc_2"
+ assert reused_first.credential_id == "svc_1"
assert minted == ["svc_1", "svc_2"]
+ assert _cache_metric("hit") == hits_before + 1
-def test_replaces_a_credential_before_expiry_with_an_independent_mint() -> None:
+def test_mint_for_one_key_does_not_block_another_key() -> None:
now = datetime(2026, 1, 1, tzinfo=UTC)
- minted = [
- _credential("svc_old", now + timedelta(minutes=2)),
- _credential("svc_new", now + timedelta(minutes=15)),
- ]
+ first_started = Event()
+ release_first = Event()
- cache = ServiceCredentialCache(mint=lambda _organization_id, _team_id, _principal: minted.pop(0), now=lambda: now)
-
- assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_old"
- now += timedelta(seconds=61)
- assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_new"
- assert minted == []
+ def mint(organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ if organization_id == "org-1":
+ first_started.set()
+ assert release_first.wait(timeout=5)
+ return _credential(f"svc_{organization_id}", now + timedelta(minutes=15))
+ client = _redis()
+ first_cache = _cache(client, mint=mint, now=lambda: now)
+ second_cache = _cache(client, mint=mint, now=lambda: now)
-def test_uses_an_unexpired_cached_credential_during_a_mint_outage_but_fails_after_expiry() -> None:
- now = datetime(2026, 1, 1, tzinfo=UTC)
- original = _credential("svc_old", now + timedelta(minutes=2))
- mint_count = 0
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ first = executor.submit(first_cache.get, "org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+ assert first_started.wait(timeout=5)
+ second = executor.submit(second_cache.get, "org-2", 2, principal=SQL_EDITOR_PRINCIPAL)
+ assert second.result(timeout=1).credential_id == "svc_org-2"
+ release_first.set()
- def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
- nonlocal mint_count
- mint_count += 1
- if mint_count == 1:
- return original
- raise ServiceCredentialUnavailable("control plane unavailable")
+ assert first.result().credential_id == "svc_org-1"
- cache = ServiceCredentialCache(mint=mint, now=lambda: now)
- assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
- now += timedelta(seconds=61)
- assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
- now += timedelta(seconds=60)
- with pytest.raises(ServiceCredentialUnavailable, match="service credential mint unavailable"):
- cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+def test_cached_payload_is_encrypted_and_expires_before_the_credential() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ client = _redis()
+ cache = _cache(
+ client,
+ mint=lambda _organization_id, _team_id, _principal: _credential("svc_visible_id", now + timedelta(minutes=15)),
+ now=lambda: now,
+ )
+ misses_before = _cache_metric("miss")
+ result = cache.get("org-sensitive", 1, principal=SQL_EDITOR_PRINCIPAL, lifecycle_generation=7)
-def test_failed_early_replacement_is_backed_off_while_cached_credential_remains_valid() -> None:
- now = datetime(2026, 1, 1, tzinfo=UTC)
- original = _credential("svc_old", now + timedelta(minutes=2))
- mint_count = 0
+ assert result.credential_id == "svc_visible_id"
+ keys = client.keys("*")
+ assert len(keys) == 1
+ payload = client.get(keys[0])
+ assert payload is not None
+ redis_material = b" ".join([*keys, payload])
+ assert b"org-sensitive" not in redis_material
+ assert SQL_EDITOR_PRINCIPAL.encode() not in redis_material
+ assert b"secret-svc_visible_id" not in redis_material
+ assert b"svc_visible_id" not in redis_material
+ assert client.ttl(keys[0]) == 14 * 60
+ assert _cache_metric("miss") == misses_before + 2
- def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
- nonlocal mint_count
- mint_count += 1
- if mint_count == 1:
- return original
- raise ServiceCredentialUnavailable("control plane unavailable")
- cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+def test_refresh_margin_replaces_with_a_new_independent_credential() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ minted = [
+ _credential("svc_old", now + timedelta(minutes=2)),
+ _credential("svc_new", now + timedelta(minutes=15)),
+ ]
+ cache = _cache(
+ _redis(),
+ mint=lambda _organization_id, _team_id, _principal: minted.pop(0),
+ now=lambda: now,
+ )
- assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_old"
now += timedelta(seconds=61)
- assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
- assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
- assert mint_count == 2
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_new"
+ assert minted == []
-def test_unexpected_early_replacement_failure_serves_and_backs_off_an_unexpired_credential() -> None:
+def test_malformed_cached_payload_is_replaced() -> None:
now = datetime(2026, 1, 1, tzinfo=UTC)
- original = _credential("svc_old", now + timedelta(minutes=2))
- mint_count = 0
-
- def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
- nonlocal mint_count
- mint_count += 1
- if mint_count == 1:
- return original
- raise RuntimeError("unexpected control-plane client failure")
+ client = _redis()
+ minted = [
+ _credential("svc_first", now + timedelta(minutes=15)),
+ _credential("svc_recovered", now + timedelta(minutes=15)),
+ ]
+ first_cache = _cache(
+ client,
+ mint=lambda _organization_id, _team_id, _principal: minted.pop(0),
+ now=lambda: now,
+ )
+ first_cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+ cache_key = client.keys("*")[0]
+ client.set(cache_key, b"not-an-encrypted-credential", ex=60)
+ second_cache = _cache(
+ client,
+ mint=lambda _organization_id, _team_id, _principal: minted.pop(0),
+ now=lambda: now,
+ )
- cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+ recovered = second_cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
- assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
- now += timedelta(seconds=61)
- assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
- assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
- assert mint_count == 2
+ assert recovered.credential_id == "svc_recovered"
+ assert minted == []
+ assert client.get(cache_key) != b"not-an-encrypted-credential"
-def test_stalled_refresh_for_one_organization_does_not_block_another() -> None:
+ "redis_error",
+ [ConnectionError("redis unavailable"), sql_editor_credentials.redis.exceptions.TimeoutError("redis timed out")],
+)
+def test_redis_get_failure_mints_each_time_without_local_reuse(redis_error: Exception) -> None:
now = datetime(2026, 1, 1, tzinfo=UTC)
- org_one_started = Event()
- release_org_one = Event()
-
- def mint(organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
- if organization_id == "org-1":
- org_one_started.set()
- assert release_org_one.wait(timeout=5)
- return _credential(f"svc_{organization_id}", now + timedelta(minutes=15))
+ minted: list[str] = []
- cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+ def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ credential_id = f"svc_{len(minted) + 1}"
+ minted.append(credential_id)
+ return _credential(credential_id, now + timedelta(minutes=15))
- with ThreadPoolExecutor(max_workers=2) as executor:
- org_one = executor.submit(cache.get, "org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
- assert org_one_started.wait(timeout=5)
- org_two = executor.submit(cache.get, "org-2", 2, principal=SQL_EDITOR_PRINCIPAL)
- assert org_two.result(timeout=1).credential_id == "svc_org-2"
- release_org_one.set()
+ client = _redis()
+ cache = _cache(client, mint=mint, now=lambda: now)
+ redis_errors_before = _cache_metric("redis_error")
+ direct_fallbacks_before = _cache_metric("direct_fallback")
- assert org_one.result().credential_id == "svc_org-1"
+ with patch.object(client, "get", side_effect=redis_error):
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_1"
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_2"
+ assert minted == ["svc_1", "svc_2"]
+ assert client.keys("*") == []
+ assert _cache_metric("redis_error") == redis_errors_before + 2
+ assert _cache_metric("direct_fallback") == direct_fallbacks_before + 2
-def test_per_organization_singleflight_state_is_bounded() -> None:
+def test_redis_client_failure_mints_without_caching() -> None:
now = datetime(2026, 1, 1, tzinfo=UTC)
- mint_count = 0
+ mint = Mock(return_value=_credential("svc_direct", now + timedelta(minutes=15)))
+ cache = RedisServiceCredentialCache(
+ redis_client=Mock(side_effect=ConnectionError("redis unavailable")),
+ mint=mint,
+ now=lambda: now,
+ )
- def mint(organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
- nonlocal mint_count
- mint_count += 1
- return _credential(f"svc_{organization_id}_{mint_count}", now + timedelta(minutes=15))
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_direct"
+ mint.assert_called_once()
- cache = ServiceCredentialCache(mint=mint, now=lambda: now, maxsize=1)
- cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
- cache.get("org-2", 2, principal=SQL_EDITOR_PRINCIPAL)
- cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
[email protected]("failure_point", ["lock", "acquire"])
+def test_redis_lock_failure_mints_without_caching(failure_point: str) -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ client = _redis()
+ if failure_point == "lock":
+ lock_patch = patch.object(client, "lock", side_effect=ConnectionError("redis unavailable"))
+ else:
+ lock = Mock()
+ lock.acquire.side_effect = ConnectionError("redis unavailable")
+ lock_patch = patch.object(client, "lock", return_value=lock)
+ cache = _cache(
+ client,
+ mint=lambda _organization_id, _team_id, _principal: _credential("svc_direct", now + timedelta(minutes=15)),
+ now=lambda: now,
+ )
- assert mint_count == 3
+ with lock_patch:
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_direct"
+ assert client.keys("*") == []
-def test_in_use_state_cannot_be_evicted_and_is_evictable_after_release() -> None:
+def test_redis_set_failure_returns_the_mint_without_caching() -> None:
now = datetime(2026, 1, 1, tzinfo=UTC)
- state_leased = Event()
- release_state = Event()
- mint_counts: dict[str, int] = {}
+ client = _redis()
+ original_set = client.set
- def mint(organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
- mint_counts[organization_id] = mint_counts.get(organization_id, 0) + 1
- return _credential(f"svc_{organization_id}", now + timedelta(minutes=15))
-
- cache = ServiceCredentialCache(mint=mint, now=lambda: now, maxsize=1)
- original_state_for = cache._state_for
- first_org_one_lookup = True
-
- def pausing_state_for(cache_key: sql_editor_credentials._CredentialCacheKey):
- nonlocal first_org_one_lookup
- state = original_state_for(cache_key)
- if (
- cache_key.organization_id == "org-1"
- and cache_key.principal == SQL_EDITOR_PRINCIPAL
- and cache_key.lifecycle_generation == 0
- and first_org_one_lookup
- ):
- first_org_one_lookup = False
- state_leased.set()
- assert release_state.wait(timeout=5)
- return state
-
- with patch.object(cache, "_state_for", side_effect=pausing_state_for):
- with ThreadPoolExecutor(max_workers=2) as executor:
- org_one = executor.submit(cache.get, "org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
- assert state_leased.wait(timeout=5)
- with pytest.raises(ServiceCredentialUnavailable, match="at capacity"):
- cache.get("org-2", 2, principal=SQL_EDITOR_PRINCIPAL)
- release_state.set()
- assert org_one.result(timeout=5).credential_id == "svc_org-1"
+ def fail_cache_set(name, *args, **kwargs):
+ if str(name).endswith(":lock"):
+ return original_set(name, *args, **kwargs)
+ raise ConnectionError("redis unavailable")
- assert cache.get("org-2", 2, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_org-2"
+ cache = _cache(
+ client,
+ mint=lambda _organization_id, _team_id, _principal: _credential("svc_direct", now + timedelta(minutes=15)),
+ now=lambda: now,
+ )
+ store_failures_before = _cache_metric("store_failure")
+ direct_fallbacks_before = _cache_metric("direct_fallback")
- assert mint_counts == {"org-1": 1, "org-2": 1}
+ with patch.object(client, "set", side_effect=fail_cache_set):
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_direct"
+ assert client.keys("*") == []
+ assert _cache_metric("store_failure") == store_failures_before + 1
+ assert _cache_metric("direct_fallback") == direct_fallbacks_before + 1
-def test_sql_editor_mint_uses_a_short_request_timeout() -> None:
+def test_redis_release_failure_does_not_fail_the_minted_credential() -> None:
now = datetime(2026, 1, 1, tzinfo=UTC)
- with patch(
- "products.managed_warehouse.backend.logic.sql_editor_credentials.mint_service_credential",
- return_value=_credential("svc_one", now + timedelta(minutes=15)),
- ) as mint:
- sql_editor_credentials._mint_sql_editor_credential("org-1", 1, SQL_EDITOR_PRINCIPAL)
+ client = _redis()
+ lock = Mock()
+ lock.acquire.return_value = True
+ lock.release.side_effect = ConnectionError("redis unavailable")
+ cache = _cache(
+ client,
+ mint=lambda _organization_id, _team_id, _principal: _credential("svc_direct", now + timedelta(minutes=15)),
+ now=lambda: now,
+ )
+ redis_errors_before = _cache_metric("redis_error")
- assert mint.call_args.kwargs["timeout_seconds"] == 3
- assert mint.call_args.kwargs["principal"] == SQL_EDITOR_PRINCIPAL
+ with patch.object(client, "lock", return_value=lock):
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_direct"
+ assert len(client.keys("*")) == 1
+ assert _cache_metric("redis_error") == redis_errors_before + 1
-def test_does_not_return_a_credential_that_expires_during_a_failed_replacement() -> None:
+def test_lock_timeout_after_an_owner_crash_mints_without_caching() -> None:
now = datetime(2026, 1, 1, tzinfo=UTC)
- original = _credential("svc_old", now + timedelta(minutes=2))
- mint_count = 0
+ client = _redis()
+ lock = Mock()
+ lock.acquire.return_value = False
+ minted: list[str] = []
def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
- nonlocal mint_count, now
- mint_count += 1
- if mint_count == 1:
- return original
- now += timedelta(minutes=1)
- raise ServiceCredentialUnavailable("control plane unavailable")
-
- cache = ServiceCredentialCache(mint=mint, now=lambda: now)
-
- assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
- now += timedelta(seconds=61)
- with pytest.raises(ServiceCredentialUnavailable, match="service credential mint unavailable"):
- cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
-
-
-def test_failure_state_does_not_retain_exception_tracebacks_or_secret_bearing_locals() -> None:
- def malformed(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
- malformed_payload = {"credential_secret": "must-not-remain-reachable"}
- assert malformed_payload
- raise ServiceCredentialUnavailable("malformed control-plane response: must-not-remain-reachable")
-
- cache = ServiceCredentialCache(mint=malformed)
+ credential_id = f"svc_{len(minted) + 1}"
+ minted.append(credential_id)
+ return _credential(credential_id, now + timedelta(minutes=15))
- with pytest.raises(ServiceCredentialUnavailable, match="service credential mint unavailable"):
- cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+ cache = _cache(client, mint=mint, now=lambda: now)
+ lock_timeouts_before = _cache_metric("lock_timeout")
+ direct_fallbacks_before = _cache_metric("direct_fallback")
- state = next(iter(cache._states.values()))
- assert not any(isinstance(value, BaseException) for value in vars(state).values())
- assert "must-not-remain-reachable" not in repr(vars(state))
+ with patch.object(client, "lock", return_value=lock):
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_1"
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_2"
+ assert client.keys("*") == []
+ assert minted == ["svc_1", "svc_2"]
+ assert _cache_metric("lock_timeout") == lock_timeouts_before + 2
+ assert _cache_metric("direct_fallback") == direct_fallbacks_before + 2
-def test_unexpected_refresh_replaces_stale_failure_state_and_is_backed_off() -> None:
+def test_lock_timeout_records_contention_when_the_owner_published_a_credential() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ client = _redis()
+ mint = Mock(return_value=_credential("svc_shared", now + timedelta(minutes=15)))
+ cache = _cache(client, mint=mint, now=lambda: now)
+ cached = cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+ cache_key = client.keys("*")[0]
+ payload = client.get(cache_key)
+ assert payload is not None
+ lock = Mock()
+ lock.acquire.return_value = False
+ lock_timeouts_before = _cache_metric("lock_timeout")
+ hits_before = _cache_metric("hit")
+ direct_fallbacks_before = _cache_metric("direct_fallback")
+
+ with (
+ patch.object(client, "get", side_effect=[None, payload]),
+ patch.object(client, "lock", return_value=lock),
+ ):
+ result = cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+
+ assert result.credential_id == cached.credential_id
+ mint.assert_called_once()
+ assert _cache_metric("lock_timeout") == lock_timeouts_before + 1
+ assert _cache_metric("hit") == hits_before + 1
+ assert _cache_metric("direct_fallback") == direct_fallbacks_before
+
+
+def test_cached_credential_is_not_used_after_redis_becomes_unavailable() -> None:
now = datetime(2026, 1, 1, tzinfo=UTC)
- failures = [
- ServiceCredentialUnavailable("old unavailable failure"),
- RuntimeError("new unexpected failure"),
+ client = _redis()
+ minted = [
+ _credential("svc_cached", now + timedelta(minutes=15)),
+ _credential("svc_direct", now + timedelta(minutes=15)),
]
+ cache = _cache(
+ client,
+ mint=lambda _organization_id, _team_id, _principal: minted.pop(0),
+ now=lambda: now,
+ )
- def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
- raise failures.pop(0)
-
- cache = ServiceCredentialCache(mint=mint, now=lambda: now)
-
- with pytest.raises(ServiceCredentialUnavailable, match="service credential mint unavailable"):
- cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
- now += timedelta(seconds=6)
- with pytest.raises(ServiceCredentialUnavailable, match="unexpected"):
- cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
- with pytest.raises(ServiceCredentialUnavailable, match="unexpected"):
- cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
-
- assert failures == []
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_cached"
+ with patch.object(client, "get", side_effect=ConnectionError("redis unavailable")):
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_direct"
+ assert minted == []
-def test_insecure_connect_bundle_is_not_cached_and_the_next_call_can_recover() -> None:
+def test_insecure_minted_credential_is_never_cached() -> None:
now = datetime(2026, 1, 1, tzinfo=UTC)
insecure = ServiceCredential(
credential_id="svc_insecure",
credential_secret="secret-insecure",
expires_at=now + timedelta(minutes=15),
connect=ServiceCredentialConnect(
- host="warehouse.dw.us.postwh.com",
+ host="warehouse.example.com",
port=5432,
database="ducklake",
sslmode="prefer",
),
)
- minted = [insecure, _credential("svc_secure", now + timedelta(minutes=15))]
- cache = ServiceCredentialCache(mint=lambda _organization_id, _team_id, _principal: minted.pop(0), now=lambda: now)
+ client = _redis()
+ cache = _cache(client, mint=lambda _organization_id, _team_id, _principal: insecure, now=lambda: now)
with pytest.raises(ServiceCredentialUnavailable, match="service credential mint unavailable"):
cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
- now += timedelta(seconds=6)
- assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_secure"
- assert minted == []
+ assert client.keys("*") == []
+
+
+def test_sql_editor_mint_uses_a_short_request_timeout() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ with patch(
+ "products.managed_warehouse.backend.logic.sql_editor_credentials.mint_service_credential",
+ return_value=_credential("svc_one", now + timedelta(minutes=15)),
+ ) as mint:
+ sql_editor_credentials._mint_sql_editor_credential("org-1", 1, SQL_EDITOR_PRINCIPAL)
+
+ assert mint.call_args.kwargs["timeout_seconds"] == 3
+ assert mint.call_args.kwargs["principal"] == SQL_EDITOR_PRINCIPAL
def test_dynamic_source_fails_closed_when_no_credential_can_be_minted(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -368,7 +540,7 @@ def test_dynamic_source_fails_closed_when_no_credential_can_be_minted(monkeypatc
monkeypatch.setattr(
sql_editor_credentials,
"_service_credential_cache",
- ServiceCredentialCache(mint=unavailable),
+ RedisServiceCredentialCache(redis_client=_redis, mint=unavailable),
)
source_auth = ManagedWarehouseSourceAuth(
prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
@@ -387,13 +559,11 @@ def test_dynamic_source_fails_closed_when_no_credential_can_be_minted(monkeypatc
def test_unmarked_source_uses_legacy_connection_details_without_minting(monkeypatch: pytest.MonkeyPatch) -> None:
- def unexpected_mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
- raise AssertionError("legacy sources must not mint service credentials")
-
+ mint = Mock(side_effect=AssertionError("legacy sources must not mint service credentials"))
monkeypatch.setattr(
sql_editor_credentials,
"_service_credential_cache",
- ServiceCredentialCache(mint=unexpected_mint),
+ RedisServiceCredentialCache(redis_client=_redis, mint=mint),
)
source_auth = ManagedWarehouseSourceAuth(
prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
@@ -411,11 +581,13 @@ def test_unmarked_source_uses_legacy_connection_details_without_minting(monkeypa
)
is None
)
+ mint.assert_not_called()
def test_dynamic_connection_carries_required_sslmode() -> None:
now = datetime(2026, 1, 1, tzinfo=UTC)
- cache = ServiceCredentialCache(
+ cache = _cache(
+ _redis(),
mint=lambda _organization_id, _team_id, _principal: _credential("svc_one", now + timedelta(minutes=15)),
now=lambda: now,
)
@@ -438,38 +610,6 @@ def test_dynamic_connection_carries_required_sslmode() -> None:
assert connection.sslmode == "require"
-def test_dynamic_connection_rejects_an_insecure_control_plane_sslmode() -> None:
- now = datetime(2026, 1, 1, tzinfo=UTC)
- credential = _credential("svc_one", now + timedelta(minutes=15))
- credential = ServiceCredential(
- credential_id=credential.credential_id,
- credential_secret=credential.credential_secret,
- expires_at=credential.expires_at,
- connect=ServiceCredentialConnect(
- host=credential.connect.host,
- port=credential.connect.port,
- database=credential.connect.database,
- sslmode="prefer",
- ),
- )
- cache = ServiceCredentialCache(mint=lambda _organization_id, _team_id, _principal: credential, now=lambda: now)
- source_auth = ManagedWarehouseSourceAuth(
- prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
- system_managed=True,
- credential_kind=MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
- lifecycle_generation=1,
- )
-
- with pytest.raises(ServiceCredentialUnavailable, match="service credential mint unavailable"):
- resolve_managed_warehouse_postgres_connection(
- source_auth=source_auth,
- organization_id="org-1",
- team_id=1,
- principal=SQL_EDITOR_PRINCIPAL,
- credential_cache=cache,
- )
-
-
def test_dynamic_source_without_a_lifecycle_generation_fails_closed() -> None:
source_auth = ManagedWarehouseSourceAuth(
prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,