Skip to content

: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.

feat(email): decouple MessagingRecord hash salt and support fallbacks (#61242)

Felipe Rosa de Almeida3ea478d3f1e9
diff --git a/posthog/models/messaging.py b/posthog/models/messaging.py
index 8e4a83a1badb..1127f3aed670 100644
--- a/posthog/models/messaging.py
+++ b/posthog/models/messaging.py
@@ -6,34 +6,65 @@ from django.db import models
from posthog.models.utils import UUIDTModel
+def _hash_email(email: str, salt: str) -> str:
+ if not salt:
+ raise ValueError("Refusing to hash an email with an empty MessagingRecord salt")
+ return hashlib.sha256(f"{salt}_{email}".encode()).hexdigest()
+
+
def get_email_hash(email: str) -> str:
- return hashlib.sha256(f"{settings.SECRET_KEY}_{email}".encode()).hexdigest()
+ """Hash to store when *writing* a MessagingRecord — always the primary salt."""
+ return _hash_email(email, settings.MESSAGING_HASH_SALT)
+
+
+def get_email_hashes(email: str) -> list[str]:
+ """All hashes to match when *reading* — primary salt plus any rotation fallbacks.
+
+ Lets us rotate MESSAGING_HASH_SALT without re-sending already-sent campaigns: new
+ records are written under the primary salt, but dedup lookups still find records
+ written under a previous salt listed in MESSAGING_HASH_SALT_FALLBACKS.
+ """
+ salts = {settings.MESSAGING_HASH_SALT, *settings.MESSAGING_HASH_SALT_FALLBACKS}
+ return [_hash_email(email, salt) for salt in salts if salt]
class MessagingRecordManager(models.Manager):
def get_or_create(self, defaults=None, **kwargs):
raw_email = kwargs.pop("raw_email", None)
+ if raw_email is None:
+ return super().get_or_create(defaults, **kwargs)
- if raw_email:
- kwargs["email_hash"] = get_email_hash(raw_email)
+ # Read across the primary salt and any rotation fallbacks (via the filter
+ # override) so we don't re-send a campaign already recorded under a previous
+ # salt; write under the primary salt only.
+ existing = self.filter(raw_email=raw_email, **kwargs).first()
+ if existing is not None:
+ return existing, False
+ kwargs["email_hash"] = get_email_hash(raw_email)
return super().get_or_create(defaults, **kwargs)
- def filter(self, *args, **kwargs):
+ async def aget_or_create(self, defaults=None, **kwargs):
raw_email = kwargs.pop("raw_email", None)
+ if raw_email is None:
+ return await super().aget_or_create(defaults, **kwargs)
- if raw_email:
- kwargs["email_hash"] = get_email_hash(raw_email)
+ existing = await self.filter(raw_email=raw_email, **kwargs).afirst()
+ if existing is not None:
+ return existing, False
- return super().filter(*args, **kwargs)
+ kwargs["email_hash"] = get_email_hash(raw_email)
+ return await super().aget_or_create(defaults, **kwargs)
- def get(self, *args, **kwargs):
+ def filter(self, *args, **kwargs):
+ # A raw_email maps to multiple hashes across salt rotations, so we only remap it
+ # on filter() — never get(), which would raise MultipleObjectsReturned if both a
+ # pre- and post-rotation record exist. Callers needing one row use
+ # filter(raw_email=...).first()/.exists().
raw_email = kwargs.pop("raw_email", None)
-
- if raw_email:
- kwargs["email_hash"] = get_email_hash(raw_email)
-
- return super().get(*args, **kwargs)
+ if raw_email is not None:
+ kwargs["email_hash__in"] = get_email_hashes(raw_email)
+ return super().filter(*args, **kwargs)
class MessagingRecord(UUIDTModel):
diff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.py
index e31a51d65236..d8ba1c2f5072 100644
--- a/posthog/settings/__init__.py
+++ b/posthog/settings/__init__.py
@@ -49,6 +49,7 @@ from posthog.settings.integrations import *
from posthog.settings.payments import *
from posthog.settings.personhog import *
from posthog.settings.ses import *
+from posthog.settings.email import *
from posthog.settings.exports import *
from posthog.settings.utils import get_from_env, str_to_bool
diff --git a/posthog/settings/email.py b/posthog/settings/email.py
new file mode 100644
index 000000000000..439b2df1aabd
--- /dev/null
+++ b/posthog/settings/email.py
@@ -0,0 +1,9 @@
+import os
+
+from posthog.settings.access import SECRET_KEY
+from posthog.settings.utils import get_list
+
+MESSAGING_HASH_SALT: str = os.getenv("MESSAGING_HASH_SALT") or SECRET_KEY
+MESSAGING_HASH_SALT_FALLBACKS: list[str] = [
+ salt for salt in get_list(os.getenv("MESSAGING_HASH_SALT_FALLBACKS", "")) if salt
+]
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index b3edc009445e..6205ab9fb9f0 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -25,7 +25,7 @@ from posthog.models import Organization, OrganizationInvite, OrganizationMembers
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.comment import Comment
from posthog.models.comment.utils import build_comment_item_url
-from posthog.models.messaging import MessagingRecord, get_email_hash
+from posthog.models.messaging import MessagingRecord, get_email_hashes
from posthog.models.utils import UUIDT
from posthog.ph_client import get_client
from posthog.scoping_audit import skip_team_scope_audit
@@ -300,17 +300,19 @@ def send_invite(invite_id: str) -> None:
# idempotency guard (a previous attempt had already set `sent_at`). Without this
# snapshot, "delivered=True" after `send()` reads identically in both cases — which
# can mislead an operator looking at the success log.
- # MessagingRecord stores SHA-256(SECRET_KEY + email) in `email_hash`. The custom
- # manager remaps a `raw_email=` kwarg to `email_hash=` magically, but django-stubs
- # can't follow that override and mypy then can't resolve `raw_email` against the
- # model's actual fields. Compute the hash directly to keep mypy happy.
- target_email_hash = get_email_hash(invite.target_email)
+ # MessagingRecord stores a one-way SHA-256(MESSAGING_HASH_SALT + email) in
+ # `email_hash`. The custom manager remaps a `raw_email=` kwarg to `email_hash=`
+ # magically, but django-stubs can't follow that override and mypy then can't
+ # resolve `raw_email` against the model's actual fields. Compute the hashes
+ # directly to keep mypy happy, matching the primary salt and any rotation
+ # fallbacks so dedup still works across a salt rotation.
+ target_email_hashes = get_email_hashes(invite.target_email)
already_delivered = MessagingRecord.objects.filter(
- campaign_key=campaign_key, email_hash=target_email_hash, sent_at__isnull=False
+ campaign_key=campaign_key, email_hash__in=target_email_hashes, sent_at__isnull=False
).exists()
message.send(send_async=False)
delivered = MessagingRecord.objects.filter(
- campaign_key=campaign_key, email_hash=target_email_hash, sent_at__isnull=False
+ campaign_key=campaign_key, email_hash__in=target_email_hashes, sent_at__isnull=False
).exists()
if delivered:
OrganizationInvite.objects.filter(pk=invite_id).update(emailing_attempt_made=True)
diff --git a/posthog/temporal/weekly_digest/activities.py b/posthog/temporal/weekly_digest/activities.py
index 6e1ccab278a1..22afc733dec8 100644
--- a/posthog/temporal/weekly_digest/activities.py
+++ b/posthog/temporal/weekly_digest/activities.py
@@ -13,7 +13,7 @@ from pydantic import ValidationError
from structlog.contextvars import bind_contextvars
from temporalio import activity
-from posthog.models.messaging import MessagingRecord, get_email_hash
+from posthog.models.messaging import MessagingRecord
from posthog.ph_client import get_client as get_ph_client
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
from posthog.session_recordings.session_recording_playlist_api import PLAYLIST_COUNT_REDIS_PREFIX
@@ -573,7 +573,7 @@ async def send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:
continue
messaging_record, created = await MessagingRecord.objects.aget_or_create(
- email_hash=get_email_hash(f"org_{organization.id}"), campaign_key=input.digest.key
+ raw_email=f"org_{organization.id}", campaign_key=input.digest.key
)
if not created and messaging_record.sent_at and not input.allow_already_sent:
diff --git a/posthog/test/test_email.py b/posthog/test/test_email.py
index 9a787901a2d6..178d5ce6ce68 100644
--- a/posthog/test/test_email.py
+++ b/posthog/test/test_email.py
@@ -1,9 +1,11 @@
+import hashlib
import datetime
import dataclasses
from decimal import Decimal
from typing import Any
from uuid import UUID
+import pytest
from freezegun import freeze_time
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -11,12 +13,13 @@ from unittest.mock import MagicMock, patch
from django.conf import settings
from django.core import mail
from django.core.exceptions import ImproperlyConfigured
+from django.test import override_settings
from django.utils import timezone
from posthog.email import CUSTOMER_IO_TEMPLATE_ID_MAP, EmailMessage, _send_email, sanitize_email_properties
from posthog.models import Organization, Person, Team, User
from posthog.models.instance_setting import override_instance_config
-from posthog.models.messaging import MessagingRecord
+from posthog.models.messaging import MessagingRecord, get_email_hash, get_email_hashes
class TestEmail(BaseTest):
@@ -442,3 +445,137 @@ class TestEmail(BaseTest):
"the Customer.io transactional message ID, otherwise the sender will raise "
"'Unknown template name' at runtime and capture_exception will swallow it.",
)
+
+
+class TestMessagingHashSalt(BaseTest):
+ def test_get_email_hash_defaults_preserve_legacy_secret_key_hashes(self) -> None:
+ # MESSAGING_HASH_SALT defaults to SECRET_KEY, so hashes written before the salt
+ # was decoupled (SHA-256(SECRET_KEY + email)) stay valid. If this breaks, an
+ # upgrade would orphan every existing email_hash and re-send live campaigns.
+ with self.settings(MESSAGING_HASH_SALT=settings.SECRET_KEY, MESSAGING_HASH_SALT_FALLBACKS=[]):
+ legacy = hashlib.sha256(f"{settings.SECRET_KEY}[email protected]".encode()).hexdigest()
+ self.assertEqual(get_email_hash("[email protected]"), legacy)
+ self.assertEqual(get_email_hashes("[email protected]"), [legacy])
+
+ def test_get_email_hashes_includes_primary_and_fallbacks_deduped(self) -> None:
+ with self.settings(MESSAGING_HASH_SALT="new_salt", MESSAGING_HASH_SALT_FALLBACKS=["old_salt", "new_salt"]):
+ primary = hashlib.sha256(b"[email protected]").hexdigest()
+ fallback = hashlib.sha256(b"[email protected]").hexdigest()
+ self.assertEqual(get_email_hash("[email protected]"), primary)
+ # both salts present and the duplicate "new_salt" collapsed; order is irrelevant
+ # since the result only feeds an `email_hash__in=` lookup
+ self.assertEqual(set(get_email_hashes("[email protected]")), {primary, fallback})
+
+ def test_unset_fallbacks_is_empty_list_not_blank_string(self) -> None:
+ # An unset env var yields [] (not [""]) — get_list("") returns [], and the
+ # settings parsing additionally strips any blanks. This is the invariant that
+ # keeps an empty salt from ever reaching the hash.
+ self.assertEqual(settings.MESSAGING_HASH_SALT_FALLBACKS, [])
+ self.assertNotIn("", settings.MESSAGING_HASH_SALT_FALLBACKS)
+
+ def test_get_email_hash_refuses_empty_primary_salt(self) -> None:
+ # Empty primary salt is a misconfiguration (would write a brute-forceable hash):
+ # the write path fails loud rather than silently degrade.
+ with self.settings(MESSAGING_HASH_SALT=""):
+ with self.assertRaises(ValueError):
+ get_email_hash("[email protected]")
+
+ def test_get_email_hashes_never_hashes_an_empty_salt(self) -> None:
+ # Even if a blank slips into the fallback list (e.g. a stray comma in the env
+ # var), it is skipped — the empty-salt hash is never produced.
+ with self.settings(MESSAGING_HASH_SALT="new_salt", MESSAGING_HASH_SALT_FALLBACKS=["", "old_salt"]):
+ primary = hashlib.sha256(b"[email protected]").hexdigest()
+ fallback = hashlib.sha256(b"[email protected]").hexdigest()
+ empty_salt_hash = hashlib.sha256(b"[email protected]").hexdigest()
+ hashes = get_email_hashes("[email protected]")
+ self.assertEqual(set(hashes), {primary, fallback})
+ self.assertNotIn(empty_salt_hash, hashes)
+
+ def test_dedup_matches_record_written_under_fallback_salt(self) -> None:
+ # Record written before rotation, under the old salt.
+ with self.settings(MESSAGING_HASH_SALT="old_salt", MESSAGING_HASH_SALT_FALLBACKS=[]):
+ MessagingRecord.objects.get_or_create(
+ raw_email="[email protected]", campaign_key="c", defaults={"sent_at": timezone.now()}
+ )
+
+ # After rotation, with the old salt listed as a fallback, the existing record is
+ # found and reused — no duplicate row, no re-send.
+ with self.settings(MESSAGING_HASH_SALT="new_salt", MESSAGING_HASH_SALT_FALLBACKS=["old_salt"]):
+ record, created = MessagingRecord.objects.get_or_create(raw_email="[email protected]", campaign_key="c")
+ self.assertFalse(created)
+ self.assertIsNotNone(record.sent_at)
+ self.assertEqual(MessagingRecord.objects.filter(campaign_key="c").count(), 1)
+
+ def test_dedup_misses_after_rotation_without_fallback(self) -> None:
+ # Control for the test above: without the old salt as a fallback, the pre-rotation
+ # record is unreachable and a fresh row is created — proving the fallback is what
+ # bridges the rotation.
+ with self.settings(MESSAGING_HASH_SALT="old_salt", MESSAGING_HASH_SALT_FALLBACKS=[]):
+ MessagingRecord.objects.get_or_create(
+ raw_email="[email protected]", campaign_key="c", defaults={"sent_at": timezone.now()}
+ )
+
+ with self.settings(MESSAGING_HASH_SALT="new_salt", MESSAGING_HASH_SALT_FALLBACKS=[]):
+ _, created = MessagingRecord.objects.get_or_create(raw_email="[email protected]", campaign_key="c")
+ self.assertTrue(created)
+ self.assertEqual(MessagingRecord.objects.filter(campaign_key="c").count(), 2)
+
+ def test_filter_by_raw_email_matches_across_salts(self) -> None:
+ with self.settings(MESSAGING_HASH_SALT="old_salt", MESSAGING_HASH_SALT_FALLBACKS=[]):
+ MessagingRecord.objects.get_or_create(
+ raw_email="[email protected]", campaign_key="c", defaults={"sent_at": timezone.now()}
+ )
+
+ with self.settings(MESSAGING_HASH_SALT="new_salt", MESSAGING_HASH_SALT_FALLBACKS=["old_salt"]):
+ self.assertTrue(
+ # django-stubs' mypy plugin resolves filter() kwargs against model fields
+ # and can't follow the manager's raw_email→email_hash__in remap.
+ MessagingRecord.objects.filter( # type: ignore[misc]
+ raw_email="[email protected]", campaign_key="c", sent_at__isnull=False
+ ).exists()
+ )
+
+
+# Async tests live as standalone functions — the async ORM (afirst/aget_or_create) can't
+# run inside BaseTest's wrapping transaction, so they need django_db(transaction=True).
[email protected]_db(transaction=True)
+async def test_aget_or_create_reuses_record_written_under_fallback_salt() -> None:
+ with override_settings(MESSAGING_HASH_SALT="old_salt", MESSAGING_HASH_SALT_FALLBACKS=[]):
+ original, created = await MessagingRecord.objects.aget_or_create(
+ raw_email="[email protected]", campaign_key="c", defaults={"sent_at": timezone.now()}
+ )
+ assert created
+
+ # After rotation the old salt is a fallback, so the read finds the existing record:
+ # no duplicate row, no re-send.
+ with override_settings(MESSAGING_HASH_SALT="new_salt", MESSAGING_HASH_SALT_FALLBACKS=["old_salt"]):
+ found, created = await MessagingRecord.objects.aget_or_create(raw_email="[email protected]", campaign_key="c")
+ assert not created
+ assert found.pk == original.pk
+ assert await MessagingRecord.objects.filter(campaign_key="c").acount() == 1
+
+
[email protected]_db(transaction=True)
+async def test_aget_or_create_writes_under_primary_salt_not_a_fallback() -> None:
+ with override_settings(MESSAGING_HASH_SALT="primary_salt", MESSAGING_HASH_SALT_FALLBACKS=["other_salt"]):
+ record, created = await MessagingRecord.objects.aget_or_create(raw_email="[email protected]", campaign_key="c")
+ assert created
+ assert record.email_hash == hashlib.sha256(b"[email protected]").hexdigest()
+
+
[email protected]_db(transaction=True)
+async def test_aget_or_create_without_fallback_creates_duplicate_after_rotation() -> None:
+ # Control: without the old salt as a fallback, the pre-rotation record is unreachable
+ # and a fresh row is created — proving the fallback is what bridges the rotation.
+ with override_settings(MESSAGING_HASH_SALT="old_salt", MESSAGING_HASH_SALT_FALLBACKS=[]):
+ await MessagingRecord.objects.aget_or_create(
+ raw_email="[email protected]", campaign_key="c", defaults={"sent_at": timezone.now()}
+ )
+
+ with override_settings(MESSAGING_HASH_SALT="new_salt", MESSAGING_HASH_SALT_FALLBACKS=[]):
+ _, created = await MessagingRecord.objects.aget_or_create(raw_email="[email protected]", campaign_key="c")
+ assert created
+ assert await MessagingRecord.objects.filter(campaign_key="c").acount() == 2