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(integration-secrets): refuse a half-configured client instead of reading env (#86546)

Tom Owersed40160e8bf3
diff --git a/posthog/integration_secrets/client.py b/posthog/integration_secrets/client.py
index c26fd6054cd6..da5c4469c990 100644
--- a/posthog/integration_secrets/client.py
+++ b/posthog/integration_secrets/client.py
@@ -17,10 +17,16 @@ Three behaviours are load-bearing:
unreachable service raises rather than quietly serving something stale. The service
needs an availability SLO before the environment variables come out.
-3. **Environment fallback only when the client is off.** Unconfigured, flag disabled, or
- a flag check that errored 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.
+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.
+
+ 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.
The token carries the request. `keys` is the exact set this call needs, so a token lifted
from a log unlocks those fields for five minutes rather than everything the deployment
@@ -44,7 +50,7 @@ from posthog.security.outbound_proxy import internal_requests
from posthog.settings.utils import get_list
from .callers import IntegrationCaller
-from .errors import SecretInRecoveryError, SecretMissingError
+from .errors import IntegrationServiceMisconfiguredError, SecretInRecoveryError, SecretMissingError
logger = structlog.get_logger(__name__)
@@ -102,6 +108,18 @@ def integration_service_signing_keys() -> list[str]:
return [key for key in get_list(settings.INTEGRATION_SERVICE_JWT_SECRET or "") if key]
+def _missing_config() -> str | None:
+ """The variable a half-configured deployment still needs, or None.
+
+ Both set, or both unset, are the two states someone can mean. Exactly one is neither.
+ """
+ has_url = bool(settings.INTEGRATION_SERVICE_URL)
+ has_keys = bool(integration_service_signing_keys())
+ if has_url == has_keys:
+ return None
+ return "INTEGRATION_SERVICE_JWT_SECRET" if has_url else "INTEGRATION_SERVICE_URL"
+
+
def _disabled_reason() -> str | None:
"""Why the environment fallback is in use, or None when the service should be called.
@@ -153,10 +171,13 @@ class IntegrationSecretsClient:
return RotatingSecret(current=secret.value, previous=secret.previous)
def _resolve(self, keys: list[str], caller: IntegrationCaller) -> dict[str, SecretValue]:
+ missing = _missing_config()
+ if missing is not None:
+ raise IntegrationServiceMisconfiguredError(missing)
reason = _disabled_reason()
if reason is not None:
INTEGRATION_SECRET_ENV_FALLBACK_COUNTER.labels(reason=reason).inc()
- return {key: self._from_environment(key) for key in keys}
+ return {key: self._from_environment(key, reason) for key in keys}
return self._fetch(keys, caller)
def _fetch(self, keys: list[str], caller: IntegrationCaller) -> dict[str, SecretValue]:
@@ -196,10 +217,12 @@ class IntegrationSecretsClient:
)
return {"Authorization": f"Bearer {token}"}
- def _from_environment(self, key: str) -> SecretValue:
+ def _from_environment(self, key: str, disabled_reason: str) -> SecretValue:
value = os.environ.get(key) or getattr(settings, key, "")
if not value:
- raise SecretMissingError(key)
+ # Carry the reason: without it this reads as "the service doesn't have it", which is
+ # the one thing it does not mean — the service was never asked.
+ raise SecretMissingError(key, disabled_reason=disabled_reason)
return SecretValue(state="steady", value=value, previous=None)
diff --git a/posthog/integration_secrets/errors.py b/posthog/integration_secrets/errors.py
index 89a129a97881..6cdc32a7dfdd 100644
--- a/posthog/integration_secrets/errors.py
+++ b/posthog/integration_secrets/errors.py
@@ -7,8 +7,36 @@ class IntegrationSecretError(Exception):
class SecretMissingError(IntegrationSecretError):
"""The key is unknown to the service, or has no value in this environment."""
- def __init__(self, key: str) -> None:
- super().__init__(key, f"{key} is not available from the integration service")
+ def __init__(self, key: str, disabled_reason: str | None = None) -> None:
+ if disabled_reason is None:
+ super().__init__(key, f"{key} is not available from the integration service")
+ return
+ # The service was never called, so saying "not available from the integration service"
+ # would send the reader to look for a key that is sitting right there. Name the fallback.
+ super().__init__(
+ key,
+ f"{key} is not set in this environment, and the integration service was not called "
+ f"({disabled_reason}) — so a key that exists only in the service cannot resolve here",
+ )
+
+
+class IntegrationServiceMisconfiguredError(Exception):
+ """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.
+ """
+
+ def __init__(self, missing: str) -> None:
+ self.missing = missing
+ super().__init__(
+ f"{missing} is not set. The integration service client needs both "
+ f"INTEGRATION_SERVICE_URL and INTEGRATION_SERVICE_JWT_SECRET, or neither "
+ f"(which reads credentials from the environment, as self-hosted does)."
+ )
class SecretInRecoveryError(IntegrationSecretError):
diff --git a/posthog/integration_secrets/test/test_client.py b/posthog/integration_secrets/test/test_client.py
index bdae12719f3c..8e81124de0ca 100644
--- a/posthog/integration_secrets/test/test_client.py
+++ b/posthog/integration_secrets/test/test_client.py
@@ -1,3 +1,4 @@
+import os
from typing import Any
import pytest
@@ -15,7 +16,11 @@ from posthog.integration_secrets.client import (
integration_service_enabled,
integration_service_signing_keys,
)
-from posthog.integration_secrets.errors import SecretInRecoveryError, SecretMissingError
+from posthog.integration_secrets.errors import (
+ IntegrationServiceMisconfiguredError,
+ SecretInRecoveryError,
+ SecretMissingError,
+)
from posthog.jwt import PosthogJwtAudience
SERVICE_SETTINGS: dict[str, Any] = {
@@ -191,6 +196,53 @@ class TestUnconfigured(SimpleTestCase):
with pytest.raises(SecretMissingError):
IntegrationSecretsClient().get("A_KEY_NOBODY_SET", CALLER)
+ @override_settings(INTEGRATION_SERVICE_URL="", INTEGRATION_SERVICE_JWT_SECRET="")
+ def test_the_error_says_the_service_was_never_called(self) -> None:
+ # "not available from the integration service" sends the reader to look for a key that is
+ # sitting in the service already. The reason it did not resolve is that nothing asked.
+ with pytest.raises(SecretMissingError) as excinfo:
+ IntegrationSecretsClient().get("A_KEY_NOBODY_SET", CALLER)
+ assert "was not called" in str(excinfo.value)
+ assert "unconfigured" in str(excinfo.value)
+
+
+class TestHalfConfigured(SimpleTestCase):
+ """One variable without the other: refuse, rather than silently reading the environment."""
+
+ @parameterized.expand(
+ [
+ ("url without a signing key", "http://svc", "", "INTEGRATION_SERVICE_JWT_SECRET"),
+ ("signing key without a url", "", "signing-key", "INTEGRATION_SERVICE_URL"),
+ ]
+ )
+ def test_raises_naming_the_variable_still_needed(self, _name: str, url: str, key: str, missing: str) -> None:
+ with (
+ override_settings(INTEGRATION_SERVICE_URL=url, INTEGRATION_SERVICE_JWT_SECRET=key),
+ patch(POST) as post,
+ patch(FLAG, return_value=True),
+ ):
+ with pytest.raises(IntegrationServiceMisconfiguredError) as excinfo:
+ IntegrationSecretsClient().get(KEY, CALLER)
+ assert missing in str(excinfo.value)
+ post.assert_not_called()
+
+ @override_settings(INTEGRATION_SERVICE_URL="http://svc", INTEGRATION_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(IntegrationServiceMisconfiguredError):
+ IntegrationSecretsClient().get(KEY, CALLER)
+
+ @override_settings(INTEGRATION_SERVICE_URL="http://svc", INTEGRATION_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(IntegrationServiceMisconfiguredError):
+ IntegrationSecretsClient().get(KEY, CALLER)
+
@override_settings(**SERVICE_SETTINGS)
class TestMintedToken(SimpleTestCase):