: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(typesafe): block external requests on cloud (#108333)
Paul D'Ambradb7299bd02e5
diff --git a/posthog/egress/test/test_typesafe.py b/posthog/egress/test/test_typesafe.pyindex 81a3f247029c..908948372a2e 100644--- a/posthog/egress/test/test_typesafe.py+++ b/posthog/egress/test/test_typesafe.py@@ -12,7 +12,15 @@ from prometheus_client import REGISTRYfrom posthog.egress.limiter.policies import Priority, resolve_policyfrom posthog.egress.typesafe.client import TypeSafeNotConfigured, TypeSafeRequestFailed, system_onefrom posthog.egress.typesafe.limiter import typesafe_account_key-from posthog.llm.system_one import ChoiceAnswer, ChoiceQuestion, NoulAnswer, NoulQuestion, Question+from posthog.egress.typesafe.transport import TypeSafeClient+from posthog.llm.system_one import (+ ChoiceAnswer,+ ChoiceQuestion,+ NoulAnswer,+ NoulQuestion,+ Question,+ SystemOneNotConfigured,+)_FAKE_API_KEY = "fake-key-for-tests"@@ -55,8 +63,20 @@ def _with_answer(question_id: str, answer: dict[str, Any]) -> str:return json.dumps({**_ANSWERS, "answers": {**_ANSWERS["answers"], question_id: answer}})-@override_settings(TYPESAFE_API_KEY=_FAKE_API_KEY)+@override_settings(TYPESAFE_API_KEY=_FAKE_API_KEY, CLOUD_DEPLOYMENT="LOCAL")class TestTypeSafeEgress(SimpleTestCase):+ @parameterized.expand(["US", "EU", "DEV", "E2E", "us", "eu", "dev", "e2e"])+ def test_cloud_never_calls_typesafe_even_with_a_key(self, deployment: str) -> None:+ with (+ override_settings(CLOUD_DEPLOYMENT=deployment),+ patch("requests.request") as request,+ ):+ with self.assertRaisesRegex(SystemOneNotConfigured, "ai-gateway"):+ system_one(state="hi", questions=_QUESTIONS, source="test")+ with self.assertRaisesRegex(SystemOneNotConfigured, "ai-gateway"):+ TypeSafeClient().request("POST", "https://api.typesafe.ai/v1/systemone", source="test")+ request.assert_not_called()+def test_sends_the_documented_request_and_records_it_without_the_key(self) -> None:consume = MagicMock(return_value=True)before = REGISTRY.get_sample_value("typesafe_api_requests_total", _COUNTER_LABELS) or 0.0diff --git a/posthog/egress/typesafe/README.md b/posthog/egress/typesafe/README.mdindex 3d0970abccd0..1b8cfb268172 100644--- a/posthog/egress/typesafe/README.md+++ b/posthog/egress/typesafe/README.md@@ -6,19 +6,21 @@ It returns probabilities, not free text.The request and answer types live in `posthog/llm/system_one.py`, because the Go ai-gateway serves the same API with models PostHog hosts.A caller builds its client with `build_system_one_client` from `posthog/llm/system_one_client.py`.It reaches the ai-gateway where `AI_GATEWAY_URL` is set.-It falls back to this domain only when the caller passes a `TypeSafeFallback`, and every caller that does so meets the usage policy below.+PostHog Cloud uses the ai-gateway with a PostHog-hosted System One model. This domain is available only in local development or self-hosted instances, when the caller passes a `TypeSafeFallback`.+The transport rejects TypeSafe requests from Cloud before an HTTP call, even if someone configures an API key or calls it directly. The Cloud check ignores case in deployment values.## Usage policy-TypeSafe is approved for experiments only.+TypeSafe is approved for local experiments only. Do not use it for Cloud features.+Use `build_system_one_client(model=..., ai_product=...)` with the PostHog-hosted model on the ai-gateway instead. Do not pass `TypeSafeFallback` for a Cloud feature.Every caller meets these rules before it merges, and a reviewer blocks a caller that does not:- **Gate the caller behind a feature flag.** Until launch, the flag reaches PostHog staff only.- **Send no customer data during the experiment.** Customer data is anything from a customer's project or account: events, persons, recordings, insights, names, and text a user types into PostHog. Use synthetic data or data that PostHog owns.-- **A launch that sends customer data needs an explicit opt-in.** Each customer turns it on before any of their data goes to TypeSafe. Use the approved opt-in copy. Until that copy exists, no caller sends customer data.-- **A launch that sends customer data needs sign-off from leadership** before it ships, in addition to the opt-in.-A self-hosted instance has no `TYPESAFE_API_KEY`, so it sends nothing.+An API key, feature flag, or customer opt-in cannot enable TypeSafe on PostHog Cloud. Changing the Cloud guard needs a separate privacy review and explicit approval before any customer data can be sent.++An instance without `TYPESAFE_API_KEY` sends nothing.## Identity@@ -49,7 +51,7 @@ Raise both settings when real traffic outgrows them.The default reserve ladder applies, and `typesafe_request` defaults to `NORMAL`.`typesafe_request` rejects `CRITICAL`, because a `CRITICAL` call is never shed and would skip the hourly spend ceiling.Give every caller an explicit lane: `NORMAL` when a person waits for the answer, `BATCH` for background work.-No caller exists on master yet. Each new caller adds itself here with its lane and its feature flag.+No TypeSafe caller exists on master yet. Each new local caller adds itself here with its lane and its feature flag.## Rate-limit headersdiff --git a/posthog/egress/typesafe/client.py b/posthog/egress/typesafe/client.pyindex e16624de70cf..916567229563 100644--- a/posthog/egress/typesafe/client.py+++ b/posthog/egress/typesafe/client.py@@ -3,10 +3,9 @@The request and answer types live in ``posthog.llm.system_one``, because the Go ai-gateway servesthe same API. This module adds TypeSafe's host, key, and egress budget.-USAGE POLICY. TypeSafe is approved for experiments only. Read "Usage policy" in this package's-README.md before you add a caller. In short: gate every caller behind a feature flag that reaches-PostHog staff only, and send no customer data. A launch that sends customer data needs an explicit-opt-in from each customer and sign-off from leadership first.+USAGE POLICY. TypeSafe is available for local experiments only. Cloud requests are blocked at the+transport. Use the ai-gateway System One client for Cloud features. Read "Usage policy" in this+package's README.md before you add a caller."""from collections.abc import Mappingdiff --git a/posthog/egress/typesafe/transport.py b/posthog/egress/typesafe/transport.pyindex 5a7ae6e4660e..1376662867e2 100644--- a/posthog/egress/typesafe/transport.py+++ b/posthog/egress/typesafe/transport.py@@ -10,10 +10,12 @@ from typing import Anyimport requests+from posthog.cloud_utils import is_cloudfrom posthog.egress.limiter.policies import Priorityfrom posthog.egress.transport.transport import EgressBudgetExhausted, EgressClientfrom posthog.egress.typesafe.limiter import ACCOUNT_SCOPE_ID, consume_typesafe_syncfrom posthog.egress.typesafe.observability import typesafe_egress+from posthog.llm.system_one import SystemOneNotConfiguredclass TypeSafeEgressBudgetExhausted(EgressBudgetExhausted):@@ -27,6 +29,11 @@ class TypeSafeClient(EgressClient):observability = typesafe_egress+ def _gate(self, scope: str | None, source: str, priority: Priority, url: str) -> None:+ if not typesafe_allowed():+ raise SystemOneNotConfigured("TypeSafe is disabled on PostHog Cloud; use the ai-gateway System One model")+ super()._gate(scope, source, priority, url)+def _standard_headers(self) -> dict[str, str]:return {"Accept": "application/json", "Content-Type": "application/json"}@@ -44,6 +51,10 @@ _typesafe_client = TypeSafeClient()DEFAULT_TIMEOUT: tuple[float, float] = (3.0, 15.0)+def typesafe_allowed() -> bool:+ return not is_cloud()++def typesafe_request(method: str,url: str,diff --git a/posthog/llm/system_one_client.py b/posthog/llm/system_one_client.pyindex f9d1595cb01c..3f560a9c09fd 100644--- a/posthog/llm/system_one_client.py+++ b/posthog/llm/system_one_client.py@@ -2,9 +2,9 @@The Go ai-gateway serves System One models that PostHog hosts, and bills the wallet of the team thatowns ``AI_GATEWAY_API_KEY``. TypeSafe serves Jev, but a caller reaches it only by passing a-``TypeSafeFallback``: TypeSafe is a third party, approved for experiments that send no customer data-(see ``posthog/egress/typesafe/README.md``). The two serve different models, so the fallback names-its own, and the result says which model answered.+``TypeSafeFallback`` in local development: TypeSafe is a third party, approved for experiments that+send no customer data (see ``posthog/egress/typesafe/README.md``). The two serve different models,+so the fallback names its own, and the result says which model answered."""from collections.abc import Mapping@@ -19,6 +19,7 @@ import structlogfrom posthog.dataclasses import frozenfrom posthog.egress.limiter.policies import Priorityfrom posthog.egress.typesafe.client import system_one+from posthog.egress.typesafe.transport import typesafe_allowedfrom posthog.llm.gateway_client import AIGatewayConfig, ai_gateway_headers, resolve_ai_gateway_config, team_distinct_idfrom posthog.llm.system_one import (SYSTEM_ONE_PATH,@@ -128,7 +129,7 @@ def _usable_gateway() -> AIGatewayConfig | None:def system_one_configured(typesafe_fallback: TypeSafeFallback | None = None) -> bool:if _usable_gateway() is not None:return True- return typesafe_fallback is not None and bool(settings.TYPESAFE_API_KEY)+ return typesafe_fallback is not None and typesafe_allowed() and bool(settings.TYPESAFE_API_KEY)def build_system_one_client(@@ -142,8 +143,8 @@ def build_system_one_client(properties: Mapping[str, str] | None = None,timeout: float = DEFAULT_TIMEOUT_SECONDS,) -> SystemOneClient:- """A client for ``model`` on the Go ai-gateway when it is configured, else for TypeSafe when the- caller passes ``typesafe_fallback``.+ """A client for ``model`` on the Go ai-gateway when it is configured, else for TypeSafe in local+ development when the caller passes ``typesafe_fallback``.``ai_product``, ``distinct_id``, ``trace_id`` and ``properties`` label the gateway's event. ``team_id``is the customer team the gateway bills, and labels the event when ``distinct_id`` is unset. Raises@@ -170,8 +171,8 @@ def build_system_one_client(model=model,timeout=timeout,)- if typesafe_fallback is None:- raise SystemOneNotConfigured("Configure AI_GATEWAY_URL (https) and AI_GATEWAY_API_KEY")+ if typesafe_fallback is None or not typesafe_allowed():+ raise SystemOneNotConfigured("Configure AI_GATEWAY_URL (https) and AI_GATEWAY_API_KEY for System One")if not settings.TYPESAFE_API_KEY:raise SystemOneNotConfigured("Configure AI_GATEWAY_URL and AI_GATEWAY_API_KEY, or TYPESAFE_API_KEY")return TypeSafeSystemOneClient(diff --git a/posthog/llm/test_system_one_client.py b/posthog/llm/test_system_one_client.pyindex 7c1d79c676a9..89d2dade229b 100644--- a/posthog/llm/test_system_one_client.py+++ b/posthog/llm/test_system_one_client.py@@ -23,6 +23,7 @@ from posthog.llm.system_one_client import (TypeSafeFallback,TypeSafeSystemOneClient,build_system_one_client,+ system_one_configured,)GATEWAY_MODEL = "posthog/hogference/jevk5-fp8-0.2"@@ -55,6 +56,7 @@ def _build(typesafe_fallback: TypeSafeFallback | None = FALLBACK) -> SystemOneCl)+@override_settings(CLOUD_DEPLOYMENT="LOCAL")class TestBuildSystemOneClient(SimpleTestCase):@parameterized.expand([@@ -99,6 +101,17 @@ class TestBuildSystemOneClient(SimpleTestCase):with override_settings(**configured), self.assertRaises(SystemOneNotConfigured):_build(typesafe_fallback)+ @parameterized.expand(["US", "EU", "DEV", "E2E"])+ def test_cloud_ignores_typesafe_fallback_even_with_a_key(self, deployment: str) -> None:+ with override_settings(**{**NOTHING, "TYPESAFE_API_KEY": "ts-key", "CLOUD_DEPLOYMENT": deployment}):+ assert not system_one_configured(FALLBACK)+ with self.assertRaisesRegex(SystemOneNotConfigured, "AI_GATEWAY_URL"):+ _build()++ with override_settings(**{**GATEWAY, "CLOUD_DEPLOYMENT": deployment}):+ assert system_one_configured(FALLBACK)+ assert isinstance(_build(), GatewaySystemOneClient)+def test_gateway_request_reaches_the_system_one_route_with_its_labels(self) -> None:with override_settings(**{**NOTHING, **GATEWAY}):client = _build()