: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(conversations): add signing secret model (#76048)
Patricio34c504433042
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex cc40993cc1fa..b3ad0227beae 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -310,6 +310,7 @@ rules:|Threshold|ToleratedHash|TeamConversationsTeamsConfig+ |SigningSecret|Ticket|TicketView|TicketViewFavorite@@ -637,6 +638,7 @@ rules:|Threshold|ToleratedHash|TeamConversationsTeamsConfig+ |SigningSecret|Ticket|TicketView|TicketViewFavoritediff --git a/posthog/models/scoping/manager.py b/posthog/models/scoping/manager.pyindex 8ed77f847c2f..3cffbb8720d0 100644--- a/posthog/models/scoping/manager.py+++ b/posthog/models/scoping/manager.py@@ -131,9 +131,33 @@ class TeamScopedManager(models.Manager[T]):return self._queryset_class(self.model, using=self._db)._apply_team_filter(team_id)+class EnvironmentScopedManager(TeamScopedManager[T]):+ """Fail-closed manager for models where sibling environments must stay isolated.++ `TeamScopedManager`'s contract is canonical (project-level) team ids: ambient+ request scope and `for_team()` both resolve a child environment's id to the+ parent. For per-environment rows (e.g. signing secrets) that is a cross-+ environment leak: reads for one environment would select another's row.++ Here `for_team()` filters by the literal id given, and ambient-context reads+ are refused so a canonicalized id can never silently pick a sibling's row.+ """++ def get_queryset(self) -> TeamScopedQuerySet[T]:+ raise TeamScopeError(+ f"{self.model.__name__} is environment-scoped: ambient team scope is canonical "+ "(project-level) and could select a sibling environment's row. "+ "Use .for_team(team_id) with the environment's own id, or .unscoped()."+ )++ def for_team(self, team_id: int, *, canonical: bool = False) -> TeamScopedQuerySet[T]:+ return self._queryset_class(self.model, using=self._db)._apply_team_filter(team_id)++__all__ = ["TeamScopeError","TeamScopedQuerySet","TeamScopedManager",+ "EnvironmentScopedManager","resolve_effective_team_id",]diff --git a/products/conversations/backend/migrations/0055_signingsecret.py b/products/conversations/backend/migrations/0055_signingsecret.pynew file mode 100644index 000000000000..50ec9dee8c92--- /dev/null+++ b/products/conversations/backend/migrations/0055_signingsecret.py@@ -0,0 +1,46 @@+# Generated by Django 5.2.14 on 2026-07-31 17:31++import django.db.models.deletion+from django.db import migrations, models++import posthog.uuidt+import posthog.helpers.encrypted_fields+++class Migration(migrations.Migration):+ dependencies = [+ ("conversations", "0054_ticket_sla_snooze_asc_indexes"),+ ("posthog", "1280_alter_integration_kind"),+ ]++ operations = [+ migrations.CreateModel(+ name="SigningSecret",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("secret", posthog.helpers.encrypted_fields.EncryptedTextField()),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "team",+ models.OneToOneField(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="conversations_signing_secret",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "posthog_conversations_signing_secret",+ },+ ),+ ]diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txtindex 2171c438fdea..9bfe514f1035 100644--- a/products/conversations/backend/migrations/max_migration.txt+++ b/products/conversations/backend/migrations/max_migration.txt@@ -1 +1 @@-0054_ticket_sla_snooze_asc_indexes+0055_signingsecretdiff --git a/products/conversations/backend/models/__init__.py b/products/conversations/backend/models/__init__.pyindex c10aad9336b8..1e46a62cc476 100644--- a/products/conversations/backend/models/__init__.py+++ b/products/conversations/backend/models/__init__.py@@ -4,6 +4,7 @@ from .email_message_mapping import EmailMessageMappingfrom .email_outbox_message import EmailOutboxMessagefrom .github_comment_mapping import GithubCommentMappingfrom .restore_token import ConversationRestoreToken+from .signing_secret import SigningSecretfrom .team_conversations_email_config import EmailChannelfrom .team_conversations_slack_config import TeamConversationsSlackConfigfrom .team_conversations_teams_channel_sync import TeamConversationsTeamsChannelSync@@ -23,6 +24,7 @@ __all__ = ["GithubCommentMapping","Priority","RuleType",+ "SigningSecret","Status","TeamConversationsSlackConfig","TeamConversationsTeamsChannelSync",diff --git a/products/conversations/backend/models/signing_secret.py b/products/conversations/backend/models/signing_secret.pynew file mode 100644index 000000000000..f5b34f444680--- /dev/null+++ b/products/conversations/backend/models/signing_secret.py@@ -0,0 +1,43 @@+from __future__ import annotations++from django.db import models++from posthog.helpers.encrypted_fields import EncryptedTextField+from posthog.models.scoping.manager import EnvironmentScopedManager+from posthog.models.utils import UUIDModel+++class SigningSecret(UUIDModel):+ """Per-team secret for widget identity verification (HMAC signing).++ Replaces the legacy plaintext Team.secret_api_token for Conversations (#63111).+ HMAC verification needs the raw value server-side, so the secret is encrypted at+ rest rather than hashed — and it is only ever valid for signing, never for API+ authentication, so a leaked value can't call any API.++ Environment-scoped on purpose: sibling environments hold independent secrets,+ mirroring Team.secret_api_token. No RootTeamMixin (its save() canonicalizes team+ to the parent), and `EnvironmentScopedManager` filters by the literal team id —+ readers pass the environment's own id via `objects.for_team(team.id)`.+ """++ objects = EnvironmentScopedManager()++ # db_constraint=False so CreateModel takes no lock on posthog_team.+ team = models.OneToOneField(+ "posthog.Team",+ on_delete=models.CASCADE,+ db_constraint=False,+ related_name="conversations_signing_secret",+ )+ # Encryption/decryption is transparent via the field; value reads back as the raw string.+ # Non-deterministic ciphertext: never filter by this value — fetch by team and compare.+ secret = EncryptedTextField()+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "posthog_conversations_signing_secret"++ def __str__(self) -> str:+ return f"SigningSecret(team={self.team_id})"diff --git a/products/conversations/backend/tests/test_signing_secret.py b/products/conversations/backend/tests/test_signing_secret.pynew file mode 100644index 000000000000..183d91c515e6--- /dev/null+++ b/products/conversations/backend/tests/test_signing_secret.py@@ -0,0 +1,28 @@+from posthog.test.base import BaseTest++from posthog.models.team import Team++from products.conversations.backend.models import SigningSecret+++class TestSigningSecret(BaseTest):+ def test_child_environment_keeps_its_own_team_on_save(self):+ # Environment-scoped by design: a canonicalizing save() (RootTeamMixin) would rewrite+ # the child's row to the parent team, sharing one secret across sibling environments+ # and making per-environment copy rows collide on the OneToOne constraint.+ child_team = Team.objects.create(+ organization=self.organization,+ project=self.project,+ parent_team=self.team,+ name="Child environment",+ )++ parent_secret = SigningSecret(team=self.team, secret="phs_parent_secret")+ parent_secret.save()+ child_secret = SigningSecret(team=child_team, secret="phs_child_secret")+ child_secret.save()++ child_secret.refresh_from_db()+ self.assertEqual(child_secret.team_id, child_team.id)+ self.assertEqual(SigningSecret.objects.unscoped().count(), 2)+ self.assertEqual(SigningSecret.objects.for_team(child_team.id).get().secret, "phs_child_secret")