: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
feat(security): add the endpoints the security hub calls (#103578)
Yasen16f4566f6b03
diff --git a/posthog/urls.py b/posthog/urls.pyindex 9ad290709288..3873b23122ad 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -59,6 +59,7 @@ from products.notebooks.backend.facade.sql_v2 import (notebook_sql_v2_data_plane_status,)from products.product_tours.backend.api import product_tours+from products.security.backend.presentation.hub_api import urlpatterns as security_hub_urlpatternsfrom products.signals.backend import views as signals_viewsfrom products.signals.backend.views import SignalUserAutonomyConfigView as signals_user_autonomy_viewfrom products.slack_app.backend.api import (@@ -153,6 +154,8 @@ urlpatterns = [),path("api/sdk_health/", sdk_health),path("api/conversations/", include("products.conversations.backend.api.urls")),+ # Routes the security hub calls from outside the cluster (auth: scoped service JWT)+ path("api/security/", include(security_hub_urlpatterns)),path("api/customer_analytics/", include("products.customer_analytics.backend.presentation.views.urls")),path("api/projects/<int:parent_lookup_team_id>/mcp_analytics/",diff --git a/products/security/backend/facade/hub.py b/products/security/backend/facade/hub.pynew file mode 100644index 000000000000..7b1adda09875--- /dev/null+++ b/products/security/backend/facade/hub.py@@ -0,0 +1,50 @@+"""What the hub-facing routes are allowed to reach. Keeps presentation out of logic/."""++from __future__ import annotations++from collections.abc import Mapping+from typing import Any++from ..logic.accounts import (+ CappedCount,+ CountableType as CountableType,+ Resolution,+ count_active_accounts,+ count_active_org_members,+ has_posthog_account,+ resolve_subject,+)+from ..logic.hub_auth import (+ INTERNAL_PURPOSE as INTERNAL_PURPOSE,+ claims_allow,+)+from ..logic.mfa_export import MfaExport, export_mfa_bypasses+from ..metrics import HUB_API_AUTH_COUNTER+++def resolve(query: str) -> Resolution:+ return resolve_subject(query)+++def count_accounts(target_type: CountableType, target_value: str) -> CappedCount:+ return count_active_accounts(target_type, target_value)+++def count_org_members(organization_id: str) -> tuple[bool, CappedCount]:+ return count_active_org_members(organization_id)+++def posthog_account_exists(*, user_uuid: str | None = None, organization_id: str | None = None) -> bool:+ return has_posthog_account(user_uuid=user_uuid, organization_id=organization_id)+++def mfa_bypasses() -> MfaExport:+ return export_mfa_bypasses()+++def token_allows(claims: Mapping[str, Any] | None, op: str) -> bool:+ return claims_allow(claims, op)+++def record_call(op: str) -> None:+ HUB_API_AUTH_COUNTER.labels(op=op).inc()diff --git a/products/security/backend/logic/mfa_export.py b/products/security/backend/logic/mfa_export.pynew file mode 100644index 000000000000..4b818bf4285d--- /dev/null+++ b/products/security/backend/logic/mfa_export.py@@ -0,0 +1,37 @@+"""Reads the legacy Redis MFA bypasses for the hub's one-time import. Deleted at cut-over."""++from datetime import UTC, datetime, timedelta++from posthog.dataclasses import frozen+from posthog.helpers.two_factor_session import (+ CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY,+ get_code_based_verification_global_disable,+)+from posthog.redis import get_client+++@frozen+class GlobalBypass:+ reason: str+ actor: str | None+ expires_at: datetime+++@frozen+class MfaExport:+ emails: tuple[str, ...]+ global_bypass: GlobalBypass | None+++def export_mfa_bypasses() -> MfaExport:+ members = get_client().smembers(CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY)+ emails = tuple(sorted(m.decode() if isinstance(m, bytes) else str(m) for m in members))+ state = get_code_based_verification_global_disable()+ global_bypass = None+ if state and state.get("expires_in_seconds"):+ global_bypass = GlobalBypass(+ reason=str(state.get("reason", "")),+ actor=state.get("disabled_by"),+ expires_at=datetime.now(UTC) + timedelta(seconds=int(state["expires_in_seconds"])),+ )+ return MfaExport(emails=emails, global_bypass=global_bypass)diff --git a/products/security/backend/presentation/hub_api.py b/products/security/backend/presentation/hub_api.pynew file mode 100644index 000000000000..39115d3e17fb--- /dev/null+++ b/products/security/backend/presentation/hub_api.py@@ -0,0 +1,176 @@+"""+Routes the security hub calls in this region.++The hub runs outside the cluster, so these routes sit on the public /api/ path. Contour+does not expose /api/internal/. A scoped HS256 token pinned to this region and one+operation is the only gate, and one global throttle caps the traffic.+"""++from typing import Any, ClassVar, cast++from django.urls import path+from django.views.decorators.csrf import csrf_exempt++import structlog+from drf_spectacular.utils import extend_schema+from rest_framework import status+from rest_framework.permissions import BasePermission, IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.throttling import SimpleRateThrottle+from rest_framework.views import APIView++from posthog.auth import ScopedServiceJWTAuthentication++from ..facade.hub import (+ INTERNAL_PURPOSE,+ count_accounts,+ count_org_members,+ mfa_bypasses,+ posthog_account_exists,+ record_call,+ resolve,+ token_allows,+)+from ..facade.temporal import start_sync_now+from .serializers import (+ CountAccountsRequestSerializer,+ CountResponseSerializer,+ MfaExportResponseSerializer,+ OrgMemberCountRequestSerializer,+ OrgMemberCountResponseSerializer,+ PosthogMembershipRequestSerializer,+ PosthogMembershipResponseSerializer,+ ResolveRequestSerializer,+ ResolveResponseSerializer,+)++logger = structlog.get_logger(__name__)+++class SecurityHubAuthentication(ScopedServiceJWTAuthentication):+ purpose = INTERNAL_PURPOSE+ require_team = False+++class SecurityHubThrottle(SimpleRateThrottle):+ """One budget for every hub route together, whoever the caller is."""++ scope = "security_hub"+ rate = "100/minute"++ def get_cache_key(self, request: Request, view: APIView) -> str:+ return self.cache_format % {"scope": self.scope, "ident": "global"}+++class HubOperationPermission(BasePermission):+ """Checks the token's op, region and lifetime. DRF runs permissions before throttles, so a refused token never spends the shared budget."""++ message = "This token is not valid for this operation."++ def has_permission(self, request: Request, view: APIView) -> bool:+ return token_allows(cast(dict[str, Any], request.auth or {}), cast(_HubView, view).op)+++class _HubView(APIView):+ authentication_classes = [SecurityHubAuthentication]+ permission_classes = [IsAuthenticated, HubOperationPermission]+ throttle_classes = [SecurityHubThrottle]+ http_method_names = ["post", "options"]+ op: ClassVar[str]++ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:+ super().initial(request, *args, **kwargs)+ record_call(self.op)+++class ResolveView(_HubView):+ op = "subject:resolve"++ @extend_schema(exclude=True)+ def post(self, request: Request) -> Response:+ serializer = ResolveRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ resolved = resolve(serializer.validated_data["query"])+ user = resolved.user+ organization = None+ if resolved.kind == "organization" and resolved.organization_ids:+ organization = {"id": resolved.organization_ids[0], "exists": True}+ payload = {+ "kind": resolved.kind,+ "user": {"uuid": user.uuid, "email": user.email, "is_active": user.is_active} if user else None,+ "organization_ids": list(resolved.organization_ids),+ "organization": organization,+ }+ return Response(ResolveResponseSerializer(payload).data)+++class CountAccountsView(_HubView):+ op = "accounts:count"++ @extend_schema(exclude=True)+ def post(self, request: Request) -> Response:+ serializer = CountAccountsRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ counted = count_accounts(serializer.validated_data["target_type"], serializer.validated_data["target_value"])+ return Response(CountResponseSerializer(counted).data)+++class OrgMemberCountView(_HubView):+ op = "org:member_count"++ @extend_schema(exclude=True)+ def post(self, request: Request) -> Response:+ serializer = OrgMemberCountRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ exists, members = count_org_members(str(serializer.validated_data["organization_id"]))+ payload = {"exists": exists, "active_members": members.count, "capped": members.capped}+ return Response(OrgMemberCountResponseSerializer(payload).data)+++class PosthogMembershipView(_HubView):+ op = "posthog_membership:check"++ @extend_schema(exclude=True)+ def post(self, request: Request) -> Response:+ serializer = PosthogMembershipRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ if "user_uuid" in data:+ found = posthog_account_exists(user_uuid=str(data["user_uuid"]))+ else:+ found = posthog_account_exists(organization_id=str(data["organization_id"]))+ return Response(PosthogMembershipResponseSerializer({"has_posthog_account": found}).data)+++class SyncNowView(_HubView):+ op = "rules:sync_now"++ @extend_schema(exclude=True)+ def post(self, request: Request) -> Response:+ # The hub does not wait for the pull, and the 5-minute schedule is the backstop.+ try:+ start_sync_now()+ except Exception:+ logger.exception("security_hub_sync_now_failed")+ return Response(status=status.HTTP_503_SERVICE_UNAVAILABLE)+ return Response(status=status.HTTP_202_ACCEPTED)+++class MfaBypassExportView(_HubView):+ op = "mfa_bypass:export"++ @extend_schema(exclude=True)+ def post(self, request: Request) -> Response:+ exported = mfa_bypasses()+ return Response(MfaExportResponseSerializer(exported).data)+++urlpatterns = [+ path("resolve/", csrf_exempt(ResolveView.as_view())),+ path("count-accounts/", csrf_exempt(CountAccountsView.as_view())),+ path("org-member-count/", csrf_exempt(OrgMemberCountView.as_view())),+ path("posthog-membership/", csrf_exempt(PosthogMembershipView.as_view())),+ path("sync-now/", csrf_exempt(SyncNowView.as_view())),+ path("mfa-bypass-export/", csrf_exempt(MfaBypassExportView.as_view())),+]diff --git a/products/security/backend/presentation/serializers.py b/products/security/backend/presentation/serializers.pynew file mode 100644index 000000000000..2acacd90a375--- /dev/null+++ b/products/security/backend/presentation/serializers.py@@ -0,0 +1,89 @@+"""DRF serializers for security."""++from typing import Any++from rest_framework import serializers+++class ResolveRequestSerializer(serializers.Serializer):+ query = serializers.CharField(+ max_length=400,+ allow_blank=True,+ trim_whitespace=True,+ help_text="An email address, user UUID or organization UUID.",+ )+++class CountAccountsRequestSerializer(serializers.Serializer):+ target_type = serializers.ChoiceField(+ choices=["email", "email_root", "email_domain"], help_text="How target_value matches accounts."+ )+ target_value = serializers.CharField(max_length=320, help_text="The value the hub normalized for this target type.")+++class OrgMemberCountRequestSerializer(serializers.Serializer):+ organization_id = serializers.UUIDField(help_text="The organization to count active members of.")+++class PosthogMembershipRequestSerializer(serializers.Serializer):+ user_uuid = serializers.UUIDField(required=False, help_text="Check this user's email.")+ organization_id = serializers.UUIDField(required=False, help_text="Check this organization's members.")++ def validate(self, attrs: dict) -> dict:+ if ("user_uuid" in attrs) == ("organization_id" in attrs):+ raise serializers.ValidationError("Send exactly one of user_uuid and organization_id.")+ return attrs+++class ResolvedUserSerializer(serializers.Serializer):+ uuid = serializers.CharField(help_text="The user's UUID.")+ email = serializers.CharField(help_text="The user's email address.")+ is_active = serializers.BooleanField(help_text="Whether the account can still sign in.")+++class ResolvedOrganizationSerializer(serializers.Serializer):+ id = serializers.CharField(help_text="The organization's UUID.")+ exists = serializers.BooleanField(help_text="Whether the organization exists.")+++class ResolveResponseSerializer(serializers.Serializer):+ kind = serializers.CharField(help_text="user, organization or none.")+ user = ResolvedUserSerializer(allow_null=True, help_text="The matched user, when the query named one.")+ organization_ids = serializers.ListField(+ child=serializers.CharField(), help_text="The organizations the match belongs to."+ )+ organization = ResolvedOrganizationSerializer(+ allow_null=True, help_text="The matched organization, when the query named one."+ )+++class CountResponseSerializer(serializers.Serializer):+ count = serializers.IntegerField(help_text="Active accounts the rule would hit.")+ capped = serializers.BooleanField(help_text="Whether counting stopped at the cap.")+++class OrgMemberCountResponseSerializer(serializers.Serializer):+ exists = serializers.BooleanField(help_text="Whether the organization exists.")+ active_members = serializers.IntegerField(help_text="Active members of the organization.")+ capped = serializers.BooleanField(help_text="Whether counting stopped at the cap.")+++class PosthogMembershipResponseSerializer(serializers.Serializer):+ has_posthog_account = serializers.BooleanField(help_text="Whether the target holds a posthog.com account.")+++class GlobalBypassSerializer(serializers.Serializer):+ reason = serializers.CharField(help_text="Why the global bypass was set.")+ actor = serializers.CharField(allow_null=True, help_text="Who set it.")+ expires_at = serializers.DateTimeField(help_text="When it expires.")+++class MfaExportResponseSerializer(serializers.Serializer):+ emails = serializers.ListField(child=serializers.CharField(), help_text="Addresses on the legacy bypass list.")++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ # "global" is a keyword, so this field cannot be declared in the class body.+ self.fields["global"] = GlobalBypassSerializer(+ source="global_bypass", allow_null=True, help_text="The global switch, when one is set."+ )diff --git a/products/security/backend/tests/test_hub_api.py b/products/security/backend/tests/test_hub_api.pynew file mode 100644index 000000000000..59f04015a542--- /dev/null+++ b/products/security/backend/tests/test_hub_api.py@@ -0,0 +1,166 @@+import time+from typing import Any++from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.core.cache import cache+from django.test import override_settings++import jwt as pyjwt+from parameterized import parameterized+from rest_framework.test import APIClient++from posthog.helpers.two_factor_session import (+ add_code_based_verification_bypass,+ set_code_based_verification_global_disable,+)+from posthog.models import User++SECRET = "in-us"+SETTINGS = {"SECURITY_HUB_REGION": "us", "SECURITY_HUB_INBOUND_JWT_SECRETS": [SECRET]}+++def token(op: str, key: str = SECRET, **overrides: object) -> str:+ now = int(time.time())+ claims = {+ "aud": "posthog:security_hub:internal",+ "region": "us",+ "op": op,+ "iat": now,+ "exp": now + 60,+ **overrides,+ }+ return pyjwt.encode(claims, key, algorithm="HS256")+++@override_settings(**SETTINGS)+class TestHubApi(BaseTest):+ # The default test user is a posthog.com account, which would make the org protected.+ CONFIG_EMAIL = "[email protected]"++ def setUp(self) -> None:+ super().setUp()+ cache.clear()+ self.client = APIClient()++ def post(self, path: str, body: dict, op: str | None, **claims: Any):+ headers: dict[str, Any] = {"HTTP_AUTHORIZATION": f"Bearer {token(op, **claims)}"} if op else {}+ return self.client.post(f"/api/security/{path}/", body, format="json", **headers)++ def test_resolve(self) -> None:+ user = User.objects.create_and_join(self.organization, "[email protected]", "password1234")+ response = self.post("resolve", {"query": "[email protected]"}, "subject:resolve")+ assert response.status_code == 200+ assert response.json() == {+ "kind": "user",+ "user": {"uuid": str(user.uuid), "email": "[email protected]", "is_active": True},+ "organization_ids": [str(self.organization.id)],+ "organization": None,+ }++ def test_resolve_organization(self) -> None:+ response = self.post("resolve", {"query": str(self.organization.id)}, "subject:resolve")+ assert response.status_code == 200+ assert response.json() == {+ "kind": "organization",+ "user": None,+ "organization_ids": [str(self.organization.id)],+ "organization": {"id": str(self.organization.id), "exists": True},+ }++ def test_counts_and_membership(self) -> None:+ User.objects.create_and_join(self.organization, "[email protected]", "password1234")+ counted = self.post(+ "count-accounts", {"target_type": "email_domain", "target_value": "throwaway.example"}, "accounts:count"+ )+ assert counted.json() == {"count": 1, "capped": False}+ members = self.post("org-member-count", {"organization_id": str(self.organization.id)}, "org:member_count")+ assert members.json()["exists"] is True+ membership = self.post(+ "posthog-membership", {"organization_id": str(self.organization.id)}, "posthog_membership:check"+ )+ assert membership.json() == {"has_posthog_account": False}++ @parameterized.expand(+ [+ (+ "both targets",+ {+ "user_uuid": "2222abcd-2222-4222-8222-22222222abcd",+ "organization_id": "1111aaaa-1111-4111-8111-11111111aaaa",+ },+ ),+ ("no target", {}),+ ("bad uuid", {"user_uuid": "nope"}),+ ]+ )+ def test_membership_needs_exactly_one_valid_target(self, _name: str, body: dict) -> None:+ assert self.post("posthog-membership", body, "posthog_membership:check").status_code == 400++ def test_count_refuses_other_types(self) -> None:+ response = self.post("count-accounts", {"target_type": "ip", "target_value": "1.2.3.4"}, "accounts:count")+ assert response.status_code == 400++ @patch("products.security.backend.presentation.hub_api.start_sync_now")+ def test_sync_now(self, start: MagicMock) -> None:+ assert self.post("sync-now", {}, "rules:sync_now").status_code == 202+ start.assert_called_once_with()++ @patch("products.security.backend.presentation.hub_api.start_sync_now", side_effect=RuntimeError("temporal down"))+ def test_sync_now_answers_503_when_temporal_is_unreachable(self, start: MagicMock) -> None:+ assert self.post("sync-now", {}, "rules:sync_now").status_code == 503++ def test_mfa_export(self) -> None:+ add_code_based_verification_bypass("[email protected]")+ set_code_based_verification_global_disable(+ reason="email outage", ttl_seconds=3600, disabled_by="[email protected]"+ )+ body = self.post("mfa-bypass-export", {}, "mfa_bypass:export").json()+ assert body["emails"] == ["[email protected]"]+ assert body["global"]["reason"] == "email outage"+ assert body["global"]["actor"] == "[email protected]"+ assert body["global"]["expires_at"].endswith("Z")++ def test_mfa_export_without_a_global_switch(self) -> None:+ assert self.post("mfa-bypass-export", {}, "mfa_bypass:export").json() == {"emails": [], "global": None}++ @parameterized.expand(+ [+ ("no token", None, {}, 401),+ ("wrong key", "subject:resolve", {"key": "other"}, 401),+ ("wrong audience", "subject:resolve", {"aud": "posthog:security_hub:rules"}, 401),+ ("expired", "subject:resolve", {"iat": 100, "exp": 160}, 401),+ ("wrong op", "rules:sync_now", {}, 403),+ ("wrong region", "subject:resolve", {"region": "eu"}, 403),+ ("too long", "subject:resolve", {"exp": int(time.time()) + 3600}, 403),+ ]+ )+ def test_auth_refusals(self, _name: str, op: str | None, claims: dict, expected: int) -> None:+ assert self.post("resolve", {"query": "[email protected]"}, op, **claims).status_code == expected++ @override_settings(SECURITY_HUB_INBOUND_JWT_SECRETS=[])+ def test_unprovisioned_secret_refuses_everything(self) -> None:+ assert self.post("resolve", {"query": "[email protected]"}, "subject:resolve").status_code == 401++ def test_get_is_not_allowed(self) -> None:+ response = self.client.get("/api/security/resolve/", HTTP_AUTHORIZATION=f"Bearer {token('subject:resolve')}")+ assert response.status_code == 405++ def test_global_throttle(self) -> None:+ # One budget for every hub route together: alternate between two different+ # routes so a throttle that was accidentally scoped per view would leave each+ # one under its own limit and this test would pass for the wrong reason.+ requests = [+ ("resolve", {"query": "[email protected]"}, "subject:resolve"),+ ("posthog-membership", {"organization_id": str(self.organization.id)}, "posthog_membership:check"),+ ]+ codes = [self.post(*requests[i % 2]).status_code for i in range(101)]+ assert codes[:100] == [200] * 100+ assert codes[100] == 429++ @parameterized.expand([("no token", None), ("wrong op", "rules:sync_now")])+ def test_refused_requests_do_not_consume_throttle_budget(self, _name: str, op: str | None) -> None:+ for _ in range(150):+ assert self.post("resolve", {"query": "[email protected]"}, op).status_code in (401, 403)+ assert self.post("resolve", {"query": "[email protected]"}, "subject:resolve").status_code == 200diff --git a/tach.toml b/tach.tomlindex 0dc15a009b99..e41c90a46ba4 100644--- a/tach.toml+++ b/tach.toml@@ -1618,6 +1618,7 @@ layer = "modules"expose = ["backend\\.facade.*","backend\\.presentation\\.views.*",+ "backend\\.presentation\\.hub_api.*",]from = ["products.security",