: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(aio): allow hosted typesafe endpoint for system one connections (#124019)
Bernat Torres6b4cfac24352
diff --git a/posthog/egress/typesafe/README.md b/posthog/egress/typesafe/README.mdindex 31f85da89d1f..7ca052278413 100644--- a/posthog/egress/typesafe/README.md+++ b/posthog/egress/typesafe/README.md@@ -20,6 +20,14 @@ Every caller meets these rules before it merges, and a reviewer blocks a callerAn 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.+### Customer System One connections++AI observability evaluations let a team save its own System One connection: an endpoint URL and the team's own credential.+That connection can point at TypeSafe's hosted API, and evaluation runs then send the team's evaluation data there from Cloud.+These calls do not use this domain: no instance key, budget, or Cloud guard applies, and the team pays TypeSafe directly.+The team chooses the endpoint and supplies the key, so PostHog sends data to TypeSafe only on that team's instruction.+Every other provider key rejects `typesafe.ai` hosts on save, so no other path can reach TypeSafe this way.+An instance without `TYPESAFE_API_KEY` sends nothing.## Identitydiff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 34a839b10e1b..c76e819fdca8 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -951,7 +951,6 @@ def test_system_one_numeric_requires_a_score_range(output_config: dict[str, floa[("system_one", "https://decisions.example.com/v1", False),("system_one", "https://ai-gateway.us.posthog.com/v1", False),- ("system_one", "https://api.typesafe.ai/v1", True),],)def test_system_one_restricted_connection_does_not_send_evaluation_data(diff --git a/products/ai_observability/backend/api/provider_keys.py b/products/ai_observability/backend/api/provider_keys.pyindex 26f9562fde06..da445f700a5d 100644--- a/products/ai_observability/backend/api/provider_keys.py+++ b/products/ai_observability/backend/api/provider_keys.py@@ -1,4 +1,5 @@import logging+from urllib.parse import urlsplitfrom uuid import UUIDfrom django.core.cache import cache@@ -121,6 +122,14 @@ _ALL_PROVIDER_CONFIG_FIELDS: tuple[str, ...] = tuple()+def _is_typesafe_host(url: str) -> bool:+ try:+ host = (urlsplit(url).hostname or "").encode("idna").decode("ascii").lower().rstrip(".")+ except (ValueError, UnicodeError):+ return False+ return host == "typesafe.ai" or host.endswith(".typesafe.ai")++class LLMProviderKeySerializer(serializers.ModelSerializer):api_key = serializers.CharField(write_only=True, required=False, allow_blank=True)system_one_model = serializers.CharField(@@ -208,6 +217,11 @@ class LLMProviderKeySerializer(serializers.ModelSerializer):return DecisionClient.normalize_base_url(value)except ValueError as error:raise serializers.ValidationError(str(error)) from error+ # TypeSafe is not a subprocessor. Only a team's own System One connection may send data there.+ if _is_typesafe_host(value):+ raise serializers.ValidationError(+ "TypeSafe is not an approved subprocessor. Use a System One connection to send data to it."+ )# `base_url_display` is readable by any project member while the API key is masked, and the# URL also reaches exception messages and log lines. A credential typed into this field# would leak through all three, so drop it before anything stores or echoes the value.diff --git a/products/ai_observability/backend/api/test/test_provider_keys.py b/products/ai_observability/backend/api/test/test_provider_keys.pyindex 775ae76fa0ac..86c4834c317b 100644--- a/products/ai_observability/backend/api/test/test_provider_keys.py+++ b/products/ai_observability/backend/api/test/test_provider_keys.py@@ -79,18 +79,26 @@ class TestProviderKeySerializer(SimpleTestCase):self.assertFalse(serializer.is_valid())self.assertIn(missing_field, serializer.errors)- def test_system_one_connection_rejects_hosted_typesafe_endpoint(self) -> None:+ @parameterized.expand(+ [+ ("openai_compatible", "https://api.typesafe.ai/v1", False),+ ("openai_compatible", "https://API.TYPESAFE.AI.:443/v1", False),+ ("system_one", "https://api.typesafe.ai/v1", True),+ ]+ )+ def test_typesafe_endpoint_is_only_accepted_for_system_one(self, provider: str, base_url: str, valid: bool) -> None:serializer = LLMProviderKeySerializer(data={- "provider": "system_one",+ "provider": provider,"name": "Example connection","api_key": "example-token",- "base_url": "https://api.typesafe.ai/v1",- "system_one_model": "example-judge-v1",+ "base_url": base_url,+ **({"system_one_model": "example-judge-v1"} if provider == "system_one" else {}),})- self.assertFalse(serializer.is_valid())- self.assertIn("base_url", serializer.errors)+ self.assertEqual(serializer.is_valid(), valid, serializer.errors)+ if not valid:+ self.assertIn("base_url", serializer.errors)def test_non_system_one_model_error_uses_model_field(self) -> None:serializer = LLMProviderKeySerializer(diff --git a/products/ai_observability/backend/llm/decisions.py b/products/ai_observability/backend/llm/decisions.pyindex ea63d3f3ea2f..8dea28310178 100644--- a/products/ai_observability/backend/llm/decisions.py+++ b/products/ai_observability/backend/llm/decisions.py@@ -65,7 +65,7 @@ def decision_evaluations_enabled(team_id: int, *, base_url: str) -> bool:host = (urlsplit(base_url).hostname or "").encode("idna").decode("ascii").lower().rstrip(".")except (ValueError, UnicodeError):return False- if not host or host == "typesafe.ai" or host.endswith(".typesafe.ai"):+ if not host:return Falseteam = Team.objects.only("uuid", "organization_id").get(id=team_id)return (@@ -109,11 +109,9 @@ class DecisionClient:):raise ValueError("Use an HTTPS base URL without credentials, a query, or a fragment.")try:- host = parsed.hostname.encode("idna").decode("ascii").lower().rstrip(".")+ parsed.hostname.encode("idna")except UnicodeError as error:raise ValueError("Use a valid HTTPS hostname.") from error- if host == "typesafe.ai" or host.endswith(".typesafe.ai"):- raise ValueError("This hosted endpoint is not available for evaluations.")return base_url.rstrip("/")@staticmethoddiff --git a/products/ai_observability/backend/llm/test/test_decisions.py b/products/ai_observability/backend/llm/test/test_decisions.pyindex 42fa464b7437..d707df0a2ed0 100644--- a/products/ai_observability/backend/llm/test/test_decisions.py+++ b/products/ai_observability/backend/llm/test/test_decisions.py@@ -52,7 +52,7 @@ def public_endpoint_dns() -> Iterator[None]:@pytest.mark.parametrize("base_url,flag,enabled",[- ("https://api.typesafe.ai/v1", True, False),+ ("https://api.typesafe.ai/v1", True, True),("", True, False),("https://decisions.example.com/v1", True, True),("https://decisions.example.com/v1", False, False),@@ -262,25 +262,6 @@ def test_unavailable_usage_does_not_discard_a_valid_answer(assert result.output_tokens == expected_output- "base_url",- ["https://api.typesafe.ai/v1", "https://API.TYPESAFE.AI.:443/v1", "https://api.typesafe.ai/v1"],-)-def test_official_endpoint_is_blocked(base_url: str) -> None:- with (- patch("httpx.AsyncHTTPTransport.handle_async_request") as request,- pytest.raises(DecisionEndpointBlockedError, match="hosted endpoint is not available"),- ):- DecisionClient.evaluate(- api_key="example-token",- base_url=base_url,- model="example-judge-v1",- state="Hello!",- questions={"verdict": NoulQuestion(instructions="Polite?")},- )- request.assert_not_called()--@pytest.mark.parametrize("answers", [{}, {"verdict": {"type": "noul", "noul": 0.9}}])def test_system_one_requires_every_requested_answer(answers: dict[str, object]) -> None:response = _response(