: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(organization): gate AI training on a signed BAA (#96835)
Rafael Audibertc527f1bfc943
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 7367f3d1334a..69eb0e04815c 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -4319,6 +4319,8 @@ export interface OrganizationApi {readonly is_ai_training_cta_shown: boolean | null/** @nullable */readonly is_hipaa: boolean | null+ /** Whether the organization has a countersigned Business Associate Agreement on file. When true, AI training stays opted out and cannot be changed. */+ readonly has_signed_baa: boolean/** Default statistical method for new experiments in this organization.** * `bayesian` - Bayesiandiff --git a/frontend/src/lib/components/AllowTrainingCallout/AllowTrainingCallout.tsx b/frontend/src/lib/components/AllowTrainingCallout/AllowTrainingCallout.tsxindex a426c0a6472c..75d8421c6cf6 100644--- a/frontend/src/lib/components/AllowTrainingCallout/AllowTrainingCallout.tsx+++ b/frontend/src/lib/components/AllowTrainingCallout/AllowTrainingCallout.tsx@@ -24,7 +24,7 @@ export function AllowTrainingCallout({isHobby ||restrictionReason ||currentOrganization?.is_ai_training_opted_in !== false ||- currentOrganization.is_hipaa ||+ currentOrganization.has_signed_baa ||currentOrganization.is_ai_training_cta_shown === false) {return nulldiff --git a/frontend/src/scenes/settings/organization/OrgAITraining.tsx b/frontend/src/scenes/settings/organization/OrgAITraining.tsxindex 05ed06771071..c7e8d31c0404 100644--- a/frontend/src/scenes/settings/organization/OrgAITraining.tsx+++ b/frontend/src/scenes/settings/organization/OrgAITraining.tsx@@ -10,11 +10,11 @@ import { organizationLogic } from 'scenes/organizationLogic'import { AI_TRAINING_URL } from './aiTrainingConstants'import { ORG_ADMIN_REQUIRED_TOOLTIP } from './organizationSettingsConstants'-function AITrainingDescription({ isHipaa, isLocked }: { isHipaa: boolean; isLocked: boolean }): JSX.Element {- if (isHipaa) {+function AITrainingDescription({ hasSignedBaa, isLocked }: { hasSignedBaa: boolean; isLocked: boolean }): JSX.Element {+ if (hasSignedBaa) {return (<p className="mb-2 text-sm text-secondary">- You are opted out of internal AI training because you are compliant with HIPAA.+ You are opted out of internal AI training because you have a signed BAA with PostHog.</p>)}@@ -44,22 +44,22 @@ export function OrganizationAITrainingOptOut(): JSX.Element {const { updateOrganization } = useActions(organizationLogic)const restrictionReason = useRestrictedArea({ minimumAccessLevel: OrganizationMembershipLevel.Admin })- const isHipaa = !!currentOrganization?.is_hipaa+ const hasSignedBaa = !!currentOrganization?.has_signed_baaconst isLocked = !!currentOrganization?.is_ai_training_locked- const disabledReason = isHipaa- ? 'HIPAA organizations are always opted out of AI training. Please contact us if this needs to change.'+ const disabledReason = hasSignedBaa+ ? 'Organizations with a signed BAA stay opted out of AI training. Contact us if this needs to change.': isLocked? 'Please contact us to change this setting.': restrictionReason? ORG_ADMIN_REQUIRED_TOOLTIP: undefined- const checked = !isHipaa && !!currentOrganization?.is_ai_training_opted_in+ const checked = !hasSignedBaa && !!currentOrganization?.is_ai_training_opted_inreturn (<div className="max-w-160">- <AITrainingDescription isHipaa={isHipaa} isLocked={isLocked} />+ <AITrainingDescription hasSignedBaa={hasSignedBaa} isLocked={isLocked} /><div className="my-4"><LemonSwitchlabel="Enable AI training on anonymized data"diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex f4368eed56bc..2a4628441e22 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -594,6 +594,7 @@ export interface OrganizationType extends OrganizationBasicType {is_ai_training_locked?: booleanis_ai_training_cta_shown?: booleanis_hipaa?: boolean+ has_signed_baa?: booleanmembers_can_invite?: booleanmembers_can_create_projects?: booleanmembers_can_use_personal_api_keys: booleandiff --git a/posthog/admin/ai_training_opt_in_history.py b/posthog/admin/ai_training_opt_in_history.pyindex 9cf8c58d1d93..1a49906bf617 100644--- a/posthog/admin/ai_training_opt_in_history.py+++ b/posthog/admin/ai_training_opt_in_history.py@@ -16,6 +16,8 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.organization import Organization+from products.legal_documents.backend.facade.api import has_signed_baa+# This value matches `detail.changes[].field`. That key holds the display name from# `field_name_overrides`. It equals the model field name because Organization sets no override for# this field. An override would empty this panel. `test_manual_opt_in_then_opt_out...` catches that.@@ -165,17 +167,17 @@ def _build_headline(current: Optional[bool], was_opted_in: bool) -> str:return f"{headline} (value is null)" if current is None else headline-def _hipaa_conflict_warning(organization: Organization) -> Optional[str]:+def _baa_conflict_warning(organization: Organization) -> Optional[str]:# The replay ML mirror reads is_ai_training_opted_in alone. That gate is in# nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.ts. No code in that- # pipeline reads is_hipaa. Change this warning if that gate starts to read is_hipaa.- if not organization.is_hipaa or organization.is_ai_training_opted_in is not True:+ # pipeline reads the BAA. Change this warning if that gate starts to read it.+ if organization.is_ai_training_opted_in is not True or not has_signed_baa(organization.id):return Nonereturn (- "HIPAA is set, but the AI training opt-in is on. The training pipeline reads the opt-in and "- "does not check HIPAA, so this organization's session recordings are eligible for training. "- "Their settings page shows them as opted out, and the API blocks them from changing it "- "themselves. Turn the opt-in off here if that is wrong."+ "A signed BAA is on file, but the AI training opt-in is on. The training pipeline reads the "+ "opt-in and does not check the BAA, so this organization's session recordings are eligible "+ "for training. Their settings page shows them as opted out, and the API blocks them from "+ "changing it themselves. Turn the opt-in off here if that is wrong.")@@ -194,6 +196,6 @@ def get_ai_training_opt_in_history(organization: Organization) -> OptInHistory:return OptInHistory(headline=_build_headline(organization.is_ai_training_opted_in, was_opted_in),changes=changes,- warning=_hipaa_conflict_warning(organization),+ warning=_baa_conflict_warning(organization),truncated=truncated,)diff --git a/posthog/admin/test_ai_training_opt_in_history.py b/posthog/admin/test_ai_training_opt_in_history.pyindex ce5bb6e68816..d4dbecb63d32 100644--- a/posthog/admin/test_ai_training_opt_in_history.py+++ b/posthog/admin/test_ai_training_opt_in_history.py@@ -1,6 +1,11 @@from posthog.test.base import APIBaseTest+from unittest.mock import patchfrom django.contrib.admin.sites import AdminSite+from django.contrib.admin.templatetags.admin_list import results+from django.db import connection+from django.test import RequestFactory+from django.test.utils import CaptureQueriesContextfrom parameterized import parameterized@@ -115,14 +120,13 @@ class TestAITrainingOptInHistory(APIBaseTest):(True, None, False),])- def test_warns_only_when_a_hipaa_organization_is_opted_in(- self, is_hipaa: bool, opted_in: bool | None, expect_warning: bool+ def test_warns_only_when_an_organization_with_a_signed_baa_is_opted_in(+ self, has_baa: bool, opted_in: bool | None, expect_warning: bool) -> None:- self.organization.is_hipaa = is_hipaa- self.organization.save()self._set_opt_in_without_logging(opted_in)- history = get_ai_training_opt_in_history(self.organization)+ with patch("posthog.admin.ai_training_opt_in_history.has_signed_baa", return_value=has_baa):+ history = get_ai_training_opt_in_history(self.organization)self.assertEqual(history.warning is not None, expect_warning)@@ -194,6 +198,36 @@ class TestAITrainingOptInHistory(APIBaseTest):self.assertIn("opted out → opted in", html)self.assertIn(self.user.email, html)+ def _baa_queries(self, context: CaptureQueriesContext) -> list[str]:+ return [q["sql"] for q in context.captured_queries if "legal_documents_legaldocument" in q["sql"]]++ def _render_organization_changelist(self) -> None:+ # Drives the same field resolution the changelist template does, without rendering+ # the admin page itself, whose app-list sidebar cannot reverse in the test settings.+ request = RequestFactory().get("/admin/posthog/organization/")+ request.user = self.user+ changelist = OrganizationAdmin(Organization, AdminSite()).get_changelist_instance(request)+ # The changelist view sets this; `results` reads it to decide whether rows are editable.+ changelist.formset = None+ list(results(changelist))++ def test_admin_organization_list_does_not_read_the_baa_per_row(self) -> None:+ for _ in range(3):+ Organization.objects.bootstrap(self.user)+ self.user.is_staff = True+ self.user.save()++ with CaptureQueriesContext(connection) as context:+ self._render_organization_changelist()++ self.assertEqual(self._baa_queries(context), [])++ def test_admin_change_form_reads_the_baa_once(self) -> None:+ with CaptureQueriesContext(connection) as context:+ OrganizationAdmin(Organization, AdminSite()).ai_training_opt_in_history_display(self.organization)++ self.assertEqual(len(self._baa_queries(context)), 1)+def test_admin_panel_is_blank_on_the_add_form(self) -> None:html = OrganizationAdmin(Organization, AdminSite()).ai_training_opt_in_history_display(Organization())diff --git a/posthog/api/organization.py b/posthog/api/organization.pyindex 927468290005..2fc098cc5f74 100644--- a/posthog/api/organization.py+++ b/posthog/api/organization.py@@ -59,6 +59,7 @@ from posthog.utils import get_safe_cache, safe_cache_setfrom products.access_control.backend.facade.user_access_control import UserAccessControl, visible_teams_for_userfrom products.access_control.backend.models.role import Rolefrom products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin+from products.legal_documents.backend.facade.api import SIGNED_BAA_ANNOTATION, annotate_signed_baa, has_signed_baaclass PremiumMultiorganizationPermission(permissions.BasePermission):@@ -171,6 +172,9 @@ class OrganizationSerializer(read_only=True,help_text="Legacy field; member-join emails are controlled per user in account notification settings.",)+ has_signed_baa = serializers.SerializerMethodField(+ help_text="Whether the organization has a countersigned Business Associate Agreement on file. When true, AI training stays opted out and cannot be changed."+ )class Meta:model = Organization@@ -203,6 +207,7 @@ class OrganizationSerializer("is_ai_training_locked","is_ai_training_cta_shown","is_hipaa",+ "has_signed_baa","default_experiment_stats_method","default_anonymize_ips","default_role_id",@@ -229,6 +234,7 @@ class OrganizationSerializer("is_ai_training_locked","is_ai_training_cta_shown","is_hipaa",+ "has_signed_baa",]extra_kwargs = {"slug": {@@ -287,6 +293,15 @@ class OrganizationSerializer(visible_projects = instance.projects.filter(id__in=self.user_permissions.project_ids_visible_for_user)return list(ProjectBasicSerializer(visible_projects, context=self.context, many=True).data)+ @extend_schema_field(serializers.BooleanField())+ def get_has_signed_baa(self, instance: Organization) -> bool:+ # The list route annotates this in the organizations query. The single-organization+ # routes do not go through that queryset, so they fall back to one lookup.+ annotated = getattr(instance, SIGNED_BAA_ANNOTATION, None)+ if annotated is not None:+ return annotated+ return has_signed_baa(instance.id)+@extend_schema_field(serializers.DictField(child=serializers.CharField()))def get_metadata(self, instance: Organization) -> dict[str, Union[str, int, object]]:return {@@ -369,9 +384,9 @@ class OrganizationSerializer(def validate_is_ai_training_opted_in(self, value: bool | None) -> bool | None:if self.instance and self.instance.is_ai_training_opted_in != value:- if self.instance.is_hipaa:+ if has_signed_baa(self.instance.id):raise serializers.ValidationError(- "HIPAA organizations are always opted out of AI training and this setting cannot be changed.",+ "Organizations with a signed BAA stay opted out of AI training. Contact PostHog support if you need to change this.",code="locked",)if self.instance.is_ai_training_locked:@@ -530,7 +545,7 @@ class OrganizationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if scoped_organizations := self.request.successful_authenticator.access_token.scoped_organizations:queryset = queryset.filter(id__in=scoped_organizations)- return queryset+ return annotate_signed_baa(queryset)def safely_get_object(self, queryset):return self.organizationdiff --git a/posthog/api/test/test_organization.py b/posthog/api/test/test_organization.pyindex 95fb00f8b1f6..d345b31b3d3f 100644--- a/posthog/api/test/test_organization.py+++ b/posthog/api/test/test_organization.py@@ -6,6 +6,8 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import ANY, patchfrom django.core.cache import cache+from django.db import connection+from django.test.utils import CaptureQueriesContextfrom django.utils import timezonefrom parameterized import parameterized@@ -185,6 +187,34 @@ class TestOrganizationAPI(APIBaseTest):self.organization.refresh_from_db()self.assertNotEqual(self.organization.name, "ASDFG")+ def test_cannot_opt_into_ai_training_with_a_signed_baa(self):+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ self.organization.is_ai_training_opted_in = False+ self.organization.save()++ with patch("posthog.api.organization.has_signed_baa", return_value=True):+ response = self.client.patch(+ f"/api/organizations/{self.organization.id}/", {"is_ai_training_opted_in": True}+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "locked")+ self.organization.refresh_from_db()+ self.assertEqual(self.organization.is_ai_training_opted_in, False)++ def test_listing_organizations_reads_the_baa_once_regardless_of_count(self):+ Organization.objects.bootstrap(self.user)+ Organization.objects.bootstrap(self.user)++ with CaptureQueriesContext(connection) as context:+ response = self.client.get("/api/organizations/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertGreaterEqual(len(response.json()["results"]), 3)+ legal_document_queries = [q for q in context.captured_queries if "legal_documents_legaldocument" in q["sql"]]+ self.assertEqual(len(legal_document_queries), 1)+def test_cant_update_plugins_access_level(self):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex 3dcbefd7ee28..60c7eb244d46 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -201,9 +201,11 @@ class TestAutoProjectMiddleware(APIBaseTest):@classmethoddef setUpTestData(cls):super().setUpTestData()- # 55, not 54: the app context serializes the project's tags, which costs one- # indexed lookup on posthog_taggeditem per page load.- cls.base_app_num_queries = 55+ # 56, not 54: the app context serializes the project's tags, which costs one+ # indexed lookup on posthog_taggeditem per page load, and the organization it+ # serializes comes off the user's current_organization foreign key, which carries+ # no signed-BAA annotation, so the AI training lock costs one more indexed lookup.+ cls.base_app_num_queries = 56# Create another team that the user does have access tocls.second_team = create_team(organization=cls.organization, name="Second Life")diff --git a/products/legal_documents/backend/facade/api.py b/products/legal_documents/backend/facade/api.pyindex 193e7129701c..ee1f438e9c2a 100644--- a/products/legal_documents/backend/facade/api.py+++ b/products/legal_documents/backend/facade/api.py@@ -12,6 +12,7 @@ from collections.abc import Callablefrom uuid import UUIDfrom django.db import transaction+from django.db.models import QuerySetfrom django.utils import timezoneimport structlog@@ -21,6 +22,7 @@ from posthog.models.organization import Organizationfrom posthog.ph_client import ph_scoped_capturefrom .. import logic+from ..logic import SIGNED_BAA_ANNOTATION as SIGNED_BAA_ANNOTATIONfrom ..logic.pandadoc import (PandaDocError,verify_webhook_signature as _verify_pandadoc_webhook_signature,@@ -84,6 +86,26 @@ def has_qualifying_baa_addon(organization: Organization) -> bool:return logic.has_qualifying_baa_addon(organization)+def has_signed_baa(organization_id: UUID) -> bool:+ """+ True once the organization has a countersigned BAA on file. This is the+ standing HIPAA gate: it decides whether AI training stays locked off, so it+ must read the signature state rather than a cached flag.++ One query per call. Use `annotate_signed_baa` when serializing a list, and+ keep this for a single organization and for validating a write.+ """+ return logic.has_signed_baa(organization_id)+++def annotate_signed_baa(queryset: QuerySet[Organization]) -> QuerySet[Organization]:+ """+ Add the signed-BAA flag to an Organization queryset as `SIGNED_BAA_ANNOTATION`,+ so serializing N organizations costs one query rather than N.+ """+ return logic.annotate_signed_baa(queryset)++def verify_pandadoc_webhook_signature(*, secret: str, body: bytes, signature: str) -> bool:"""Passthrough so the presentation layer never reaches past the facade."""return _verify_pandadoc_webhook_signature(secret=secret, body=body, signature=signature)diff --git a/products/legal_documents/backend/logic/__init__.py b/products/legal_documents/backend/logic/__init__.pyindex f801bd81c23d..f1cd56e76b61 100644--- a/products/legal_documents/backend/logic/__init__.py+++ b/products/legal_documents/backend/logic/__init__.py@@ -12,7 +12,7 @@ from datetime import timedeltafrom uuid import UUIDfrom django.conf import settings-from django.db.models import QuerySet+from django.db.models import Exists, OuterRef, QuerySetfrom django.utils import timezoneimport structlog@@ -37,6 +37,9 @@ logger = structlog.get_logger(__name__)# Addon types that entitle an organization to a BAA.BAA_ADDON_TYPES = frozenset({"boost", "scale", "enterprise"})+# Attribute `annotate_signed_baa` writes onto each Organization row.+SIGNED_BAA_ANNOTATION = "has_signed_baa"+# PostHog-side mailbox used both as the CC recipient on every signing envelope# and as the document owner. PandaDoc sends the signing email on behalf of the# owner, so this is the From address the signer sees.@@ -81,6 +84,26 @@ def has_qualifying_baa_addon(organization: Organization) -> bool:return False+def _signed_baa_subquery() -> QuerySet[LegalDocument]:+ return LegalDocument.objects.filter(+ organization_id=OuterRef("pk"),+ document_type=DocumentType.BAA,+ status=LegalDocument.Status.SIGNED,+ )+++def has_signed_baa(organization_id: UUID) -> bool:+ return LegalDocument.objects.filter(+ organization_id=organization_id,+ document_type=DocumentType.BAA,+ status=LegalDocument.Status.SIGNED,+ ).exists()+++def annotate_signed_baa(queryset: QuerySet[Organization]) -> QuerySet[Organization]:+ return queryset.annotate(**{SIGNED_BAA_ANNOTATION: Exists(_signed_baa_subquery())})++def exists_for_organization_and_type(organization_id: UUID, document_type: str) -> bool:return LegalDocument.objects.filter(organization_id=organization_id, document_type=document_type).exists()diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 6fbba5114c2c..6cbe3d0cebaf 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -125,6 +125,8 @@ export interface OrganizationApi {readonly is_ai_training_cta_shown: boolean | null/** @nullable */readonly is_hipaa: boolean | null+ /** Whether the organization has a countersigned Business Associate Agreement on file. When true, AI training stays opted out and cannot be changed. */+ readonly has_signed_baa: boolean/** Default statistical method for new experiments in this organization.** * `bayesian` - Bayesian@@ -233,6 +235,8 @@ export interface PatchedOrganizationApi {readonly is_ai_training_cta_shown?: boolean | null/** @nullable */readonly is_hipaa?: boolean | null+ /** Whether the organization has a countersigned Business Associate Agreement on file. When true, AI training stays opted out and cannot be changed. */+ readonly has_signed_baa?: boolean/** Default statistical method for new experiments in this organization.** * `bayesian` - Bayesiandiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 979004cdf7ad..951ecab1c50d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -54408,6 +54408,8 @@ export namespace Schemas {readonly is_ai_training_cta_shown: boolean | null;/** @nullable */readonly is_hipaa: boolean | null;+ /** Whether the organization has a countersigned Business Associate Agreement on file. When true, AI training stays opted out and cannot be changed. */+ readonly has_signed_baa: boolean;/** Default statistical method for new experiments in this organization.** * `bayesian` - Bayesian@@ -65772,6 +65774,8 @@ export namespace Schemas {readonly is_ai_training_cta_shown?: boolean | null;/** @nullable */readonly is_hipaa?: boolean | null;+ /** Whether the organization has a countersigned Business Associate Agreement on file. When true, AI training stays opted out and cannot be changed. */+ readonly has_signed_baa?: boolean;/** Default statistical method for new experiments in this organization.** * `bayesian` - Bayesian