:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(credentials-service): read the environment when a pod is half-configured (#122385)
Tom Owers13184d4d928a
diff --git a/posthog/credentials_service/client.py b/posthog/credentials_service/client.pyindex b27591dc9a13..c62aecdc389c 100644--- a/posthog/credentials_service/client.py+++ b/posthog/credentials_service/client.py@@ -18,15 +18,14 @@ Three behaviours are load-bearing:needs an availability SLO before the environment variables come out.3. **Environment fallback only when the client is off.** Flag disabled, a flag check that- errored, or NEITHER variable configured means "read `os.environ` as before". That covers- self-hosted deployments, local development, and the rollout window. It is not an outage- path: once the client is on and the service is down, the call fails.+ errored, or the deployment not fully configured means "read `os.environ` as before". That+ covers self-hosted deployments, local development, and the rollout window. It is not an+ outage path: once the client is on and the service is down, the call fails.- Half-configured is the exception, and it raises. A URL without a signing key (or the- reverse) reads as "not configured" and quietly serves credentials from the pod's own- environment — which looks like success for every key still mounted there and fails only- for the ones that have actually moved to the service. That is the shape of a rollout that- appears to work and hasn't started.+ Half-configured (a URL without a signing key, or the reverse) also reads the environment,+ because a deploy that adds one variable before the other must not take down every credential+ read in the pod. It is still a mistake, so it is loud: a warning once per process naming the+ variable to set, and its own `half_configured` reason on the environment fallback counter.The token carries the request. `keys` is the exact set this call needs, so a token liftedfrom a log unlocks those fields for five minutes rather than everything the deployment@@ -35,6 +34,7 @@ may read. There is deliberately no request body.import osimport time+import functoolsfrom dataclasses import fieldfrom datetime import timedeltafrom typing import Any@@ -53,12 +53,7 @@ from posthog.security.outbound_proxy import internal_requestsfrom posthog.settings.utils import get_listfrom .callers import CredentialsCaller-from .errors import (- CredentialsServiceMisconfiguredError,- CredentialsServiceUnreachableError,- SecretInRecoveryError,- SecretMissingError,-)+from .errors import CredentialsServiceUnreachableError, SecretInRecoveryError, SecretMissingErrorlogger = structlog.get_logger(__name__)@@ -145,16 +140,29 @@ def _missing_config() -> str | None:return "CREDENTIALS_SERVICE_JWT_SECRET" if has_url else "CREDENTIALS_SERVICE_URL"+def _warn_half_configured(missing: str) -> None:+ logger.warning(+ "credentials_service.half_configured_reading_environment",+ missing=missing,+ detail="Set both CREDENTIALS_SERVICE_URL and CREDENTIALS_SERVICE_JWT_SECRET, or neither.",+ )++def _disabled_reason() -> str | None:"""Why the environment fallback is in use, or None when the service should be called.The flag fails closed: closed means the old environment-variable path, because a flag- service blip must not take out credential reads. The three reasons matter separately+ service blip must not take out credential reads. The four reasons matter separatelyduring the rollout — "flag_error" is the fail-closed path that quietly keeps a pod onenvironment variables while the flag service is unhealthy, and it must not look likea deliberate opt-out."""- if not settings.CREDENTIALS_SERVICE_URL or not credentials_service_signing_keys():+ missing = _missing_config()+ if missing is not None:+ _warn_half_configured(missing)+ return "half_configured"+ if not settings.CREDENTIALS_SERVICE_URL:return "unconfigured"try:enabled = bool(posthoganalytics.feature_enabled(CREDENTIALS_SERVICE_FLAG, CREDENTIALS_SERVICE_FLAG_DISTINCT_ID))@@ -279,9 +287,6 @@ class CredentialsServiceClient:return RotatingSecret(current=secret.value, incoming=secret.incoming)def _resolve(self, keys: list[str], caller: CredentialsCaller) -> dict[str, SecretValue]:- missing = _missing_config()- if missing is not None:- raise CredentialsServiceMisconfiguredError(missing)reason = _disabled_reason()if reason is not None:CREDENTIALS_SERVICE_ENV_FALLBACK_COUNTER.labels(reason=reason).inc()diff --git a/posthog/credentials_service/errors.py b/posthog/credentials_service/errors.pyindex d658aa227de4..5d6baa5902c5 100644--- a/posthog/credentials_service/errors.py+++ b/posthog/credentials_service/errors.py@@ -50,27 +50,6 @@ class SecretMissingError(CredentialsSecretError):)-class CredentialsServiceMisconfiguredError(CredentialsServiceFailure):- """Half-configured: one of the two variables is set and the other is not.-- Both unset is a valid state — self-hosted and local development don't run the service, and- reading the environment is the whole point of the fallback. One without the other is a state- nobody chose, and it is invisible: it reads as "not configured", so credentials still mounted- as environment variables resolve as if the service answered, while the ones that have actually- moved raise SecretMissingError. Refuse instead, and name the variable to set.-- Reportable: a deployment is wrong and only a deploy fixes it.- """-- def __init__(self, missing: str) -> None:- self.missing = missing- super().__init__(- f"{missing} is not set. The credentials service client needs both "- f"CREDENTIALS_SERVICE_URL and CREDENTIALS_SERVICE_JWT_SECRET, or neither "- f"(which reads credentials from the environment, as self-hosted does)."- )--class SecretInRecoveryError(CredentialsSecretError):"""The credential is known-burned and has no valid replacement yet.diff --git a/posthog/credentials_service/test/test_client.py b/posthog/credentials_service/test/test_client.pyindex be779d3175a7..2aefeac41e8e 100644--- a/posthog/credentials_service/test/test_client.py+++ b/posthog/credentials_service/test/test_client.py@@ -15,12 +15,12 @@ from prometheus_client import REGISTRYfrom posthog.credentials_service.callers import CredentialsCallerfrom posthog.credentials_service.client import (CredentialsServiceClient,+ _warn_half_configured,credentials_service_enabled,credentials_service_signing_keys,)from posthog.credentials_service.errors import (CredentialsServiceFailure,- CredentialsServiceMisconfiguredError,CredentialsServiceUnreachableError,SecretInRecoveryError,SecretMissingError,@@ -223,7 +223,6 @@ class TestCredentialsServiceClient(SimpleTestCase):[("missing", SecretMissingError(KEY), True),("in recovery", SecretInRecoveryError(KEY), False),- ("half-configured", CredentialsServiceMisconfiguredError("CREDENTIALS_SERVICE_URL"), True),("unreachable", CredentialsServiceUnreachableError("no answer"), False),])@@ -297,41 +296,45 @@ class TestUnconfigured(SimpleTestCase):class TestHalfConfigured(SimpleTestCase):- """One variable without the other: refuse, rather than silently reading the environment."""+ """One variable without the other reads the environment, as if neither were set, and says so."""++ def setUp(self) -> None:+ _warn_half_configured.cache_clear()@parameterized.expand([- ("url without a signing key", "http://svc", "", "CREDENTIALS_SERVICE_JWT_SECRET"),- ("signing key without a url", "", "signing-key", "CREDENTIALS_SERVICE_URL"),+ ("url without a signing key, flag on", "http://svc", "", True, "CREDENTIALS_SERVICE_JWT_SECRET"),+ ("url without a signing key, flag off", "http://svc", "", False, "CREDENTIALS_SERVICE_JWT_SECRET"),+ ("signing key without a url, flag on", "", "signing-key", True, "CREDENTIALS_SERVICE_URL"),+ ("signing key without a url, flag off", "", "signing-key", False, "CREDENTIALS_SERVICE_URL"),])- def test_raises_naming_the_variable_still_needed(self, _name: str, url: str, key: str, missing: str) -> None:+ def test_reads_the_environment_instead_of_raising(+ self, _name: str, url: str, key: str, flag_on: bool, missing: str+ ) -> None:+ labels = {"reason": "half_configured"}+ before = REGISTRY.get_sample_value("posthog_credentials_service_env_fallback_total", labels) or 0with (override_settings(CREDENTIALS_SERVICE_URL=url, CREDENTIALS_SERVICE_JWT_SECRET=key),+ patch.dict(os.environ, {KEY: "from-env"}),patch(POST) as post,- patch(FLAG, return_value=True),+ patch(FLAG, return_value=flag_on),+ patch("posthog.credentials_service.client.logger") as log,):- with pytest.raises(CredentialsServiceMisconfiguredError) as excinfo:- CredentialsServiceClient().get(KEY, CALLER)- assert missing in str(excinfo.value)- post.assert_not_called()+ client = CredentialsServiceClient()+ assert client.get(KEY, CALLER) == "from-env"+ assert client.get(KEY, CALLER) == "from-env"- @override_settings(CREDENTIALS_SERVICE_URL="http://svc", CREDENTIALS_SERVICE_JWT_SECRET="")- def test_a_mounted_environment_variable_does_not_paper_over_it(self) -> None:- # The failure this exists to catch. Half-configured, the fallback would have returned the- # value from the pod's environment and the deployment would look wired up — until someone- # asks for a credential that only exists in the service.- with patch.dict(os.environ, {KEY: "still-mounted-on-the-pod"}):- with pytest.raises(CredentialsServiceMisconfiguredError):- CredentialsServiceClient().get(KEY, CALLER)+ post.assert_not_called()+ log.warning.assert_called_once()+ assert log.warning.call_args.kwargs["missing"] == missing+ after = REGISTRY.get_sample_value("posthog_credentials_service_env_fallback_total", labels)+ assert after == before + 2@override_settings(CREDENTIALS_SERVICE_URL="http://svc", CREDENTIALS_SERVICE_JWT_SECRET="")- def test_the_flag_does_not_rescue_a_half_configured_deployment(self) -> None:- # Turning the flag off is how you disable the client deliberately; it is not a way to make- # a misconfiguration legal, or the rollout gate would hide it.- with patch(FLAG, return_value=False):- with pytest.raises(CredentialsServiceMisconfiguredError):- CredentialsServiceClient().get(KEY, CALLER)+ def test_service_is_not_enabled(self) -> None:+ with patch(FLAG, return_value=True):+ assert credentials_service_enabled() is False@override_settings(**SERVICE_SETTINGS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.pyindex 20b7e087a7e9..b475aad8d288 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py@@ -21,7 +21,6 @@ from parameterized import parameterizedfrom requests.exceptions import HTTPError, ProxyErrorfrom posthog.credentials_service.errors import (- CredentialsServiceMisconfiguredError,CredentialsServiceUnreachableError,SecretInRecoveryError,SecretMissingError,@@ -1700,7 +1699,6 @@ async def test_probe_never_runs_when_not_eligible_or_resetting(overrides: dict[s(SecretInRecoveryError("HUBSPOT_APP_CLIENT_SECRET"), False),(SecretMissingError("HUBSPOT_APP_CLIENT_SECRET"), True),(SecretMissingError("HUBSPOT_APP_CLIENT_SECRET", disabled_reason="unconfigured"), True),- (CredentialsServiceMisconfiguredError("CREDENTIALS_SERVICE_URL"), True),(CredentialsServiceUnreachableError("connection refused"), False),],)