: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(activity-log): record the mcp end user ip and no ip for sandboxes (#105745)
Yasen448d6f72ac8b
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.mdindex 1e21c5b4eb48..aae265df9ff6 100644--- a/docs/internal/activity-logging.md+++ b/docs/internal/activity-logging.md@@ -166,6 +166,22 @@ A task link appears only when the token has a server-set task binding, so intentThe `X-PostHog-Task-Id` header cannot supply that binding, and the authenticated user remains the actor on the audit row.This applies to new activity rows; it does not recover intent that was discarded before the change.+### Client IP++`ActivityLoggingMiddleware` stores the request's client IP, and `log_activity` writes it to `ActivityLog.ip_address`.+Only the activity log uses the rules below. Throttles, IP allowlists, and request logs read the IP from the request as before.++- **Browser and API requests.** The IP comes from `get_ip_address`: the leftmost `X-Forwarded-For` entry, or `REMOTE_ADDR`.+- **MCP requests.** The MCP server calls the API from inside the cluster, so `REMOTE_ADDR` is the MCP pod.+ The MCP server signs the end user's IP and sends it in `X-PostHog-MCP-Client-IP`, `X-PostHog-MCP-Client-IP-Timestamp`, and `X-PostHog-MCP-Client-IP-Signature`.+ The middleware removes these headers from every request.+ When the signature verifies against `MCP_CLIENT_IP_SIGNING_KEYS`, the row records the signed IP.+ Any other result keeps the `get_ip_address` value.+ The signature format is the managed proxy format, `hex(HMAC-SHA256(key, f"{ip}:{unix_seconds}"))`, valid from 5 seconds ahead to 60 seconds old.+ The `posthog_mcp_client_ip_verifications` counter records each outcome.+- **Sandbox agents.** A row written with an OAuth token bound to a sandbox task keeps the request IP.+ The token can leave the sandbox, so the IP is what tells a sandbox write apart from a write made elsewhere with the same token.+A model with a fail-closed manager (`TeamScopedRootMixin`, `ProductTeamModel`) raises `TeamScopeError` on any query without team context.The mixin's before-update read is by primary key without a team filter (`unscoped()`), so a `save()` outside a request works.Your own reads in the same path still need `with team_scope(team_id):` or `Model.objects.for_team(team_id)`.diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.mdindex fdb0b7cdf96e..ae09303ca711 100644--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md@@ -222,6 +222,9 @@ The tag is derived from the task binding on the run's own token, not from the `xThe `scout:` prefix is reserved for that path, and a header value claiming it is dropped, so an agent cannot claim to be a scout it is not.Every other client keeps the self-reported header value.+A row written with a token bound to a sandbox task still records the request IP address.+The token can leave the sandbox, so the address is what tells a sandbox write apart from a write made elsewhere with the same token.+## PostHog MCP serverThe sandbox comes with access to the PostHog MCP server,diff --git a/posthog/middleware.py b/posthog/middleware.pyindex 67df848f7482..1d38e092cd02 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -142,11 +142,11 @@ def session_age_for_user(user: User) -> int:return settings.SESSION_COOKIE_AGE-MANAGED_PROXY_SIGNATURE_MAX_AGE_SECONDS = 60-MANAGED_PROXY_SIGNATURE_MAX_CLOCK_SKEW_SECONDS = 5+SIGNED_CLIENT_IP_MAX_AGE_SECONDS = 60+SIGNED_CLIENT_IP_MAX_CLOCK_SKEW_SECONDS = 5-class ManagedProxyClientIPOutcome(StrEnum):+class SignedClientIPOutcome(StrEnum):VALID = "valid"# The instance holds no signing key, which is the normal state outside PostHog Cloud.NOT_CONFIGURED = "not_configured"@@ -163,37 +163,69 @@ MANAGED_PROXY_CLIENT_IP_VERIFICATIONS = Counter(["outcome"],)+MCP_CLIENT_IP_VERIFICATIONS = Counter(+ "posthog_mcp_client_ip_verifications",+ "Verifications of the end user IP that the MCP server signs, by outcome.",+ ["outcome"],+)++MCP_CLIENT_IP_META_KEY = "HTTP_X_POSTHOG_MCP_CLIENT_IP"+MCP_CLIENT_IP_TIMESTAMP_META_KEY = "HTTP_X_POSTHOG_MCP_CLIENT_IP_TIMESTAMP"+MCP_CLIENT_IP_SIGNATURE_META_KEY = "HTTP_X_POSTHOG_MCP_CLIENT_IP_SIGNATURE"-def verify_managed_proxy_client_ip(- ip: str | None, timestamp: str | None, signature: str | None-) -> ManagedProxyClientIPOutcome:- """Report whether the managed reverse proxy signed this client IP.- The proxy Worker sends hex(HMAC-SHA256(key, f"{ip}:{timestamp}")) with the timestamp in unix seconds.- A change to this format must also go to the Worker, or Django ignores the signed IP on every request.+def verify_signed_client_ip(+ ip: str | None, timestamp: str | None, signature: str | None, signing_keys: list[str]+) -> SignedClientIPOutcome:+ """Report whether the holder of one of `signing_keys` signed this client IP.++ The signer sends hex(HMAC-SHA256(key, f"{ip}:{timestamp}")) with the timestamp in unix seconds.+ The managed proxy Worker and the MCP server both sign in this format. A change to it must also go+ to them, or Django ignores the signed IP on every request."""- keys = [key for key in settings.MANAGED_PROXY_SIGNING_KEYS if key]+ keys = [key for key in signing_keys if key]if not keys:- return ManagedProxyClientIPOutcome.NOT_CONFIGURED+ return SignedClientIPOutcome.NOT_CONFIGUREDif not ip or not timestamp or not signature:- return ManagedProxyClientIPOutcome.INVALID_INPUT+ return SignedClientIPOutcome.INVALID_INPUT# int() raises ValueError on very long digit strings, so check the length first.if len(timestamp) > 12 or not (timestamp.isascii() and timestamp.isdigit()):- return ManagedProxyClientIPOutcome.INVALID_INPUT+ return SignedClientIPOutcome.INVALID_INPUTtry:ip_address(ip)except ValueError:- return ManagedProxyClientIPOutcome.INVALID_INPUT+ return SignedClientIPOutcome.INVALID_INPUTage_seconds = time.time() - int(timestamp)- if not -MANAGED_PROXY_SIGNATURE_MAX_CLOCK_SKEW_SECONDS <= age_seconds <= MANAGED_PROXY_SIGNATURE_MAX_AGE_SECONDS:- return ManagedProxyClientIPOutcome.TIMESTAMP_OUT_OF_WINDOW+ if not -SIGNED_CLIENT_IP_MAX_CLOCK_SKEW_SECONDS <= age_seconds <= SIGNED_CLIENT_IP_MAX_AGE_SECONDS:+ return SignedClientIPOutcome.TIMESTAMP_OUT_OF_WINDOWmessage = f"{ip}:{timestamp}".encode()provided = signature.lower()for key in keys:if signatures_match(hmac_sha256_signature(key, message), provided):- return ManagedProxyClientIPOutcome.VALID- return ManagedProxyClientIPOutcome.BAD_SIGNATURE+ return SignedClientIPOutcome.VALID+ return SignedClientIPOutcome.BAD_SIGNATURE+++def pop_mcp_client_ip(request: HttpRequest) -> str | None:+ """Remove the MCP server's signed end user IP from the request, and return it when it verifies.++ The MCP server calls the API from inside the cluster, so REMOTE_ADDR is the MCP pod. The signed+ IP is the one the MCP server received from its own edge. Only the activity log uses it, so the+ request's X-Forwarded-For does not change.+ """+ ip = request.META.pop(MCP_CLIENT_IP_META_KEY, None)+ timestamp = request.META.pop(MCP_CLIENT_IP_TIMESTAMP_META_KEY, None)+ signature = request.META.pop(MCP_CLIENT_IP_SIGNATURE_META_KEY, None)+ if ip is None and timestamp is None and signature is None:+ return None+ # request.headers caches a copy of META on first access, and the pops above changed META.+ # Drop the cache so that a later reader cannot see the unverified values.+ request.__dict__.pop("headers", None)++ outcome = verify_signed_client_ip(ip, timestamp, signature, settings.MCP_CLIENT_IP_SIGNING_KEYS)+ MCP_CLIENT_IP_VERIFICATIONS.labels(outcome=outcome.value).inc()+ return ip if outcome is SignedClientIPOutcome.VALID else Noneclass ManagedProxyClientIPMiddleware:@@ -228,9 +260,9 @@ class ManagedProxyClientIPMiddleware:if ip is None and timestamp is None and signature is None:return self.get_response(request)- outcome = verify_managed_proxy_client_ip(ip, timestamp, signature)+ outcome = verify_signed_client_ip(ip, timestamp, signature, settings.MANAGED_PROXY_SIGNING_KEYS)MANAGED_PROXY_CLIENT_IP_VERIFICATIONS.labels(outcome=outcome.value).inc()- if outcome is ManagedProxyClientIPOutcome.VALID:+ if outcome is SignedClientIPOutcome.VALID:request.META["HTTP_X_FORWARDED_FOR"] = ip# request.headers caches a copy of META on first access, and the pops above changed META.# Drop the cache so that a later reader sees the change.@@ -1285,7 +1317,7 @@ class ActivityLoggingMiddleware:if client_header:activity_storage.set_client(client_from_header(client_header))- activity_storage.set_ip_address(get_ip_address(request) or None)+ activity_storage.set_ip_address(pop_mcp_client_ip(request) or get_ip_address(request) or None)try:response = self.get_response(request)diff --git a/posthog/settings/access.py b/posthog/settings/access.pyindex 3e1e4c511d13..a21639cee4c3 100644--- a/posthog/settings/access.py+++ b/posthog/settings/access.py@@ -43,6 +43,9 @@ TRUST_ALL_PROXIES = get_from_env("TRUST_ALL_PROXIES", False, type_cast=str_to_bo# signature from any key. When the list is empty, Django never trusts the signed client IP headers.MANAGED_PROXY_SIGNING_KEYS: list[str] = get_list(os.getenv("MANAGED_PROXY_SIGNING_KEYS", ""))+# Keys the MCP server signs the end user IP with (ActivityLoggingMiddleware). Empty means never trusted.+MCP_CLIENT_IP_SIGNING_KEYS: list[str] = get_list(os.getenv("MCP_CLIENT_IP_SIGNING_KEYS", ""))+if IS_BEHIND_PROXY:USE_X_FORWARDED_HOST = Truediff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.pyindex 9459c597e9b1..c5da96060f30 100644--- a/posthog/test/activity_logging/test_activity_logging.py+++ b/posthog/test/activity_logging/test_activity_logging.py@@ -1,3 +1,6 @@+import hmac+import time+import hashlibfrom datetime import timedeltafrom uuid import UUID@@ -700,14 +703,21 @@ class TestAgentAttributionOnApiWrites(APIBaseTest):expected_trigger: dict | None,) -> None:self._authenticate_as_oauth_agent(client_id, task_id, delegated)+ signed_at = str(int(time.time()))- response = self.client.post(- f"/api/projects/{self.team.id}/dashboards/",- {"name": "Weekly signups"},- HTTP_X_POSTHOG_CLIENT="mcp",- HTTP_X_POSTHOG_TASK_ID="019f4c2a-0000-7000-8000-0000000000bb",- HTTP_X_POSTHOG_INTENT=intent or "",- )+ with self.settings(MCP_CLIENT_IP_SIGNING_KEYS=["mcp-client-ip-test-key"]):+ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/",+ {"name": "Weekly signups"},+ HTTP_X_POSTHOG_CLIENT="mcp",+ HTTP_X_POSTHOG_TASK_ID="019f4c2a-0000-7000-8000-0000000000bb",+ HTTP_X_POSTHOG_INTENT=intent or "",+ HTTP_X_POSTHOG_MCP_CLIENT_IP="203.0.113.7",+ HTTP_X_POSTHOG_MCP_CLIENT_IP_TIMESTAMP=signed_at,+ HTTP_X_POSTHOG_MCP_CLIENT_IP_SIGNATURE=hmac.new(+ b"mcp-client-ip-test-key", f"203.0.113.7:{signed_at}".encode(), hashlib.sha256+ ).hexdigest(),+ )self.assertEqual(response.status_code, 201, response.content)log = ActivityLog.objects.filter(scope="Dashboard").latest("id")@@ -715,6 +725,7 @@ class TestAgentAttributionOnApiWrites(APIBaseTest):self.assertEqual(log.detail["trigger"], expected_trigger)self.assertEqual(log.user_id, self.user.id)self.assertEqual(log.client, "mcp")+ self.assertEqual(log.ip_address, "203.0.113.7")def test_recording_intent_does_not_re_enter_authentication(self) -> None:self._authenticate_as_oauth_agent(ARRAY_APP_CLIENT_ID_DEV, None)diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex ef65c4228f7e..bb5089439957 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -30,8 +30,9 @@ from social_core.exceptions import AuthCanceled, AuthFailed, AuthMissingParametefrom posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_teamfrom posthog.middleware import (+ ActivityLoggingMiddleware,ManagedProxyClientIPMiddleware,- ManagedProxyClientIPOutcome,+ SignedClientIPOutcome,per_request_logging_context_middleware,)from posthog.models.organization import Organization@@ -88,6 +89,24 @@ def _managed_proxy_headers(}+MCP_CLIENT_IP_KEY = "mcp-client-ip-test-key"+MCP_CLIENT_IP_OLD_KEY = "mcp-client-ip-old-key"+MCP_POD_IP = "10.0.0.5"+++def _mcp_client_ip_headers(+ ip: str = MANAGED_PROXY_CLIENT_IP,+ *,+ key: str = MCP_CLIENT_IP_KEY,+ timestamp: int | str = MANAGED_PROXY_NOW,+) -> dict[str, Any]: # dict[str, str] does not unpack into the test client's typed keyword arguments+ return {+ "HTTP_X_POSTHOG_MCP_CLIENT_IP": ip,+ "HTTP_X_POSTHOG_MCP_CLIENT_IP_TIMESTAMP": str(timestamp),+ "HTTP_X_POSTHOG_MCP_CLIENT_IP_SIGNATURE": _managed_proxy_signature(key, ip, str(timestamp)),+ }++class TestAccessMiddleware(APIBaseTest):CONFIG_AUTO_LOGIN = False@@ -267,7 +286,7 @@ class TestManagedProxyClientIPMiddleware(SimpleTestCase):"posthog_managed_proxy_client_ip_verifications_total", {"outcome": outcome.value})or 0.0- for outcome in ManagedProxyClientIPOutcome+ for outcome in SignedClientIPOutcome}def _run_middleware(self, meta: dict[str, Any], expected_outcome: str | None) -> tuple[str, str | None]:@@ -2164,6 +2183,81 @@ class TestActivityLoggingMiddleware(APIBaseTest):self.middleware(request)self.assertIsNone(self.captured["ip_address"])+ @parameterized.expand(+ [+ ("signed ip", _mcp_client_ip_headers(), [MCP_CLIENT_IP_KEY], MANAGED_PROXY_CLIENT_IP, "valid"),+ (+ "signed with an older key",+ _mcp_client_ip_headers("2001:db8::1", key=MCP_CLIENT_IP_OLD_KEY),+ [MCP_CLIENT_IP_KEY, MCP_CLIENT_IP_OLD_KEY],+ "2001:db8::1",+ "valid",+ ),+ (+ "signed with the managed proxy key",+ _mcp_client_ip_headers(key=MANAGED_PROXY_KEY),+ [MCP_CLIENT_IP_KEY],+ MCP_POD_IP,+ "bad_signature",+ ),+ ("no key configured", _mcp_client_ip_headers(), [], MCP_POD_IP, "not_configured"),+ (+ "expired timestamp",+ _mcp_client_ip_headers(timestamp=MANAGED_PROXY_NOW - 61),+ [MCP_CLIENT_IP_KEY],+ MCP_POD_IP,+ "timestamp_out_of_window",+ ),+ (+ "unsigned ip",+ {"HTTP_X_POSTHOG_MCP_CLIENT_IP": MANAGED_PROXY_CLIENT_IP},+ [MCP_CLIENT_IP_KEY],+ MCP_POD_IP,+ "invalid_input",+ ),+ ("no mcp headers", {}, [MCP_CLIENT_IP_KEY], MCP_POD_IP, None),+ ]+ )+ def test_mcp_signed_client_ip(+ self,+ _name: str,+ meta: dict[str, Any],+ signing_keys: list[str],+ expected_ip: str,+ expected_outcome: str | None,+ ) -> None:+ def verification_counts() -> dict[str, float]:+ return {+ outcome.value: REGISTRY.get_sample_value(+ "posthog_mcp_client_ip_verifications_total", {"outcome": outcome.value}+ )+ or 0.0+ for outcome in SignedClientIPOutcome+ }++ def get_response(request: HttpRequest) -> HttpResponse:+ self.captured["ip_address"] = self.activity_storage.get_ip_address()+ self.captured["request_ip"] = get_ip_address(request)+ self.captured["leftover"] = [name for name in request.headers if name.lower().startswith("x-posthog-mcp")]+ return HttpResponse()++ request = self.factory.get("/", REMOTE_ADDR=MCP_POD_IP, **meta)+ request.user = self.user+ # An earlier middleware may read request.headers, which caches a snapshot of META.+ assert request.headers.get("x-posthog-mcp-client-ip") == meta.get("HTTP_X_POSTHOG_MCP_CLIENT_IP")+ counts_before = verification_counts()++ with self.settings(MCP_CLIENT_IP_SIGNING_KEYS=signing_keys), time_machine.travel(MANAGED_PROXY_NOW, tick=False):+ ActivityLoggingMiddleware(get_response)(request)++ assert self.captured["ip_address"] == expected_ip+ assert self.captured["request_ip"] == MCP_POD_IP+ assert self.captured["leftover"] == []+ expected_counts = dict(counts_before)+ if expected_outcome:+ expected_counts[expected_outcome] += 1+ assert verification_counts() == expected_counts+class TestSocialAuthExceptionMiddleware(APIBaseTest):CONFIG_AUTO_LOGIN = False