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.

feat(cloud-spend): serve personal spend to EU via signed cross-region proxy (#69310)

Alessandro Pogliaghi020d7ad3b818
diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.py
index 6915e6de784d..987b2fbf86fb 100644
--- a/posthog/settings/base_variables.py
+++ b/posthog/settings/base_variables.py
@@ -68,6 +68,10 @@ GITHUB_SECRET_ALERT_RELAY_URL: str | None = get_from_env("GITHUB_SECRET_ALERT_RE
# Override in tests via @override_settings to point at a per-test team.
LLM_ANALYTICS_INTERNAL_TEAM_ID: int = 2
+# Shared secret for EU→US personal-spend proxy calls (products/ai_observability).
+# Must hold the same value in both regions; unset disables the proxy.
+PERSONAL_SPEND_CROSS_REGION_SECRET: str = get_from_env("PERSONAL_SPEND_CROSS_REGION_SECRET", "")
+
# Override for the AI observability trial-eval deprecation cutoff
AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE: str | None = get_from_env(
"AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE", optional=True
diff --git a/posthog/urls.py b/posthog/urls.py
index 41f2504051da..d0a2bdbe7f2f 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -45,7 +45,7 @@ from posthog.models.instance_setting import get_instance_setting
from posthog.oauth2_urls import urlpatterns as oauth2_urls
from posthog.temporal.codec_server import decode_payloads
-from products.ai_observability.backend.api.personal_spend import personal_spend_eu_redirect
+from products.ai_observability.backend.api.personal_spend import PersonalSpendEUProxyViewSet
from products.cdp.backend.api import hog_function_template
from products.data_warehouse.backend.presentation.views.public_source_configs import PublicSourceConfigViewSet
from products.demo.backend.facade.api import demo_route
@@ -575,16 +575,16 @@ urlpatterns = [
]
# Personal LLM spend data only lives in PostHog Cloud US — EU forwards its product
-# LLM telemetry over, so EU callers get a 302 to the US-hosted endpoint instead of
-# a silent 404. Must be inserted *before* the `^api.+` catch-all above; otherwise
-# the catch-all matches first and the redirect is unreachable.
+# LLM telemetry over — so the EU view proxies the query to US server-side. Must be
+# inserted *before* the `^api.+` catch-all above; otherwise the catch-all matches
+# first and the view is unreachable.
if settings.CLOUD_DEPLOYMENT == "EU":
urlpatterns.insert(
0,
path(
"api/llm_analytics/@me/spend/",
- personal_spend_eu_redirect,
- name="personal_spend_eu_redirect",
+ PersonalSpendEUProxyViewSet.as_view({"get": "list"}),
+ name="personal_spend_eu",
),
)
diff --git a/products/ai_observability/backend/api/__init__.py b/products/ai_observability/backend/api/__init__.py
index e6fc1b9bcacc..3e80e6eaa918 100644
--- a/products/ai_observability/backend/api/__init__.py
+++ b/products/ai_observability/backend/api/__init__.py
@@ -10,7 +10,7 @@ from .evaluations import EvaluationViewSet
from .models import LLMModelsViewSet
from .offline_evaluations import AIObservabilityOfflineEvaluationsViewSet
from .parser_recipes import ParserRecipeViewSet
-from .personal_spend import PersonalSpendViewSet
+from .personal_spend import PersonalSpendInternalViewSet, PersonalSpendViewSet
from .provider_keys import LLMProviderKeyValidationViewSet, LLMProviderKeyViewSet
from .proxy import SUPPORTED_MODELS_WITH_THINKING, LLMProxyViewSet
from .review_queues import ReviewQueueItemViewSet, ReviewQueueViewSet
@@ -44,6 +44,7 @@ __all__ = [
"ReviewQueueItemViewSet",
"ScoreDefinitionViewSet",
"AIObservabilityOfflineEvaluationsViewSet",
+ "PersonalSpendInternalViewSet",
"PersonalSpendViewSet",
"TaggerViewSet",
"TraceReviewViewSet",
diff --git a/products/ai_observability/backend/api/personal_spend.py b/products/ai_observability/backend/api/personal_spend.py
index 5691a11eae89..6d3d934dff11 100644
--- a/products/ai_observability/backend/api/personal_spend.py
+++ b/products/ai_observability/backend/api/personal_spend.py
@@ -13,15 +13,21 @@ Endpoint:
from __future__ import annotations
import re
+import hmac
+import json
+import time
+import hashlib
import datetime
from typing import Any, cast
from urllib.parse import urlencode
from zoneinfo import ZoneInfo
from django.conf import settings
+from django.contrib.auth.models import AnonymousUser
from django.core.cache import cache
-from django.http import HttpRequest, HttpResponseRedirect
+from django.http import HttpRequest, HttpResponseBase, HttpResponseRedirect
+import requests
import structlog
from drf_spectacular.utils import extend_schema
from rest_framework import exceptions, permissions, serializers, status, viewsets
@@ -34,7 +40,12 @@ from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
-from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.auth import (
+ OAuthAccessTokenAuthentication,
+ PersonalAPIKeyAuthentication,
+ SessionAuthentication,
+ WebhookSignatureAuthentication,
+)
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.models import Team, User
from posthog.permissions import APIScopePermission
@@ -612,7 +623,90 @@ def _fetch_by_day(
return _truncate(rows, BY_DAY_MAX_ROWS)
-class PersonalSpendViewSet(viewsets.ViewSet):
+def _compute_spend_analysis(
+ *,
+ email: str,
+ date_from: str,
+ date_to: str | None,
+ product: str,
+ limit: int,
+ refresh: bool,
+) -> dict[str, Any]:
+ """Cached, email-scoped spend analysis shared by the US viewset and the
+ cross-region receiver. Expects already-validated params."""
+ from_dt, to_dt = _resolve_window(date_from, date_to)
+
+ cache_key = _cache_key(email, date_from, date_to, product, limit)
+
+ if not refresh:
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return cached
+
+ team_id = _internal_team_id()
+ try:
+ team = Team.objects.get(pk=team_id)
+ except Team.DoesNotExist:
+ logger.exception("personal_spend.team_missing", team_id=team_id)
+ raise exceptions.NotFound("Internal analytics team is not provisioned on this deployment.")
+
+ # Tag the underlying ClickHouse reads with the LLM_ANALYTICS product so they show up
+ # in the existing per-product Prometheus + cost-attribution dashboards alongside the
+ # rest of AI observability traffic. Wraps every call into `_fetch_*` -> HogQL.
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team_id):
+ summary = _fetch_summary(team, email, from_dt, to_dt, product)
+ by_tool = _fetch_by_tool(team, email, from_dt, to_dt, product, limit)
+ scoped = summary["scoped_cost_usd"] or 0.0
+ # `cost_usd` in by_tool can exceed scoped_cost_usd because multi-tool generations
+ # contribute to every tool. `share_of_scoped` is independent per row, so agents can
+ # present headline percentages directly without reconciling sums.
+ for row in by_tool["items"]:
+ row["share_of_scoped"] = (row["cost_usd"] / scoped) if scoped > 0 else 0.0
+
+ payload = {
+ "summary": summary,
+ "by_product": _fetch_by_product(team, email, from_dt, to_dt, limit),
+ "by_tool": by_tool,
+ "by_model": _fetch_by_model(team, email, from_dt, to_dt, product, limit),
+ "by_day": _fetch_by_day(team, email, from_dt, to_dt, product),
+ # Deprecated — trace IDs are opaque and unactionable in the UI. Returned empty so
+ # existing consumers don't crash while they remove the rendering. Drop the field
+ # entirely once no consumer reads it.
+ "top_traces": {"items": [], "truncated": False},
+ }
+
+ response_data = PersonalSpendAnalysisResponseSerializer(payload).data
+ cache.set(cache_key, response_data, timeout=CACHE_TIMEOUT_SECONDS)
+ return response_data
+
+
+class _PersonalSpendUserViewSet(viewsets.ViewSet):
+ """Base with the auth surface shared by the US viewset and the EU proxy so
+ the regions stay indistinguishable to clients. The US internal receiver
+ relies on this EU-side throttling as its only rate limit."""
+
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+ permission_classes = [permissions.IsAuthenticated, APIScopePermission]
+ # Identity-scoped (`/@me/...`): the caller reads their own spend, not data
+ # nested under a team or project. `scope_object = "user"` matches the shape
+ # of `/api/users/@me/` — APIScopePermission already exempts the `user`
+ # bucket from team/org scoping, so we don't need
+ # `dangerously_skip_scoped_team_enforcement` here. `user:read` is a clean
+ # superset of "read your own spend": anyone trusted with `user:read`
+ # already learns the more sensitive identity facts on `/api/users/@me/`,
+ # and the wildcard `*` plus OAuth identity tokens (MCP) inherit access
+ # the same way they do for every other `user`-scoped endpoint.
+ scope_object = "user"
+ throttle_classes = [PersonalSpendBurstThrottle, PersonalSpendSustainedThrottle, PersonalSpendDailyThrottle]
+
+ def _require_email(self, request: Request) -> str:
+ email = cast(User, request.user).email
+ if not email:
+ raise exceptions.PermissionDenied("User has no email on record; cannot scope spend analysis.")
+ return email
+
+
+class PersonalSpendViewSet(_PersonalSpendUserViewSet):
"""
Returns the requesting user's personal LLM spend analysis across PostHog products.
@@ -638,29 +732,10 @@ class PersonalSpendViewSet(viewsets.ViewSet):
`SUPPORTED_PRODUCTS` for the currently accepted values. `by_product` always
returns the full cross-product breakdown. The endpoint is only registered
on US Cloud + dev/test envs; hobby / self-hosted deploys never see this
- URL; EU deploys receive a 302 to the US URL.
+ URL; EU deploys serve it via `PersonalSpendEUProxyViewSet` (or a 302 to
+ the US URL while the cross-region secret is unprovisioned).
"""
- authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
- permission_classes = [permissions.IsAuthenticated, APIScopePermission]
- # Identity-scoped (`/@me/...`): the caller reads their own spend, not data
- # nested under a team or project. `scope_object = "user"` matches the shape
- # of `/api/users/@me/` — APIScopePermission already exempts the `user`
- # bucket from team/org scoping, so we don't need
- # `dangerously_skip_scoped_team_enforcement` here. `user:read` is a clean
- # superset of "read your own spend": anyone trusted with `user:read`
- # already learns the more sensitive identity facts on `/api/users/@me/`,
- # and the wildcard `*` plus OAuth identity tokens (MCP) inherit access
- # the same way they do for every other `user`-scoped endpoint.
- scope_object = "user"
-
- def get_throttles(self):
- return [
- PersonalSpendBurstThrottle(),
- PersonalSpendSustainedThrottle(),
- PersonalSpendDailyThrottle(),
- ]
-
@extend_schema(
operation_id="llm_analytics_personal_spend_list",
parameters=[_SpendQueryParamsSerializer],
@@ -684,62 +759,12 @@ class PersonalSpendViewSet(viewsets.ViewSet):
tags=["AI observability"],
)
def list(self, request: Request) -> Response:
- user = cast(User, request.user)
- email = user.email
- if not email:
- raise exceptions.PermissionDenied("User has no email on record; cannot scope spend analysis.")
+ email = self._require_email(request)
params = _SpendQueryParamsSerializer(data=request.query_params)
params.is_valid(raise_exception=True)
- date_from = params.validated_data["date_from"]
- date_to = params.validated_data["date_to"]
- product = params.validated_data["product"]
- limit = params.validated_data["limit"]
- refresh = params.validated_data["refresh"]
-
- from_dt, to_dt = _resolve_window(date_from, date_to)
- cache_key = _cache_key(email, date_from, date_to, product, limit)
-
- if not refresh:
- cached = cache.get(cache_key)
- if cached is not None:
- return Response(cached, status=status.HTTP_200_OK)
-
- team_id = _internal_team_id()
- try:
- team = Team.objects.get(pk=team_id)
- except Team.DoesNotExist:
- logger.exception("personal_spend.team_missing", team_id=team_id)
- raise exceptions.NotFound("Internal analytics team is not provisioned on this deployment.")
-
- # Tag the underlying ClickHouse reads with the LLM_ANALYTICS product so they show up
- # in the existing per-product Prometheus + cost-attribution dashboards alongside the
- # rest of AI observability traffic. Wraps every call into `_fetch_*` -> HogQL.
- with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team_id):
- summary = _fetch_summary(team, email, from_dt, to_dt, product)
- by_tool = _fetch_by_tool(team, email, from_dt, to_dt, product, limit)
- scoped = summary["scoped_cost_usd"] or 0.0
- # `cost_usd` in by_tool can exceed scoped_cost_usd because multi-tool generations
- # contribute to every tool. `share_of_scoped` is independent per row, so agents can
- # present headline percentages directly without reconciling sums.
- for row in by_tool["items"]:
- row["share_of_scoped"] = (row["cost_usd"] / scoped) if scoped > 0 else 0.0
-
- payload = {
- "summary": summary,
- "by_product": _fetch_by_product(team, email, from_dt, to_dt, limit),
- "by_tool": by_tool,
- "by_model": _fetch_by_model(team, email, from_dt, to_dt, product, limit),
- "by_day": _fetch_by_day(team, email, from_dt, to_dt, product),
- # Deprecated — trace IDs are opaque and unactionable in the UI. Returned empty so
- # existing consumers don't crash while they remove the rendering. Drop the field
- # entirely once no consumer reads it.
- "top_traces": {"items": [], "truncated": False},
- }
-
- response_data = PersonalSpendAnalysisResponseSerializer(payload).data
- cache.set(cache_key, response_data, timeout=CACHE_TIMEOUT_SECONDS)
+ response_data = _compute_spend_analysis(email=email, **params.validated_data)
return Response(response_data, status=status.HTTP_200_OK)
@@ -754,6 +779,9 @@ def personal_spend_eu_redirect(request: HttpRequest) -> HttpResponseRedirect:
spend analysis only runs there. Returning a 302 makes the new home discoverable
instead of serving a silent 404. Callers still need a US-valid auth token.
+ Now only the fallback path of `PersonalSpendEUProxyViewSet`, used while
+ `PERSONAL_SPEND_CROSS_REGION_SECRET` is not provisioned.
+
The target host is hardcoded — only an allowlist of known params is forwarded
(re-encoded via `urlencode`) so a malicious caller cannot smuggle extra path or
fragment characters into the redirect target.
@@ -763,3 +791,157 @@ def personal_spend_eu_redirect(request: HttpRequest) -> HttpResponseRedirect:
if safe_params:
target = f"{target}?{urlencode(safe_params)}"
return HttpResponseRedirect(target)
+
+
+# EU → US cross-region proxy: spend data only lives on US Cloud and EU
+# credentials are not valid there, so the EU deployment authenticates the
+# caller itself and asserts the verified email to a US-side internal endpoint
+# over an HMAC-signed server-to-server call (same pattern as the Slack app's
+# cross-region probe in products/slack_app/backend/api.py).
+
+CROSS_REGION_SIGNATURE_HEADER = "X-PostHog-Spend-Signature"
+CROSS_REGION_TIMESTAMP_HEADER = "X-PostHog-Spend-Timestamp"
+# Fast connect failure; cold spend runs take a few seconds of ClickHouse time.
+CROSS_REGION_TIMEOUT_SECONDS = (3, 15)
+_CROSS_REGION_INTERNAL_PATH = "/api/llm_analytics/internal/spend/"
+
+
+def _cross_region_target_url() -> str:
+ # Under DEBUG a single instance plays both regions (Slack proxy's dev topology).
+ if settings.DEBUG:
+ return f"{settings.SITE_URL}{_CROSS_REGION_INTERNAL_PATH}"
+ return f"https://us.posthog.com{_CROSS_REGION_INTERNAL_PATH}"
+
+
+def sign_cross_region_spend_request(body: bytes, secret: str, *, timestamp: int | None = None) -> tuple[str, str]:
+ """HMAC-SHA256 hexdigest over `v0:{ts}:{body}`; the sending half of
+ `PersonalSpendCrossRegionAuthentication`. Returns (signature, timestamp)."""
+ ts = str(int(time.time()) if timestamp is None else timestamp)
+ hmac_input = f"v0:{ts}:{body.decode('utf-8')}"
+ digest = hmac.new(secret.encode("utf-8"), hmac_input.encode("utf-8"), digestmod=hashlib.sha256).hexdigest()
+ return digest, ts
+
+
+class PersonalSpendCrossRegionAuthentication(WebhookSignatureAuthentication):
+ """HMAC verification for the EU→US personal-spend proxy. The base class
+ fails closed on missing headers, unset secret, stale timestamp, or digest
+ mismatch; the asserted identity lives in the signed body, not `request.user`."""
+
+ def get_signature_header(self) -> str:
+ return CROSS_REGION_SIGNATURE_HEADER
+
+ def get_timestamp_header(self) -> str:
+ return CROSS_REGION_TIMESTAMP_HEADER
+
+ def build_hmac_input(self, timestamp: str, body: str) -> str:
+ return f"v0:{timestamp}:{body}"
+
+ def get_signing_secret(self, request: Request) -> str | None:
+ return settings.PERSONAL_SPEND_CROSS_REGION_SECRET or None
+
+ def authenticate(self, request: Request) -> tuple[AnonymousUser, Any] | None:
+ try:
+ return super().authenticate(request)
+ except UnicodeDecodeError:
+ # The base class decodes the raw body before verifying; garbage
+ # bytes must be an auth failure, not a 500.
+ raise exceptions.AuthenticationFailed("Invalid request body encoding.")
+
+
+class _InternalSpendRequestSerializer(_SpendQueryParamsSerializer):
+ """The EU proxy's payload: the standard query params plus the EU-verified email."""
+
+ email = serializers.EmailField(required=True, allow_blank=False)
+
+
+class PersonalSpendInternalViewSet(viewsets.ViewSet):
+ """US-side receiver for the EU personal-spend proxy (US + dev/test only).
+ The asserted `email` is trusted because the body is HMAC-signed with the
+ region-shared secret; the EU side authenticates and throttles the user
+ before the hop, so no throttles here."""
+
+ authentication_classes = [PersonalSpendCrossRegionAuthentication]
+ permission_classes = []
+ throttle_classes = []
+
+ @extend_schema(exclude=True)
+ def create(self, request: Request) -> Response:
+ params = _InternalSpendRequestSerializer(data=request.data)
+ params.is_valid(raise_exception=True)
+
+ return Response(_compute_spend_analysis(**params.validated_data), status=status.HTTP_200_OK)
+
+
+class _CrossRegionUpstreamError(exceptions.APIException):
+ status_code = status.HTTP_502_BAD_GATEWAY
+ default_detail = "Spend analysis is temporarily unavailable."
+ default_code = "cross_region_upstream_unavailable"
+
+
+class PersonalSpendEUProxyViewSet(_PersonalSpendUserViewSet):
+ """EU `/api/llm_analytics/@me/spend/`: authenticates locally, fetches from
+ US server-side. Falls back to the 302 redirect while the secret is unset."""
+
+ @extend_schema(
+ operation_id="llm_analytics_personal_spend_eu_list",
+ parameters=[_SpendQueryParamsSerializer],
+ responses={200: PersonalSpendAnalysisResponseSerializer},
+ description="EU mirror of the personal spend endpoint — proxies to PostHog Cloud US, where the data lives.",
+ tags=["AI observability"],
+ )
+ def list(self, request: Request) -> HttpResponseBase:
+ secret = settings.PERSONAL_SPEND_CROSS_REGION_SECRET
+ if not secret:
+ return personal_spend_eu_redirect(request._request)
+
+ email = self._require_email(request)
+
+ # Validate in-region so bad requests 400 without paying for the hop.
+ params = _SpendQueryParamsSerializer(data=request.query_params)
+ params.is_valid(raise_exception=True)
+ data = params.validated_data
+
+ # Same cache as the US compute path, so repeat loads skip the cross-region hop.
+ cache_key = _cache_key(email, data["date_from"], data["date_to"], data["product"], data["limit"])
+ if not data["refresh"]:
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return Response(cached, status=status.HTTP_200_OK)
+
+ body = json.dumps({**data, "email": email}).encode("utf-8")
+ signature, ts = sign_cross_region_spend_request(body, secret)
+ try:
+ upstream = requests.post(
+ _cross_region_target_url(),
+ data=body,
+ headers={
+ "Content-Type": "application/json",
+ CROSS_REGION_SIGNATURE_HEADER: signature,
+ CROSS_REGION_TIMESTAMP_HEADER: ts,
+ },
+ timeout=CROSS_REGION_TIMEOUT_SECONDS,
+ )
+ except requests.RequestException as exc:
+ logger.exception("personal_spend.cross_region_proxy_failed", error=str(exc))
+ raise _CrossRegionUpstreamError()
+
+ if upstream.status_code == status.HTTP_200_OK:
+ try:
+ payload = upstream.json()
+ except ValueError:
+ logger.exception("personal_spend.cross_region_proxy_bad_json")
+ raise _CrossRegionUpstreamError()
+ cache.set(cache_key, payload, timeout=CACHE_TIMEOUT_SECONDS)
+ return Response(payload, status=status.HTTP_200_OK)
+
+ # Relay caller-attributable upstream errors; anything else (including a
+ # 401 secret mismatch between regions) is a 502.
+ if upstream.status_code in (status.HTTP_400_BAD_REQUEST, status.HTTP_429_TOO_MANY_REQUESTS):
+ try:
+ detail = upstream.json()
+ except ValueError:
+ detail = {"detail": f"Upstream error {upstream.status_code}"}
+ return Response(detail, status=upstream.status_code)
+
+ logger.error("personal_spend.cross_region_proxy_non_success", status_code=upstream.status_code)
+ raise _CrossRegionUpstreamError()
diff --git a/products/ai_observability/backend/api/test/test_personal_spend.py b/products/ai_observability/backend/api/test/test_personal_spend.py
index 56d7bd4eb2ed..f30fbf760858 100644
--- a/products/ai_observability/backend/api/test/test_personal_spend.py
+++ b/products/ai_observability/backend/api/test/test_personal_spend.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import json
+import time
from datetime import UTC, datetime, timedelta
from posthog.test.base import (
@@ -14,16 +16,26 @@ from posthog.test.base import (
)
from unittest.mock import patch
+from django.core.cache import cache
from django.test import override_settings
from django.utils import timezone
+import requests
from parameterized import parameterized
from rest_framework import status
+from rest_framework.test import APIRequestFactory, force_authenticate
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from products.ai_observability.backend.api.personal_spend import (
+ CROSS_REGION_SIGNATURE_HEADER,
+ CROSS_REGION_TIMESTAMP_HEADER,
+ PersonalSpendEUProxyViewSet,
+ sign_cross_region_spend_request,
+)
+
ENDPOINT = "/api/llm_analytics/@me/spend/"
# `product` is required server-side; spell that out once for every happy-path test.
PRODUCT_QS = "product=posthog_code"
@@ -536,3 +548,216 @@ class TestPersonalSpendNonSessionAuth(APIBaseTest):
token = self._make_oauth_token(scope)
response = self.client.get(ENDPOINT_OK, headers={"authorization": f"Bearer {token}"})
assert response.status_code == expected, response.content
+
+
+INTERNAL_ENDPOINT = "/api/llm_analytics/internal/spend/"
+CROSS_REGION_SECRET = "test-cross-region-secret"
+
+
+def _json_body(payload: dict) -> bytes:
+ return json.dumps(payload).encode("utf-8")
+
+
+def _signed_headers(body: bytes, secret: str = CROSS_REGION_SECRET, timestamp: int | None = None) -> dict[str, str]:
+ signature, ts = sign_cross_region_spend_request(body, secret, timestamp=timestamp)
+ return {CROSS_REGION_SIGNATURE_HEADER: signature, CROSS_REGION_TIMESTAMP_HEADER: ts}
+
+
+class TestPersonalSpendInternalEndpoint(ClickhouseTestMixin, APIBaseTest):
+ """The US-side receiver of the EU→US proxy: HMAC-gated, no user auth."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ overrides = override_settings(
+ LLM_ANALYTICS_INTERNAL_TEAM_ID=self.team.id,
+ PERSONAL_SPEND_CROSS_REGION_SECRET=CROSS_REGION_SECRET,
+ )
+ overrides.enable()
+ self.addCleanup(overrides.disable)
+ cache.clear()
+ # No session — the endpoint must work purely off the signature.
+ self.client.logout()
+ self.payload = {"email": "[email protected]", "product": "posthog_code"}
+ self.body = _json_body(self.payload)
+
+ def _post(self, body: bytes, headers: dict[str, str] | None = None):
+ return self.client.post(
+ INTERNAL_ENDPOINT,
+ data=body,
+ content_type="application/json",
+ headers=headers or {},
+ )
+
+ def test_unsigned_request_rejected(self) -> None:
+ response = self._post(self.body)
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_wrong_secret_rejected(self) -> None:
+ response = self._post(self.body, _signed_headers(self.body, secret="wrong-secret"))
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_tampered_body_rejected(self) -> None:
+ headers = _signed_headers(self.body)
+ tampered = _json_body({**self.payload, "email": "[email protected]"})
+ response = self._post(tampered, headers)
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_expired_timestamp_rejected(self) -> None:
+ stale_ts = int(time.time()) - 3600
+ response = self._post(self.body, _signed_headers(self.body, timestamp=stale_ts))
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_invalid_utf8_body_rejected(self) -> None:
+ headers = {
+ CROSS_REGION_SIGNATURE_HEADER: "irrelevant",
+ CROSS_REGION_TIMESTAMP_HEADER: str(int(time.time())),
+ }
+ response = self._post(b"\xff\xfe\xfa", headers)
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_unset_secret_disables_endpoint(self) -> None:
+ with override_settings(PERSONAL_SPEND_CROSS_REGION_SECRET=""):
+ response = self._post(self.body, _signed_headers(self.body))
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_missing_email_rejected(self) -> None:
+ body = _json_body({"product": "posthog_code"})
+ response = self._post(body, _signed_headers(body))
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_invalid_product_rejected(self) -> None:
+ body = _json_body({"email": "[email protected]", "product": "wibble"})
+ response = self._post(body, _signed_headers(body))
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_signed_request_computes_spend_for_asserted_email(self) -> None:
+ _create_person(distinct_ids=["eu-user"], team=self.team, properties={"email": "[email protected]"})
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id="eu-user",
+ properties={
+ "$ai_input_tokens": 100,
+ "$ai_output_tokens": 10,
+ "$ai_model": "claude-opus-4-8",
+ "$ai_trace_id": "trace-eu-1",
+ "$ai_total_cost_usd": 2.5,
+ "ai_product": "posthog_code",
+ },
+ )
+ flush_persons_and_events()
+
+ response = self._post(self.body, _signed_headers(self.body))
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ assert body["summary"]["scoped_cost_usd"] == 2.5
+ assert body["summary"]["scoped_event_count"] == 1
+
+ def test_signed_request_other_email_sees_nothing(self) -> None:
+ _create_person(distinct_ids=["eu-user"], team=self.team, properties={"email": "[email protected]"})
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id="eu-user",
+ properties={"$ai_total_cost_usd": 2.5, "ai_product": "posthog_code"},
+ )
+ flush_persons_and_events()
+
+ body = _json_body({"email": "[email protected]", "product": "posthog_code"})
+ response = self._post(body, _signed_headers(body))
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["summary"]["scoped_cost_usd"] == 0
+
+
+class TestPersonalSpendEUProxy(APIBaseTest):
+ """The EU-side view: authenticates locally, then relays a signed call to US."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ def _get(self, query: dict | None = None, *, user=None):
+ factory = APIRequestFactory()
+ request = factory.get("/api/llm_analytics/@me/spend/", data=query or {"product": "posthog_code"})
+ if user is not None:
+ force_authenticate(request, user=user)
+ return PersonalSpendEUProxyViewSet.as_view({"get": "list"})(request)
+
+ def test_unauthenticated_rejected_in_region(self) -> None:
+ with override_settings(PERSONAL_SPEND_CROSS_REGION_SECRET=CROSS_REGION_SECRET):
+ response = self._get()
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_falls_back_to_redirect_while_secret_unset(self) -> None:
+ with override_settings(PERSONAL_SPEND_CROSS_REGION_SECRET=""):
+ response = self._get(user=self.user)
+ assert response.status_code == status.HTTP_302_FOUND
+ assert response["Location"].startswith("https://us.posthog.com/api/llm_analytics/@me/spend/")
+
+ def test_invalid_params_rejected_without_upstream_call(self) -> None:
+ with override_settings(PERSONAL_SPEND_CROSS_REGION_SECRET=CROSS_REGION_SECRET):
+ with patch("products.ai_observability.backend.api.personal_spend.requests.post") as post:
+ response = self._get({"product": "wibble"}, user=self.user)
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ post.assert_not_called()
+
+ def test_relays_upstream_success_and_signs_asserted_email(self) -> None:
+ upstream_payload = {"summary": {"scoped_cost_usd": 1.25}}
+ with override_settings(PERSONAL_SPEND_CROSS_REGION_SECRET=CROSS_REGION_SECRET):
+ with patch("products.ai_observability.backend.api.personal_spend.requests.post") as post:
+ post.return_value.status_code = status.HTTP_200_OK
+ post.return_value.json.return_value = upstream_payload
+ response = self._get(user=self.user)
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.data == upstream_payload
+
+ (target_url,) = post.call_args.args
+ assert target_url.endswith("/api/llm_analytics/internal/spend/")
+ sent_body = post.call_args.kwargs["data"]
+ sent = json.loads(sent_body)
+ assert sent["email"] == self.user.email
+ assert sent["product"] == "posthog_code"
+ headers = post.call_args.kwargs["headers"]
+ ts = int(headers[CROSS_REGION_TIMESTAMP_HEADER])
+ expected_signature, _ = sign_cross_region_spend_request(sent_body, CROSS_REGION_SECRET, timestamp=ts)
+ assert headers[CROSS_REGION_SIGNATURE_HEADER] == expected_signature
+
+ def test_repeat_request_served_from_local_cache(self) -> None:
+ upstream_payload = {"summary": {"scoped_cost_usd": 1.25}}
+ with override_settings(PERSONAL_SPEND_CROSS_REGION_SECRET=CROSS_REGION_SECRET):
+ with patch("products.ai_observability.backend.api.personal_spend.requests.post") as post:
+ post.return_value.status_code = status.HTTP_200_OK
+ post.return_value.json.return_value = upstream_payload
+ first = self._get(user=self.user)
+ second = self._get(user=self.user)
+
+ assert first.status_code == status.HTTP_200_OK
+ assert second.status_code == status.HTTP_200_OK
+ assert second.data == upstream_payload
+ assert post.call_count == 1
+
+ @parameterized.expand(
+ [
+ ("upstream_throttle", status.HTTP_429_TOO_MANY_REQUESTS, status.HTTP_429_TOO_MANY_REQUESTS),
+ ("upstream_validation", status.HTTP_400_BAD_REQUEST, status.HTTP_400_BAD_REQUEST),
+ ("upstream_signature_mismatch", status.HTTP_401_UNAUTHORIZED, status.HTTP_502_BAD_GATEWAY),
+ ("upstream_server_error", status.HTTP_500_INTERNAL_SERVER_ERROR, status.HTTP_502_BAD_GATEWAY),
+ ]
+ )
+ def test_upstream_error_mapping(self, _label: str, upstream_status: int, expected: int) -> None:
+ with override_settings(PERSONAL_SPEND_CROSS_REGION_SECRET=CROSS_REGION_SECRET):
+ with patch("products.ai_observability.backend.api.personal_spend.requests.post") as post:
+ post.return_value.status_code = upstream_status
+ post.return_value.json.return_value = {"detail": "upstream detail"}
+ response = self._get(user=self.user)
+ assert response.status_code == expected
+
+ def test_transport_failure_maps_to_bad_gateway(self) -> None:
+ with override_settings(PERSONAL_SPEND_CROSS_REGION_SECRET=CROSS_REGION_SECRET):
+ with patch(
+ "products.ai_observability.backend.api.personal_spend.requests.post",
+ side_effect=requests.ConnectionError("boom"),
+ ):
+ response = self._get(user=self.user)
+ assert response.status_code == status.HTTP_502_BAD_GATEWAY
diff --git a/products/ai_observability/backend/routes.py b/products/ai_observability/backend/routes.py
index b3526b39a54c..4c99a1cc54c2 100644
--- a/products/ai_observability/backend/routes.py
+++ b/products/ai_observability/backend/routes.py
@@ -21,6 +21,7 @@ from products.ai_observability.backend.api import (
LLMProviderKeyViewSet,
LLMProxyViewSet,
ParserRecipeViewSet,
+ PersonalSpendInternalViewSet,
PersonalSpendViewSet,
ReviewQueueItemViewSet,
ReviewQueueViewSet,
@@ -36,6 +37,8 @@ def register_routes(routers: RouterRegistry) -> None:
# CLOUD/DEBUG/TEST gate the registration carried inline.
if CLOUD_DEPLOYMENT == "US" or DEBUG or TEST:
routers.root.register(r"llm_analytics/@me/spend", PersonalSpendViewSet, "personal_spend")
+ # HMAC-authenticated receiver for the EU→US personal-spend proxy.
+ routers.root.register(r"llm_analytics/internal/spend", PersonalSpendInternalViewSet, "personal_spend_internal")
routers.projects.register(
r"llm_analytics/parser_recipes", ParserRecipeViewSet, "project_llm_analytics_parser_recipes", ["team_id"]