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(proxy): harden managed proxy client ip handling (#102443)

Tom Piccirello155bf776ba31
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 86cf84f619bb..f1656b538faf 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -7,6 +7,7 @@ import posixpath
from collections.abc import Callable
from contextlib import suppress
from datetime import UTC, datetime, timedelta
+from enum import StrEnum
from ipaddress import ip_address, ip_network
from typing import Optional, cast
from urllib.parse import urlencode
@@ -47,6 +48,7 @@ from posthog.geoip import get_geoip_properties
from posthog.helpers.impersonation import get_original_user_from_session
from posthog.helpers.sso import sso_failure_redirect_url
from posthog.helpers.user_devices import set_known_device_cookie
+from posthog.ingress.verify.schemes import hmac_sha256_signature, signatures_match
from posthog.models import Organization, Team, User
from posthog.models.activity_logging.utils import ACTIVITY_LOG_CLIENT_HEADER, activity_storage, client_from_header
from posthog.models.utils import generate_random_token
@@ -118,6 +120,101 @@ default_cookie_options = {
cookie_api_paths_to_ignore = {"api", "flags", "scim"}
+MANAGED_PROXY_SIGNATURE_MAX_AGE_SECONDS = 60
+MANAGED_PROXY_SIGNATURE_MAX_CLOCK_SKEW_SECONDS = 5
+
+
+class ManagedProxyClientIPOutcome(StrEnum):
+ VALID = "valid"
+ # The instance holds no signing key, which is the normal state outside PostHog Cloud.
+ NOT_CONFIGURED = "not_configured"
+ TIMESTAMP_OUT_OF_WINDOW = "timestamp_out_of_window"
+ INVALID_INPUT = "invalid_input"
+ BAD_SIGNATURE = "bad_signature"
+
+
+# Alert on `valid` falling to zero while managed proxy traffic continues. Do not alert on the
+# failure outcomes, because anyone can raise those by sending forged headers to the origin.
+MANAGED_PROXY_CLIENT_IP_VERIFICATIONS = Counter(
+ "posthog_managed_proxy_client_ip_verifications",
+ "Verifications of the client IP that the managed reverse proxy signs, by outcome.",
+ ["outcome"],
+)
+
+
+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.
+ """
+ keys = [key for key in settings.MANAGED_PROXY_SIGNING_KEYS if key]
+ if not keys:
+ return ManagedProxyClientIPOutcome.NOT_CONFIGURED
+ if not ip or not timestamp or not signature:
+ return ManagedProxyClientIPOutcome.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
+ try:
+ ip_address(ip)
+ except ValueError:
+ return ManagedProxyClientIPOutcome.INVALID_INPUT
+ age_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
+
+ message = 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
+
+
+class ManagedProxyClientIPMiddleware:
+ """Use the client IP that the managed reverse proxy signed as the request's client IP.
+
+ Envoy sets X-Forwarded-For to its peer, which is a Cloudflare edge for managed proxy traffic.
+ Only a shared secret can recover the real client, because a Cloudflare edge range identifies
+ Cloudflare and not PostHog's Worker: any Cloudflare tenant can point a zone at this origin.
+ The ingress must therefore keep overwriting X-Forwarded-For rather than appending to it.
+
+ After a valid signature, X-Forwarded-For holds only the signed IP, so get_ip_address,
+ get_trusted_client_ip, axes, DRF throttles and the request log all see the real client.
+ The rewrite goes into request.META because axes/ipware and the DRF throttles read
+ HTTP_X_FORWARDED_FOR from META directly, which a request attribute would not reach.
+
+ REMOTE_ADDR stays the transport peer. get_trusted_client_ip then returns the signed IP only
+ when that peer is in TRUSTED_PROXIES, or when TRUST_ALL_PROXIES is set.
+
+ Any other outcome keeps the edge IP and lets the request through. The edge IP comes from Envoy
+ rather than from the client, so the fallback costs precision and not safety. A rejection would
+ instead turn a key or Worker mistake into failed requests on a path that carries event capture.
+ """
+
+ def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
+ self.get_response = get_response
+
+ def __call__(self, request: HttpRequest) -> HttpResponse:
+ # Remove the headers on every request, so that no later code can read an unverified value.
+ ip = request.META.pop("HTTP_X_POSTHOG_CLIENT_IP", None)
+ timestamp = request.META.pop("HTTP_X_POSTHOG_CLIENT_IP_TIMESTAMP", None)
+ signature = request.META.pop("HTTP_X_POSTHOG_CLIENT_IP_SIGNATURE", None)
+ 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)
+ MANAGED_PROXY_CLIENT_IP_VERIFICATIONS.labels(outcome=outcome.value).inc()
+ if outcome is ManagedProxyClientIPOutcome.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.
+ request.__dict__.pop("headers", None)
+ return self.get_response(request)
+
class AllowIPMiddleware:
def __init__(self, get_response):
diff --git a/posthog/settings/access.py b/posthog/settings/access.py
index 77fcd0c755c5..3e1e4c511d13 100644
--- a/posthog/settings/access.py
+++ b/posthog/settings/access.py
@@ -38,6 +38,11 @@ IS_BEHIND_PROXY = get_from_env("IS_BEHIND_PROXY", False, type_cast=str_to_bool)
TRUSTED_PROXIES = os.getenv("TRUSTED_PROXIES", None)
TRUST_ALL_PROXIES = get_from_env("TRUST_ALL_PROXIES", False, type_cast=str_to_bool)
+# Keys the managed reverse proxy uses to sign the client IP it forwards (ManagedProxyClientIPMiddleware).
+# Comma-separated, newest first: "<new>,<old>" while a rotation is in progress. Django accepts a
+# 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", ""))
+
if IS_BEHIND_PROXY:
USE_X_FORWARDED_HOST = True
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 7bc44be12559..b57420c28dac 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -161,6 +161,9 @@ INSTALLED_APPS = [
MIDDLEWARE = [
"django_prometheus.middleware.PrometheusBeforeMiddleware",
"posthog.gzip_middleware.ScopedGZipMiddleware",
+ # Must precede per_request_logging_context_middleware, the only client-IP reader that runs on
+ # the request path. AllowIPMiddleware and axes read the IP at or after the view.
+ "posthog.middleware.ManagedProxyClientIPMiddleware",
"posthog.middleware.per_request_logging_context_middleware",
"django_structlog.middlewares.RequestMiddleware",
"posthog.middleware.Fix204Middleware",
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 19a127669e40..ddf945db50db 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -1,4 +1,6 @@
+import hmac
import json
+import hashlib
from datetime import datetime, timedelta
from typing import Any, cast
@@ -20,18 +22,26 @@ from django.urls import reverse
import structlog
from loginas import settings as la_settings
from parameterized import parameterized
+from prometheus_client import REGISTRY
from rest_framework import status
from social_core.backends.base import BaseAuth
from social_core.exceptions import AuthCanceled, AuthFailed, AuthMissingParameter
from posthog.api.test.test_organization import create_organization
from posthog.api.test.test_team import create_team
-from posthog.middleware import CSPMiddleware, app_csp_header_name, per_request_logging_context_middleware
+from posthog.middleware import (
+ CSPMiddleware,
+ ManagedProxyClientIPMiddleware,
+ ManagedProxyClientIPOutcome,
+ app_csp_header_name,
+ per_request_logging_context_middleware,
+)
from posthog.models.organization import Organization
from posthog.models.organization_invite import OrganizationInvite
from posthog.models.team import Team
from posthog.models.user import User
from posthog.settings import SITE_URL
+from posthog.utils import get_ip_address, get_trusted_client_ip
from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort
@@ -44,6 +54,42 @@ def _social_auth_backend() -> BaseAuth:
return cast(BaseAuth, MagicMock())
+MANAGED_PROXY_KEY = "managed-proxy-test-key"
+MANAGED_PROXY_OLD_KEY = "managed-proxy-old-key"
+MANAGED_PROXY_NOW = 1_800_000_000
+MANAGED_PROXY_EDGE_IP = "198.51.100.10"
+MANAGED_PROXY_CLIENT_IP = "203.0.113.7"
+# GeoIP resolves these two, so the geo-block can tell them apart.
+MANAGED_PROXY_GERMAN_CLIENT_IP = "45.90.4.87"
+MANAGED_PROXY_NON_GERMAN_EDGE_IP = "28.160.62.192"
+# hex(HMAC-SHA256(MANAGED_PROXY_KEY, f"{MANAGED_PROXY_CLIENT_IP}:{MANAGED_PROXY_NOW}")), computed
+# independently of _managed_proxy_signature so that it pins the format the Worker also asserts.
+MANAGED_PROXY_KNOWN_ANSWER_SIGNATURE = "f825f520f1c3a2ef243b6a055a528b8ce94a3b4b9110bb6f3c2b568191e7b717"
+MANAGED_PROXY_KNOWN_ANSWER_HEADERS = {
+ "HTTP_X_POSTHOG_CLIENT_IP": MANAGED_PROXY_CLIENT_IP,
+ "HTTP_X_POSTHOG_CLIENT_IP_TIMESTAMP": str(MANAGED_PROXY_NOW),
+ "HTTP_X_POSTHOG_CLIENT_IP_SIGNATURE": MANAGED_PROXY_KNOWN_ANSWER_SIGNATURE,
+}
+
+
+def _managed_proxy_signature(key: str, ip: str, timestamp: str) -> str:
+ return hmac.new(key.encode(), f"{ip}:{timestamp}".encode(), hashlib.sha256).hexdigest()
+
+
+def _managed_proxy_headers(
+ ip: str = MANAGED_PROXY_CLIENT_IP,
+ *,
+ key: str = MANAGED_PROXY_KEY,
+ signed_ip: str | None = None,
+ 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_CLIENT_IP": ip,
+ "HTTP_X_POSTHOG_CLIENT_IP_TIMESTAMP": str(timestamp),
+ "HTTP_X_POSTHOG_CLIENT_IP_SIGNATURE": _managed_proxy_signature(key, signed_ip or ip, str(timestamp)),
+ }
+
+
class TestAccessMiddleware(APIBaseTest):
CONFIG_AUTO_LOGIN = False
@@ -191,6 +237,147 @@ class TestAccessMiddleware(APIBaseTest):
response = self.client.get("/", headers={"x-forwarded-for": "192.168.1.1"})
self.assertNotIn(b"PostHog is not available", response.content)
+ @parameterized.expand([("signed", MANAGED_PROXY_KEY, True), ("unsigned", "some-other-key", False)])
+ def test_blocked_geoip_regions_sees_managed_proxy_client_ip(self, _name: str, key: str, blocked: bool) -> None:
+ with (
+ self.settings(
+ BLOCKED_GEOIP_REGIONS=["DE"],
+ USE_X_FORWARDED_HOST=True,
+ TRUST_ALL_PROXIES=True,
+ MANAGED_PROXY_SIGNING_KEYS=[MANAGED_PROXY_KEY],
+ ),
+ time_machine.travel(MANAGED_PROXY_NOW, tick=False),
+ ):
+ response = self.client.get(
+ "/",
+ HTTP_X_FORWARDED_FOR=MANAGED_PROXY_NON_GERMAN_EDGE_IP,
+ **_managed_proxy_headers(MANAGED_PROXY_GERMAN_CLIENT_IP, key=key),
+ )
+
+ assert (b"PostHog is not available" in response.content) is blocked
+
+
+@override_settings(
+ MANAGED_PROXY_SIGNING_KEYS=[MANAGED_PROXY_KEY, MANAGED_PROXY_OLD_KEY],
+ USE_X_FORWARDED_HOST=True,
+ TRUST_ALL_PROXIES=True,
+)
+class TestManagedProxyClientIPMiddleware(SimpleTestCase):
+ def _verification_counts(self) -> dict[str, float]:
+ return {
+ outcome.value: REGISTRY.get_sample_value(
+ "posthog_managed_proxy_client_ip_verifications_total", {"outcome": outcome.value}
+ )
+ or 0.0
+ for outcome in ManagedProxyClientIPOutcome
+ }
+
+ def _run_middleware(self, meta: dict[str, Any], expected_outcome: str | None) -> tuple[str, str | None]:
+ counts_before = self._verification_counts()
+ request = RequestFactory().get("/", REMOTE_ADDR="10.0.0.5", HTTP_X_FORWARDED_FOR=MANAGED_PROXY_EDGE_IP, **meta)
+ # An earlier middleware may read request.headers, which caches a snapshot of META.
+ assert request.headers.get("x-forwarded-for") == MANAGED_PROXY_EDGE_IP
+ seen: dict[str, Any] = {}
+
+ def get_response(request: HttpRequest) -> HttpResponse:
+ seen["ips"] = (get_ip_address(request), get_trusted_client_ip(request))
+ seen["leftover"] = [key for key in request.META if key.startswith("HTTP_X_POSTHOG_CLIENT_IP")] + [
+ name for name in request.headers if name.lower().startswith("x-posthog-client-ip")
+ ]
+ return HttpResponse()
+
+ with time_machine.travel(MANAGED_PROXY_NOW, tick=False):
+ ManagedProxyClientIPMiddleware(get_response)(request)
+
+ assert seen["leftover"] == []
+ expected_counts = dict(counts_before)
+ if expected_outcome:
+ expected_counts[expected_outcome] += 1
+ assert self._verification_counts() == expected_counts
+ return seen["ips"]
+
+ @parameterized.expand(
+ [
+ ("known_answer_vector", MANAGED_PROXY_KNOWN_ANSWER_HEADERS, MANAGED_PROXY_CLIENT_IP),
+ (
+ "uppercase_hex",
+ {
+ **MANAGED_PROXY_KNOWN_ANSWER_HEADERS,
+ "HTTP_X_POSTHOG_CLIENT_IP_SIGNATURE": MANAGED_PROXY_KNOWN_ANSWER_SIGNATURE.upper(),
+ },
+ MANAGED_PROXY_CLIENT_IP,
+ ),
+ ("older_key", _managed_proxy_headers(key=MANAGED_PROXY_OLD_KEY), MANAGED_PROXY_CLIENT_IP),
+ ("ipv6", _managed_proxy_headers("2001:db8::1"), "2001:db8::1"),
+ ("oldest_timestamp", _managed_proxy_headers(timestamp=MANAGED_PROXY_NOW - 60), MANAGED_PROXY_CLIENT_IP),
+ ("newest_timestamp", _managed_proxy_headers(timestamp=MANAGED_PROXY_NOW + 5), MANAGED_PROXY_CLIENT_IP),
+ ]
+ )
+ def test_valid_signature_sets_client_ip(self, _name: str, meta: dict[str, Any], expected_ip: str) -> None:
+ assert self._run_middleware(meta, "valid") == (expected_ip, expected_ip)
+
+ @parameterized.expand(
+ [
+ ("no_headers", {}, None),
+ ("unknown_key", _managed_proxy_headers(key="some-other-key"), "bad_signature"),
+ ("signed_for_another_ip", _managed_proxy_headers(signed_ip="192.0.2.1"), "bad_signature"),
+ (
+ "expired_timestamp",
+ _managed_proxy_headers(timestamp=MANAGED_PROXY_NOW - 61),
+ "timestamp_out_of_window",
+ ),
+ (
+ "future_timestamp",
+ _managed_proxy_headers(timestamp=MANAGED_PROXY_NOW + 6),
+ "timestamp_out_of_window",
+ ),
+ ("non_numeric_timestamp", _managed_proxy_headers(timestamp="1800000000.0"), "invalid_input"),
+ ("oversized_timestamp", _managed_proxy_headers(timestamp="1" * 5000), "invalid_input"),
+ ("malformed_ip", _managed_proxy_headers("not-an-ip"), "invalid_input"),
+ (
+ "missing_timestamp",
+ {k: v for k, v in _managed_proxy_headers().items() if k != "HTTP_X_POSTHOG_CLIENT_IP_TIMESTAMP"},
+ "invalid_input",
+ ),
+ (
+ "empty_signature",
+ {**_managed_proxy_headers(), "HTTP_X_POSTHOG_CLIENT_IP_SIGNATURE": ""},
+ "invalid_input",
+ ),
+ (
+ "non_ascii_signature",
+ {**_managed_proxy_headers(), "HTTP_X_POSTHOG_CLIENT_IP_SIGNATURE": "é" * 64},
+ "bad_signature",
+ ),
+ ]
+ )
+ def test_unverified_request_keeps_edge_ip(
+ self, _name: str, meta: dict[str, Any], expected_outcome: str | None
+ ) -> None:
+ assert self._run_middleware(meta, expected_outcome) == (MANAGED_PROXY_EDGE_IP, MANAGED_PROXY_EDGE_IP)
+
+ @parameterized.expand(
+ [
+ ("no_keys", [], "not_configured"),
+ ("empty_key", [""], "not_configured"),
+ ("empty_key_in_list", [MANAGED_PROXY_KEY, ""], "bad_signature"),
+ ]
+ )
+ def test_signing_key_list_keeps_edge_ip(self, _name: str, keys: list[str], expected_outcome: str) -> None:
+ with self.settings(MANAGED_PROXY_SIGNING_KEYS=keys):
+ client_ips = self._run_middleware(_managed_proxy_headers(key="some-other-key"), expected_outcome)
+
+ assert client_ips == (MANAGED_PROXY_EDGE_IP, MANAGED_PROXY_EDGE_IP)
+
+ def test_runs_before_the_middleware_that_logs_the_forwarded_for_header(self) -> None:
+ # per_request_logging_context_middleware reads x-forwarded-for on the request path, so it
+ # only records the signed IP while it stays below this middleware. AllowIPMiddleware and axes
+ # read the client IP at or after the view, so their position does not constrain this one.
+ middleware = list(settings.MIDDLEWARE)
+ assert middleware.index("posthog.middleware.ManagedProxyClientIPMiddleware") < middleware.index(
+ "posthog.middleware.per_request_logging_context_middleware"
+ )
+
class TestAutoProjectMiddleware(APIBaseTest):
# How many queries are made in the base app