: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
feat(integration-secrets): log every credential request (#88386)
Tom Owers4c0e12b1822b
diff --git a/posthog/integration_secrets/client.py b/posthog/integration_secrets/client.pyindex 17587cee09b1..64322d446f30 100644--- a/posthog/integration_secrets/client.py+++ b/posthog/integration_secrets/client.py@@ -34,9 +34,11 @@ may read. There is deliberately no request body."""import os+import timefrom dataclasses import fieldfrom datetime import timedeltafrom typing import Any+from urllib.parse import urlparsefrom django.conf import settings@@ -157,7 +159,89 @@ def integration_service_enabled() -> bool:return _disabled_reason() is None+def _log_resolve(+ url: str,+ keys: list[str],+ caller: IntegrationCaller,+ started_at_monotonic: float,+ *,+ response: Any = None,+ body: dict[str, Any] | None = None,+ error: BaseException | None = None,+) -> None:+ """One structured line per credential request. Never raises.++ Field names match `data_imports.http.request` (method, url, host, status_code, latency_ms,+ error_class) so a credential read reads alongside the rest of a job's HTTP traffic instead of+ needing its own query. Without it this hop is invisible: a sync that fails on a credential+ shows the source's traffic and a silent gap where the read was.++ What it adds over a plain request log is the part that answers rotation questions — per-key+ `state` and `version_id`. "Which value did this pod actually get, and when did it change?"+ is otherwise unanswerable from the caller's side, because nothing about the value may be+ logged and the service's own audit line lives in a different system.++ Nothing here can carry a credential, and that is a property of what is selected rather than+ of any scrubbing: values are read from the response by name (`state`, `version_id`) and the+ value fields are never among them. The request is logged by URL only — the bearer token is+ in a header that is not touched, and the path carries no parameters.++ Never raises, for the same reason the warehouse observer doesn't: a broken telemetry layer+ must not become a failed credential read.+ """+ try:+ status_code = getattr(response, "status_code", None)+ secrets: dict[str, Any] = (body or {}).get("secrets") or {}+ # `sorted` so two reads of the same keys produce the same line and diff cleanly.+ states = {key: secrets[key].get("state") for key in sorted(secrets)}+ versions = {key: secrets[key].get("version_id") for key in sorted(secrets)}+ missing = sorted((body or {}).get("missing") or [])++ fields: dict[str, Any] = {+ "method": "POST",+ "url": url,+ "host": urlparse(url).hostname or "",+ "status_code": status_code,+ "latency_ms": max(0, int((time.monotonic() - started_at_monotonic) * 1000)),+ "error_class": type(error).__name__ if error is not None else None,+ "caller": str(caller),+ "keys": sorted(keys),+ "states": states,+ "version_ids": versions,+ "missing": missing,+ }++ if error is not None or (status_code is not None and status_code >= 400):+ logger.warning("integration_secrets.resolve", **fields)+ elif missing or any(state != "steady" for state in states.values()):+ # A rotating or recovered key, or one the service doesn't hold, is the case worth+ # seeing without turning debug on — it explains a failure, or a value changing under+ # a caller that did nothing differently.+ logger.info("integration_secrets.resolve", **fields)+ else:+ # Steady reads are the overwhelming majority and say nothing new, so they sit at+ # debug, the same level the warehouse observer gives an ordinary 2xx.+ logger.debug("integration_secrets.resolve", **fields)+ except Exception:+ logger.debug("integration_secrets.resolve_log_failed", exc_info=True)++class IntegrationSecretsClient:+ def __init__(self, session: requests.Session | None = None) -> None:+ """`session` swaps the transport without changing anything else.++ The default is the shared internal session, which is right for most callers. A product+ that already runs its own instrumented session — warehouse sources meters and logs every+ outbound request through a tracked adapter — passes it here so credential reads land in+ the same place as the rest of that job's HTTP traffic, instead of being the one hop that+ is invisible while you are debugging a sync.++ Anything passed in must have HTTP sample capture switched OFF. Responses on this path+ carry credentials in plaintext, and a sampler that stores request/response bodies for+ later inspection would write them somewhere they must never be.+ """+ self._session = session or internal_requests+def get(self, key: str, caller: IntegrationCaller) -> str:return self.get_many([key], caller)[key]@@ -232,22 +316,23 @@ class IntegrationSecretsClient:# process, not the service being unreachable. Catching it here would file it under the# one label nobody investigates.headers = self._auth_headers(keys, caller)+ url = f"{settings.INTEGRATION_SERVICE_URL.rstrip('/')}{RESOLVE_PATH}"+ started = time.monotonic()try:- response = internal_requests.post(- f"{settings.INTEGRATION_SERVICE_URL.rstrip('/')}{RESOLVE_PATH}",- headers=headers,- timeout=REQUEST_TIMEOUT_SECONDS,- )+ response = self._session.post(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)response.raise_for_status()# ValueError covers a body that is not JSON. Modern `requests` raises its own# JSONDecodeError (a RequestException), but the stdlib/simplejson ValueError still# surfaces on older paths, and nothing else in this block raises one.- return response.json()+ body: dict[str, Any] = response.json()except (requests.RequestException, ValueError) as e:INTEGRATION_SECRET_FETCH_COUNTER.labels(outcome="unreachable").inc()+ _log_resolve(url, keys, caller, started, response=getattr(e, "response", None), error=e)raise IntegrationServiceUnreachableError(f"The integration service did not answer a credential request: {e}") from e+ _log_resolve(url, keys, caller, started, response=response, body=body)+ return bodydef _auth_headers(self, keys: list[str], caller: IntegrationCaller) -> dict[str, str]:token = encode_jwt(diff --git a/posthog/integration_secrets/test/test_client.py b/posthog/integration_secrets/test/test_client.pyindex d988c691c071..44938b1a148b 100644--- a/posthog/integration_secrets/test/test_client.py+++ b/posthog/integration_secrets/test/test_client.py@@ -2,6 +2,7 @@ import osfrom typing import Anyimport pytest+from unittest import mockfrom unittest.mock import patchfrom django.test import SimpleTestCase, override_settings@@ -352,3 +353,143 @@ class TestMintedToken(SimpleTestCase):jwt.decode(token, "signing-key-new", audience=audience, algorithms=["HS256"])with pytest.raises(jwt.InvalidSignatureError):jwt.decode(token, "signing-key-old", audience=audience, algorithms=["HS256"])+++@override_settings(**SERVICE_SETTINGS)+class TestResolveLogging(SimpleTestCase):+ """The credential read is otherwise the one invisible hop in a job's HTTP traffic."""++ def setUp(self) -> None:+ self.secrets = IntegrationSecretsClient()+ flag = patch(FLAG, return_value=True)+ flag.start()+ self.addCleanup(flag.stop)++ @staticmethod+ def _response(payload: dict[str, Any], status_code: int = 200) -> Any:+ response = FakeResponse(payload)+ response.status_code = status_code # type: ignore[attr-defined]+ return response++ def test_logs_the_request_with_the_shared_http_field_names(self) -> None:+ # Same names as data_imports.http.request, so a credential read shows up in the same+ # query as the rest of a job's traffic rather than needing its own.+ with patch(POST, return_value=self._response(body({KEY: steady("sec")}))):+ with patch("posthog.integration_secrets.client.logger") as log:+ self.secrets.get(KEY, CALLER)++ fields = log.debug.call_args.kwargs+ assert log.debug.call_args.args[0] == "integration_secrets.resolve"+ assert fields["method"] == "POST"+ assert fields["status_code"] == 200+ assert fields["host"] == "integration-service.posthog.svc.cluster.local"+ assert fields["error_class"] is None+ assert fields["caller"] == str(CALLER)+ assert fields["keys"] == [KEY]+ assert isinstance(fields["latency_ms"], int)++ # The rotation questions this exists to answer: which value did this pod get, and has it+ # changed? Nothing about the value itself may be logged, so state and version carry it.+ def test_logs_per_key_state_and_version_at_info_when_a_rotation_is_in_flight(self) -> None:+ rotating = {+ "state": "rotating",+ "value": "live",+ "previous": "staged",+ "version_id": "v9",+ "fetched_at": "now",+ }+ with patch(POST, return_value=self._response(body({KEY: rotating}))):+ with patch("posthog.integration_secrets.client.logger") as log:+ self.secrets.get(KEY, CALLER)++ # info, not debug: a value changing under a caller that did nothing differently is the+ # thing you want visible without having turned debug on first.+ log.debug.assert_not_called()+ fields = log.info.call_args.kwargs+ assert fields["states"] == {KEY: "rotating"}+ assert fields["version_ids"] == {KEY: "v9"}++ @parameterized.expand(+ [+ ("a missing key", {"missing": [KEY]}, SecretMissingError),+ (+ "a key in recovery",+ {"secrets": {KEY: {"state": "recovery", "version_id": "v1", "fetched_at": "now"}}},+ SecretInRecoveryError,+ ),+ ]+ )+ def test_logs_at_info_for(self, _name: str, payload: dict[str, Any], expected: type[Exception]) -> None:+ with patch(POST, return_value=self._response(body(**payload))):+ with patch("posthog.integration_secrets.client.logger") as log:+ with pytest.raises(expected):+ self.secrets.get(KEY, CALLER)++ log.info.assert_called_once()+ log.debug.assert_not_called()++ def test_logs_a_transport_failure_at_warning_with_the_error_class(self) -> None:+ with patch(POST, side_effect=requests.ConnectionError("connection refused")):+ with patch("posthog.integration_secrets.client.logger") as log:+ with pytest.raises(IntegrationServiceUnreachableError):+ self.secrets.get(KEY, CALLER)++ fields = log.warning.call_args.kwargs+ assert fields["error_class"] == "ConnectionError"+ assert fields["status_code"] is None++ # The property that matters most here, and the reason nothing is scrubbed: fields are chosen+ # by name from the response, and no value field is among them. A scrubber would be a thing to+ # get wrong; selecting is a thing that cannot be.+ def test_no_credential_value_can_reach_a_log_line(self) -> None:+ secret_value = "sk-live-do-not-log-me"+ rotating = {+ "state": "rotating",+ "value": secret_value,+ "previous": "staged-do-not-log-me",+ "version_id": "v1",+ "fetched_at": "now",+ }+ with patch(POST, return_value=self._response(body({KEY: rotating}))):+ with patch("posthog.integration_secrets.client.logger") as log:+ assert self.secrets.get(KEY, CALLER) == secret_value++ emitted = repr([c.kwargs for c in log.info.call_args_list + log.debug.call_args_list])+ assert secret_value not in emitted+ assert "staged-do-not-log-me" not in emitted+ # The bearer token lives in a header the logger never touches.+ assert "Authorization" not in emitted+ assert "signing-key-new" not in emitted++ def test_a_broken_logger_cannot_fail_a_credential_read(self) -> None:+ # Same contract as the warehouse observer: telemetry must never become an outage.+ with patch(POST, return_value=self._response(body({KEY: steady("sec")}))):+ with patch("posthog.integration_secrets.client.logger") as log:+ log.debug.side_effect = [RuntimeError("log pipeline is down"), None]+ assert self.secrets.get(KEY, CALLER) == "sec"+++@override_settings(**SERVICE_SETTINGS)+class TestInjectedSession(SimpleTestCase):+ def setUp(self) -> None:+ flag = patch(FLAG, return_value=True)+ flag.start()+ self.addCleanup(flag.stop)++ # Warehouse sources already meter and log every outbound request through a tracked adapter.+ # Passing that session in puts credential reads in the same place as the rest of the job's+ # traffic, instead of leaving a silent gap where the read was.+ def test_uses_the_session_it_was_given(self) -> None:+ session = mock.MagicMock()+ session.post.return_value = FakeResponse(body({KEY: steady("sec")}))++ with patch(POST) as shared_post:+ assert IntegrationSecretsClient(session=session).get(KEY, CALLER) == "sec"++ session.post.assert_called_once()+ shared_post.assert_not_called()++ def test_defaults_to_the_shared_internal_session(self) -> None:+ with patch(POST, return_value=FakeResponse(body({KEY: steady("sec")}))) as shared_post:+ assert IntegrationSecretsClient().get(KEY, CALLER) == "sec"+ shared_post.assert_called_once()