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.

fix(encryption): support SECRET_KEY_FALLBACKS on encrypted fields (#61947)

Felipe Rosa de Almeidaa9985df74a88
diff --git a/posthog/helpers/encrypted_fields.py b/posthog/helpers/encrypted_fields.py
index 68ddc9e15764..6d92bb6c8afe 100644
--- a/posthog/helpers/encrypted_fields.py
+++ b/posthog/helpers/encrypted_fields.py
@@ -5,6 +5,7 @@ import json
import base64
from django.conf import settings
+from django.core.checks import Error, register
from django.db import models
from django.utils.functional import cached_property
@@ -32,17 +33,22 @@ class EncryptedFieldMixin:
keys = [base64.urlsafe_b64encode(x.encode("utf-8")) for x in settings.ENCRYPTION_SALT_KEYS]
# TODO: Remove support for these once the migration is complete
- # Generate keys for each salt key and secret key
- for salt_key in settings.SALT_KEY:
- salt = bytes(salt_key, "utf-8")
- kdf = PBKDF2HMAC(
- algorithm=hashes.SHA256(),
- length=32,
- salt=salt,
- iterations=100000,
- backend=default_backend(),
- )
- keys.append(base64.urlsafe_b64encode(kdf.derive(settings.SECRET_KEY.encode("utf-8"))))
+ # Legacy decrypt-only keys for values written before the ENCRYPTION_SALT_KEYS rework.
+ # We derive from SECRET_KEY *and* every SECRET_KEY_FALLBACKS entry so that rotating
+ # SECRET_KEY (old key moved into SECRET_KEY_FALLBACKS) keeps any legacy rows decryptable
+ # — without this, rotation permanently strands them. These are appended last, so they
+ # are never used to encrypt new values.
+ for secret_key in [settings.SECRET_KEY, *settings.SECRET_KEY_FALLBACKS]:
+ for salt_key in settings.SALT_KEY:
+ salt = bytes(salt_key, "utf-8")
+ kdf = PBKDF2HMAC(
+ algorithm=hashes.SHA256(),
+ length=32,
+ salt=salt,
+ iterations=100000,
+ backend=default_backend(),
+ )
+ keys.append(base64.urlsafe_b64encode(kdf.derive(secret_key.encode("utf-8"))))
return keys
@cached_property
@@ -203,3 +209,24 @@ class EncryptedJSONStringField(EncryptedFieldMixin, models.JSONField):
pass
return value
+
+
+@register()
+def check_encryption_salt_keys(app_configs, **kwargs):
+ # Each ENCRYPTION_SALT_KEYS entry is used directly as a Fernet key, which must be exactly 32 bytes.
+ # A wrong-length key otherwise fails lazily with an opaque error on the first encrypt/decrypt — and
+ # during a SECRET_KEY / ENCRYPTION_SALT_KEYS rotation that surfaces as a confusing runtime crash
+ # instead of a clear config error. SECRET_KEY / SALT_KEY are exempt: they run through PBKDF2, which
+ # normalizes any input length to 32 bytes.
+ errors = []
+ for index, key in enumerate(settings.ENCRYPTION_SALT_KEYS):
+ byte_length = len(key.encode("utf-8"))
+ if byte_length != 32:
+ errors.append(
+ Error(
+ f"ENCRYPTION_SALT_KEYS[{index}] must be exactly 32 bytes, got {byte_length}.",
+ hint="Generate one with `openssl rand -hex 16` (produces 32 characters).",
+ id="posthog.E004",
+ )
+ )
+ return errors
diff --git a/posthog/helpers/tests/test_encrypted_fields.py b/posthog/helpers/tests/test_encrypted_fields.py
index 7e9a50b3d889..d4fa6a741bcd 100644
--- a/posthog/helpers/tests/test_encrypted_fields.py
+++ b/posthog/helpers/tests/test_encrypted_fields.py
@@ -7,9 +7,13 @@ from unittest.mock import patch
from django.test import SimpleTestCase, override_settings
from cryptography.fernet import Fernet, InvalidToken
+from cryptography.hazmat.backends import default_backend
+from cryptography.hazmat.primitives import hashes
+from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from parameterized import parameterized
-from posthog.helpers.encrypted_fields import EncryptedFieldMixin
+from posthog.helpers.encrypted_fields import EncryptedFieldMixin, check_encryption_salt_keys
+from posthog.settings.utils import get_list
KEY_A = "a" * 32
KEY_B = "b" * 32
@@ -17,6 +21,7 @@ KEY_C = "c" * 32
OLD = "o" * 32
NEW = "n" * 32
+SALT = "legacy-salt-key"
PLAINTEXT = "super-secret-value"
@@ -25,6 +30,23 @@ def _fernet(raw_key: str) -> Fernet:
return Fernet(base64.urlsafe_b64encode(raw_key.encode("utf-8")))
+def _legacy_fernet(secret_key: str, salt_key: str = SALT) -> Fernet:
+ # Reproduces the legacy PBKDF2(SECRET_KEY, salt=SALT_KEY) derivation in EncryptedFieldMixin.keys
+ kdf = PBKDF2HMAC(
+ algorithm=hashes.SHA256(),
+ length=32,
+ salt=salt_key.encode("utf-8"),
+ iterations=100000,
+ backend=default_backend(),
+ )
+ return Fernet(base64.urlsafe_b64encode(kdf.derive(secret_key.encode("utf-8"))))
+
+
+def _legacy_token(secret_key: str, plaintext: str = PLAINTEXT) -> str:
+ # A value as it was written in the pre-ENCRYPTION_SALT_KEYS era, encrypted under the SECRET_KEY
+ return _legacy_fernet(secret_key).encrypt(plaintext.encode("utf-8")).decode("utf-8")
+
+
def _encrypt_with(keys: list[str], plaintext: str = PLAINTEXT) -> str:
# Simulates an app running with the given ENCRYPTION_SALT_KEYS encrypting a value
with override_settings(ENCRYPTION_SALT_KEYS=keys, SALT_KEY=[]):
@@ -156,3 +178,76 @@ class TestEncryptionKeyRotationTwoStep(SimpleTestCase):
token = _encrypt_with([NEW, OLD])
with self.assertRaises(InvalidToken):
_decrypt_with([OLD], token)
+
+
+class TestSecretKeyRotation(SimpleTestCase):
+ # Legacy rows were encrypted under PBKDF2(SECRET_KEY, salt=SALT_KEY). Rotating SECRET_KEY must
+ # keep them decryptable via SECRET_KEY_FALLBACKS, otherwise the rotation strands them forever.
+
+ @override_settings(SECRET_KEY=OLD, SECRET_KEY_FALLBACKS=[], SALT_KEY=[SALT], ENCRYPTION_SALT_KEYS=[KEY_A])
+ def test_legacy_value_decrypts_before_rotation(self):
+ assert EncryptedFieldMixin().decrypt(_legacy_token(OLD)) == PLAINTEXT
+
+ @override_settings(SECRET_KEY=NEW, SECRET_KEY_FALLBACKS=[OLD], SALT_KEY=[SALT], ENCRYPTION_SALT_KEYS=[KEY_A])
+ def test_legacy_value_decrypts_after_rotation_via_fallback(self):
+ # OLD has moved out of SECRET_KEY into SECRET_KEY_FALLBACKS; legacy data must still read
+ assert EncryptedFieldMixin().decrypt(_legacy_token(OLD)) == PLAINTEXT
+
+ @override_settings(SECRET_KEY=NEW, SECRET_KEY_FALLBACKS=[], SALT_KEY=[SALT], ENCRYPTION_SALT_KEYS=[KEY_A])
+ def test_rotation_without_fallback_strands_legacy_value(self):
+ # Documents the data-loss failure mode the fallback support prevents
+ with self.assertRaises(InvalidToken):
+ EncryptedFieldMixin().decrypt(_legacy_token(OLD))
+
+ @override_settings(SECRET_KEY=NEW, SECRET_KEY_FALLBACKS=[OLD], SALT_KEY=[SALT], ENCRYPTION_SALT_KEYS=[KEY_A])
+ def test_new_writes_use_encryption_salt_keys_not_secret_derived_key(self):
+ # The SECRET_KEY-derived keys are decrypt-only; new values must encrypt under ENCRYPTION_SALT_KEYS[0]
+ token = EncryptedFieldMixin().encrypt(PLAINTEXT)
+
+ assert _fernet(KEY_A).decrypt(token.encode("utf-8")).decode("utf-8") == PLAINTEXT
+ with self.assertRaises(InvalidToken):
+ _legacy_fernet(NEW).decrypt(token.encode("utf-8"))
+
+
+class TestEncryptionSaltKeysCheck(SimpleTestCase):
+ # System check that ENCRYPTION_SALT_KEYS entries are valid Fernet keys (exactly 32 bytes). Each is
+ # used directly as a Fernet key, so a wrong-length one would otherwise crash opaquely on first use.
+
+ @override_settings(ENCRYPTION_SALT_KEYS=["00beef0000beef0000beef0000beef00"])
+ def test_single_valid_key_passes(self):
+ assert check_encryption_salt_keys(None) == []
+
+ @override_settings(ENCRYPTION_SALT_KEYS=get_list("00beef0000beef0000beef0000beef00," + "a" * 32))
+ def test_two_valid_keys_pass(self):
+ assert check_encryption_salt_keys(None) == []
+
+ @override_settings(ENCRYPTION_SALT_KEYS=get_list(",".join(["a" * 32, "b" * 32, "c" * 32])))
+ def test_three_valid_keys_pass(self):
+ assert check_encryption_salt_keys(None) == []
+
+ @override_settings(ENCRYPTION_SALT_KEYS=["tooshort"])
+ def test_short_key_is_flagged(self):
+ errors = check_encryption_salt_keys(None)
+ assert len(errors) == 1
+ assert errors[0].id == "posthog.E004"
+ assert "ENCRYPTION_SALT_KEYS[0]" in errors[0].msg
+ assert "got 8" in errors[0].msg
+
+ @override_settings(ENCRYPTION_SALT_KEYS=["a" * 33])
+ def test_long_key_is_flagged(self):
+ errors = check_encryption_salt_keys(None)
+ assert len(errors) == 1
+ assert "got 33" in errors[0].msg
+
+ @override_settings(ENCRYPTION_SALT_KEYS=["a" * 32, "b" * 31])
+ def test_reports_index_of_offending_key(self):
+ errors = check_encryption_salt_keys(None)
+ assert len(errors) == 1
+ assert "ENCRYPTION_SALT_KEYS[1]" in errors[0].msg
+
+ @override_settings(ENCRYPTION_SALT_KEYS=["é" * 32])
+ def test_counts_bytes_not_characters(self):
+ # 32 'é' is 64 bytes in UTF-8 — must be flagged, since Fernet keys are byte-sized
+ errors = check_encryption_salt_keys(None)
+ assert len(errors) == 1
+ assert "got 64" in errors[0].msg
diff --git a/posthog/management/commands/audit_encrypted_field_keys.py b/posthog/management/commands/audit_encrypted_field_keys.py
new file mode 100644
index 000000000000..2a1d1a057e00
--- /dev/null
+++ b/posthog/management/commands/audit_encrypted_field_keys.py
@@ -0,0 +1,298 @@
+import json
+import base64
+import binascii
+from dataclasses import (
+ dataclass,
+ field as dataclass_field,
+)
+
+from django.apps import apps
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError
+from django.db import connections, router
+
+from cryptography.fernet import Fernet, InvalidToken, MultiFernet
+from cryptography.hazmat.backends import default_backend
+from cryptography.hazmat.primitives import hashes
+from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
+
+from posthog.helpers.encrypted_fields import EncryptedFieldMixin
+
+# Read-only audit that answers a single question before a SECRET_KEY rotation: is any encrypted-field
+# value still decryptable *only* by a SECRET_KEY-derived legacy key? Those rows would be permanently
+# stranded the moment the old key leaves SECRET_KEY / SECRET_KEY_FALLBACKS. New writes use
+# ENCRYPTION_SALT_KEYS[0]; the SECRET_KEY-derived keys are a decrypt-only fallback for pre-rework data.
+
+# Per-row classifications. Only LEGACY blocks dropping the old key; the rest are informational.
+CLEAN = "clean" # every token decrypts under ENCRYPTION_SALT_KEYS — unaffected by rotation
+LEGACY = "legacy" # at least one token decrypts only under a SECRET_KEY-derived key
+PLAINTEXT = "plaintext" # a leaf was never a Fernet token — stored unencrypted
+UNREADABLE = "unreadable" # token-shaped but no configured key decrypts it (wrong/lost key, or corrupt)
+EMPTY = "empty" # no meaningful value to classify (NULL, "", {}, [])
+
+# jsonb leaves that carry no secret — an EncryptedJSONField with an empty value serializes to these
+_EMPTY_MARKERS = frozenset({"", "{}", "[]", "null"})
+
+# A Fernet token is urlsafe-base64 of >= 73 bytes whose first (version) byte is 0x80
+_FERNET_VERSION = 0x80
+_FERNET_MIN_BYTES = 73
+
+
+@dataclass
+class FieldReport:
+ label: str
+ scanned: int = 0
+ counts: dict[str, int] = dataclass_field(
+ default_factory=lambda: {CLEAN: 0, LEGACY: 0, PLAINTEXT: 0, UNREADABLE: 0, EMPTY: 0}
+ )
+ samples: dict[str, list[str]] = dataclass_field(default_factory=dict)
+ error: str | None = None
+
+
+def _salt_only_fernet() -> MultiFernet | None:
+ keys = [base64.urlsafe_b64encode(x.encode("utf-8")) for x in settings.ENCRYPTION_SALT_KEYS]
+ return MultiFernet([Fernet(k) for k in keys]) if keys else None
+
+
+def _legacy_fernet() -> MultiFernet | None:
+ # Mirrors the SECRET_KEY-derived branch of EncryptedFieldMixin.keys (SECRET_KEY + every fallback)
+ keys = []
+ for secret_key in [settings.SECRET_KEY, *settings.SECRET_KEY_FALLBACKS]:
+ for salt_key in settings.SALT_KEY:
+ kdf = PBKDF2HMAC(
+ algorithm=hashes.SHA256(),
+ length=32,
+ salt=salt_key.encode("utf-8"),
+ iterations=100000,
+ backend=default_backend(),
+ )
+ keys.append(base64.urlsafe_b64encode(kdf.derive(secret_key.encode("utf-8"))))
+ return MultiFernet([Fernet(k) for k in keys]) if keys else None
+
+
+def _leaves(value: object) -> list[str]:
+ # An EncryptedJSONField stores a token per leaf; scalar / JSON-string fields store a single token.
+ # Callers must hand jsonb columns over as already-parsed dicts/lists (see Command._coerce_raw) —
+ # Django's psycopg setup returns jsonb as a JSON *string* from a raw cursor, which would otherwise
+ # be misread here as one opaque leaf.
+ if isinstance(value, str):
+ return [value]
+ if isinstance(value, dict):
+ return [leaf for v in value.values() for leaf in _leaves(v)]
+ if isinstance(value, list):
+ return [leaf for v in value for leaf in _leaves(v)]
+ return []
+
+
+def _looks_like_fernet_token(value: str) -> bool:
+ try:
+ decoded = base64.urlsafe_b64decode(value.encode("utf-8"))
+ except (binascii.Error, ValueError):
+ return False
+ return len(decoded) >= _FERNET_MIN_BYTES and decoded[0] == _FERNET_VERSION
+
+
+def _decryptable(fernet: MultiFernet | None, token: str) -> bool:
+ if fernet is None:
+ return False
+ try:
+ fernet.decrypt(token.encode("utf-8"))
+ return True
+ except (InvalidToken, ValueError, TypeError):
+ return False
+
+
+def _classify_leaf(leaf: str, salt_only: MultiFernet | None, legacy: MultiFernet | None) -> str:
+ if not _looks_like_fernet_token(leaf):
+ return PLAINTEXT
+ if _decryptable(salt_only, leaf):
+ return CLEAN
+ if _decryptable(legacy, leaf):
+ return LEGACY
+ return UNREADABLE
+
+
+def classify(raw: object, salt_only: MultiFernet | None, legacy: MultiFernet | None) -> str:
+ leaves = [leaf for leaf in _leaves(raw) if leaf not in _EMPTY_MARKERS]
+ if not leaves:
+ return EMPTY
+
+ # Classify per leaf, then collapse to the row's most severe leaf. LEGACY must win over PLAINTEXT /
+ # UNREADABLE: a single legacy-encrypted leaf is stranded on rotation, so a row containing one must
+ # count as LEGACY even if a sibling leaf is plaintext — otherwise `safe_to_drop_secret_key` could
+ # report true while legacy tokens are still present. CLEAN only when every leaf is clean.
+ buckets = {_classify_leaf(leaf, salt_only, legacy) for leaf in leaves}
+ for bucket in (LEGACY, UNREADABLE, PLAINTEXT):
+ if bucket in buckets:
+ return bucket
+ return CLEAN
+
+
+class Command(BaseCommand):
+ help = (
+ "Audit every Fernet-encrypted DB field and report which rows still depend on a SECRET_KEY-derived "
+ "legacy key. Read-only. Run before rotating SECRET_KEY; a clean run (0 legacy rows) means the old "
+ "key can be safely dropped from SECRET_KEY / SECRET_KEY_FALLBACKS."
+ )
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ "--field",
+ metavar="app_label.Model.field",
+ help="Audit only this field instead of every discovered encrypted field",
+ )
+ parser.add_argument("--batch-size", type=int, default=1000, help="Rows fetched per DB round-trip")
+ parser.add_argument("--limit", type=int, default=0, help="Max rows to scan per field (0 = all)")
+ parser.add_argument("--samples", type=int, default=5, help="Sample pks to record per flagged class")
+ parser.add_argument("--json", action="store_true", help="Emit a machine-readable JSON report instead")
+
+ def handle(self, *args, **options):
+ salt_only = _salt_only_fernet()
+ legacy = _legacy_fernet()
+ if salt_only is None:
+ raise CommandError("ENCRYPTION_SALT_KEYS is empty — nothing can be classified as clean")
+
+ all_fields = self._discover_fields()
+ if not all_fields:
+ raise CommandError("No encrypted fields found")
+
+ only = options.get("field")
+ fields = [(m, f) for m, f in all_fields if only is None or self._label(m, f) == only]
+ if only and not fields:
+ available = "\n ".join(sorted(self._label(m, f) for m, f in all_fields))
+ raise CommandError(f"--field {only!r} did not match any encrypted field. Available:\n {available}")
+
+ reports = [self._audit_field(model, model_field, salt_only, legacy, options) for model, model_field in fields]
+
+ if options["json"]:
+ self._emit_json(reports)
+ else:
+ self._emit_console(reports)
+
+ @staticmethod
+ def _label(model, model_field) -> str:
+ return f"{model._meta.app_label}.{model.__name__}.{model_field.name}"
+
+ def _discover_fields(self):
+ discovered = []
+ for model in apps.get_models():
+ if model._meta.proxy:
+ continue
+ for model_field in model._meta.concrete_fields:
+ if isinstance(model_field, EncryptedFieldMixin):
+ discovered.append((model, model_field))
+ return discovered
+
+ def _audit_field(self, model, model_field, salt_only, legacy, options) -> FieldReport:
+ report = FieldReport(label=self._label(model, model_field))
+ samples = options["samples"]
+
+ connection = connections[router.db_for_read(model)]
+ quote = connection.ops.quote_name
+ table, column, pk_column = model._meta.db_table, model_field.column, model._meta.pk.column
+
+ # Only EncryptedJSONField is a jsonb column (per-leaf tokens); every other encrypted field is a
+ # text column holding a single token. A raw cursor returns jsonb as a JSON string under Django's
+ # psycopg config, so those rows need parsing before their leaves can be classified individually.
+ is_json_column = model_field.get_internal_type() == "JSONField"
+
+ cursor = connection.cursor()
+ try:
+ for pk, raw in self._iter_rows(cursor, quote, table, column, pk_column, options):
+ report.scanned += 1
+ bucket = classify(self._coerce_raw(raw, is_json_column), salt_only, legacy)
+ report.counts[bucket] += 1
+ if bucket in (LEGACY, PLAINTEXT, UNREADABLE):
+ pks = report.samples.setdefault(bucket, [])
+ if len(pks) < samples:
+ pks.append(str(pk))
+ except Exception as exc: # missing table on a partially-migrated DB, permission issues, etc.
+ report.error = str(exc)
+ finally:
+ cursor.close()
+ return report
+
+ @staticmethod
+ def _coerce_raw(raw: object, is_json_column: bool) -> object:
+ # A raw cursor hands jsonb back as a JSON string (Django parses jsonb itself in JSONField),
+ # so decode it into the dict/list whose leaves carry the per-leaf tokens. NULL stays None.
+ # The isinstance guard keeps this correct if a backend ever returns jsonb already parsed.
+ if is_json_column and isinstance(raw, str):
+ try:
+ return json.loads(raw)
+ except (json.JSONDecodeError, TypeError):
+ return raw
+ return raw
+
+ def _iter_rows(self, cursor, quote, table, column, pk_column, options):
+ batch_size, limit = options["batch_size"], options["limit"]
+ last_pk, fetched = None, 0
+ select = f"SELECT {quote(pk_column)}, {quote(column)} FROM {quote(table)}"
+ while True:
+ if last_pk is None:
+ cursor.execute(f"{select} ORDER BY {quote(pk_column)} LIMIT %s", [batch_size])
+ else:
+ cursor.execute(
+ f"{select} WHERE {quote(pk_column)} > %s ORDER BY {quote(pk_column)} LIMIT %s",
+ [last_pk, batch_size],
+ )
+ rows = cursor.fetchall()
+ if not rows:
+ return
+ for pk, raw in rows:
+ yield pk, raw
+ last_pk = pk
+ fetched += 1
+ if limit and fetched >= limit:
+ return
+
+ def _emit_json(self, reports):
+ payload = {
+ "safe_to_drop_secret_key": all(r.counts[LEGACY] == 0 and r.error is None for r in reports),
+ "fields": [r.__dict__ for r in reports],
+ }
+ self.stdout.write(json.dumps(payload, indent=2))
+
+ def _emit_console(self, reports):
+ total_legacy = sum(r.counts[LEGACY] for r in reports)
+ total_plaintext = sum(r.counts[PLAINTEXT] for r in reports)
+ total_unreadable = sum(r.counts[UNREADABLE] for r in reports)
+
+ for r in sorted(reports, key=lambda x: x.label):
+ if r.error:
+ self.stdout.write(self.style.WARNING(f" SKIP {r.label}: {r.error}"))
+ continue
+ c = r.counts
+ style = self.style.ERROR if c[LEGACY] else self.style.SUCCESS
+ self.stdout.write(
+ style(
+ f" {r.label}: scanned={r.scanned} clean={c[CLEAN]} legacy={c[LEGACY]} "
+ f"plaintext={c[PLAINTEXT]} unreadable={c[UNREADABLE]} empty={c[EMPTY]}"
+ )
+ )
+ for bucket in (LEGACY, PLAINTEXT, UNREADABLE):
+ if r.samples.get(bucket):
+ self.stdout.write(f" {bucket} pks (sample): {', '.join(r.samples[bucket])}")
+
+ self.stdout.write("")
+ if total_legacy:
+ self.stdout.write(
+ self.style.ERROR(
+ f"{total_legacy} row(s) still depend on a SECRET_KEY-derived key. Re-encrypt them before "
+ "dropping the old key from SECRET_KEY / SECRET_KEY_FALLBACKS."
+ )
+ )
+ else:
+ self.stdout.write(
+ self.style.SUCCESS(
+ "No rows depend on a SECRET_KEY-derived key — safe to drop the old key once it is no longer "
+ "needed in SECRET_KEY_FALLBACKS for Django session/CSRF rotation."
+ )
+ )
+ if total_plaintext or total_unreadable:
+ self.stdout.write(
+ self.style.WARNING(
+ f"{total_plaintext} plaintext and {total_unreadable} unreadable row(s) found — these do not "
+ "block rotation but should be inspected separately."
+ )
+ )
diff --git a/posthog/management/commands/test/test_audit_encrypted_field_keys.py b/posthog/management/commands/test/test_audit_encrypted_field_keys.py
new file mode 100644
index 000000000000..017b4b5d8dba
--- /dev/null
+++ b/posthog/management/commands/test/test_audit_encrypted_field_keys.py
@@ -0,0 +1,400 @@
+import json
+import base64
+from io import StringIO
+from typing import Any, cast
+
+from posthog.test.base import BaseTest
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+from django.db import connections, router
+from django.test import SimpleTestCase, override_settings
+
+from cryptography.fernet import Fernet, MultiFernet
+from cryptography.hazmat.backends import default_backend
+from cryptography.hazmat.primitives import hashes
+from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
+
+from posthog.management.commands.audit_encrypted_field_keys import (
+ CLEAN,
+ EMPTY,
+ LEGACY,
+ PLAINTEXT,
+ UNREADABLE,
+ Command,
+ _classify_leaf,
+ _decryptable,
+ _leaves,
+ _legacy_fernet,
+ _looks_like_fernet_token,
+ _salt_only_fernet,
+ classify,
+)
+from posthog.models.integration import Integration
+
+# ENCRYPTION_KEY and OTHER_KEY are used directly as Fernet keys, so they must be exactly 32 bytes.
+# SECRET and SALT_RAW only feed PBKDF2 (password / salt), so their length is irrelevant.
+SALT_RAW = "a" * 32
+SECRET = "b" * 32
+ENCRYPTION_KEY = "c" * 32
+OTHER_KEY = "d" * 32
+
+
+def _salt_fernet(raw_key: str) -> Fernet:
+ return Fernet(base64.urlsafe_b64encode(raw_key.encode("utf-8")))
+
+
+def _secret_derived_fernet(secret_key: str, salt_key: str) -> Fernet:
+ kdf = PBKDF2HMAC(
+ algorithm=hashes.SHA256(),
+ length=32,
+ salt=salt_key.encode("utf-8"),
+ iterations=100000,
+ backend=default_backend(),
+ )
+ return Fernet(base64.urlsafe_b64encode(kdf.derive(secret_key.encode("utf-8"))))
+
+
+@override_settings(
+ ENCRYPTION_SALT_KEYS=[ENCRYPTION_KEY], SECRET_KEY=SECRET, SECRET_KEY_FALLBACKS=[], SALT_KEY=[SALT_RAW]
+)
+class TestAuditClassify(SimpleTestCase):
+ def setUp(self):
+ self.salt_only = _salt_only_fernet()
+ self.legacy = _legacy_fernet()
+
+ def _enc_salt(self, plaintext="secret"):
+ return _salt_fernet(ENCRYPTION_KEY).encrypt(plaintext.encode("utf-8")).decode("utf-8")
+
+ def _enc_legacy(self, plaintext="secret"):
+ return _secret_derived_fernet(SECRET, SALT_RAW).encrypt(plaintext.encode("utf-8")).decode("utf-8")
+
+ def _enc_other(self, plaintext="secret"):
+ return _salt_fernet(OTHER_KEY).encrypt(plaintext.encode("utf-8")).decode("utf-8")
+
+ def test_scalar_token_under_encryption_salt_key_is_clean(self):
+ assert classify(self._enc_salt(), self.salt_only, self.legacy) == CLEAN
+
+ def test_scalar_token_under_secret_derived_key_is_legacy(self):
+ assert classify(self._enc_legacy(), self.salt_only, self.legacy) == LEGACY
+
+ def test_token_under_unknown_key_is_unreadable(self):
+ assert classify(self._enc_other(), self.salt_only, self.legacy) == UNREADABLE
+
+ def test_non_token_string_is_plaintext(self):
+ assert classify("not-encrypted-at-all", self.salt_only, self.legacy) == PLAINTEXT
+
+ def test_empty_and_trivial_values_are_empty(self):
+ values: list[object] = [None, "", "{}", "[]", "null", {}, []]
+ for value in values:
+ assert classify(value, self.salt_only, self.legacy) == EMPTY, value
+
+ def test_json_field_all_leaves_clean(self):
+ raw = {"a": self._enc_salt("x"), "nested": {"b": self._enc_salt("y")}, "list": [self._enc_salt("z")]}
+ assert classify(raw, self.salt_only, self.legacy) == CLEAN
+
+ def test_json_field_with_one_legacy_leaf_is_legacy(self):
+ raw = {"a": self._enc_salt("x"), "b": self._enc_legacy("y")}
+ assert classify(raw, self.salt_only, self.legacy) == LEGACY
+
+ def test_json_field_with_one_plaintext_leaf_is_plaintext(self):
+ # With no legacy/unreadable leaf, a never-encrypted leaf dominates clean ones — needs inspection
+ raw = {"a": self._enc_salt("x"), "b": "leaked-plaintext"}
+ assert classify(raw, self.salt_only, self.legacy) == PLAINTEXT
+
+ def test_json_field_legacy_leaf_beats_plaintext_leaf(self):
+ # Regression: a legacy token is stranded on rotation, so it must win over a plaintext sibling —
+ # otherwise the row would be hidden from `legacy` and safe_to_drop_secret_key could read true
+ raw = {"a": self._enc_legacy("x"), "b": "leaked-plaintext"}
+ assert classify(raw, self.salt_only, self.legacy) == LEGACY
+
+ def test_json_field_legacy_leaf_beats_unreadable_leaf(self):
+ raw = {"a": self._enc_legacy("x"), "b": self._enc_other("y")}
+ assert classify(raw, self.salt_only, self.legacy) == LEGACY
+
+ def test_json_field_unreadable_leaf_beats_plaintext_leaf(self):
+ raw = {"a": self._enc_other("x"), "b": "leaked-plaintext"}
+ assert classify(raw, self.salt_only, self.legacy) == UNREADABLE
+
+ @override_settings(SECRET_KEY="new-secret", SECRET_KEY_FALLBACKS=[SECRET], SALT_KEY=[SALT_RAW])
+ def test_secret_derived_leaf_still_legacy_via_fallback(self):
+ legacy = _legacy_fernet()
+ assert classify(self._enc_legacy(), self.salt_only, legacy) == LEGACY
+
+
+@override_settings(
+ ENCRYPTION_SALT_KEYS=[ENCRYPTION_KEY], SECRET_KEY=SECRET, SECRET_KEY_FALLBACKS=[], SALT_KEY=[SALT_RAW]
+)
+class TestAuditFieldArgument(SimpleTestCase):
+ # --field resolves against the app registry before any DB access, so these need no database
+
+ def test_unknown_field_raises_clear_error_listing_available_fields(self):
+ with self.assertRaises(CommandError) as ctx:
+ call_command("audit_encrypted_field_keys", field="nope.Nope.nope")
+ message = str(ctx.exception)
+ assert "nope.Nope.nope" in message
+ assert "did not match" in message
+ # lists real fields so the user can fix the typo instead of concluding there are none
+ assert "posthog.Integration.sensitive_config" in message
+
+
+class TestAuditFernetBuilders(SimpleTestCase):
+ @override_settings(ENCRYPTION_SALT_KEYS=[], SALT_KEY=[])
+ def test_salt_only_fernet_is_none_when_no_keys(self):
+ assert _salt_only_fernet() is None
+
+ @override_settings(SECRET_KEY=SECRET, SECRET_KEY_FALLBACKS=[], SALT_KEY=[])
+ def test_legacy_fernet_is_none_when_no_salt_keys(self):
+ assert _legacy_fernet() is None
+
+ @override_settings(SECRET_KEY=SECRET, SECRET_KEY_FALLBACKS=["fb1", "fb2"], SALT_KEY=[SALT_RAW, "salt2"])
+ def test_legacy_fernet_covers_secret_key_and_all_fallbacks(self):
+ legacy = _legacy_fernet()
+ assert isinstance(legacy, MultiFernet)
+ # 3 secret keys (secret + 2 fallbacks) x 2 salt keys = 6 derived keys; each decrypts its own ciphertext
+ token = _secret_derived_fernet("fb2", "salt2").encrypt(b"x").decode("utf-8")
+ assert legacy.decrypt(token.encode("utf-8")) == b"x"
+
+
+@override_settings(
+ ENCRYPTION_SALT_KEYS=[ENCRYPTION_KEY], SECRET_KEY=SECRET, SECRET_KEY_FALLBACKS=[], SALT_KEY=[SALT_RAW]
+)
+class TestAuditLeafHelpers(SimpleTestCase):
+ # The leaf-walking and token-probing helpers underneath classify(), tested in isolation.
+
+ def setUp(self):
+ self.salt_only = _salt_only_fernet()
+ self.legacy = _legacy_fernet()
+ self.clean_token = _salt_fernet(ENCRYPTION_KEY).encrypt(b"secret").decode("utf-8")
+ self.legacy_token = _secret_derived_fernet(SECRET, SALT_RAW).encrypt(b"secret").decode("utf-8")
+ self.other_token = _salt_fernet(OTHER_KEY).encrypt(b"secret").decode("utf-8")
+
+ def test_leaves_flattens_every_nesting_into_only_strings(self):
+ cases: list[tuple[object, list[str]]] = [
+ ("token", ["token"]), # scalar field stores a single token
+ ({"a": "t1", "b": "t2"}, ["t1", "t2"]), # jsonb object — one token per value
+ (["t1", "t2"], ["t1", "t2"]),
+ ({"a": {"b": "t"}, "c": ["d", "e"]}, ["t", "d", "e"]), # arbitrarily nested
+ ({"a": "t", "b": 5, "c": None}, ["t"]), # non-string leaves carry no token, so dropped
+ (123, []),
+ (None, []),
+ ({}, []),
+ ([], []),
+ ]
+ for value, expected in cases:
+ assert _leaves(value) == expected, value
+
+ def test_looks_like_fernet_token_only_for_real_tokens(self):
+ too_short = base64.urlsafe_b64encode(b"short").decode("utf-8")
+ wrong_version_byte = base64.urlsafe_b64encode(b"\x00" + b"x" * 80).decode("utf-8")
+ cases: list[tuple[str, bool]] = [
+ (self.clean_token, True),
+ (self.legacy_token, True),
+ (self.other_token, True), # token-shaped even when no configured key decrypts it
+ ("not-base64-at-all!!", False), # invalid base64 padding
+ ("plaintext", False),
+ (too_short, False), # decodes to < 73 bytes
+ (wrong_version_byte, False), # long enough, but first byte is not Fernet's 0x80
+ ]
+ for value, expected in cases:
+ assert _looks_like_fernet_token(value) is expected, value
+
+ def test_decryptable_is_false_without_a_fernet(self):
+ assert _decryptable(None, self.clean_token) is False
+
+ def test_decryptable_matches_only_the_right_key(self):
+ assert _decryptable(self.salt_only, self.clean_token) is True
+ assert _decryptable(self.salt_only, self.legacy_token) is False
+ assert _decryptable(self.legacy, self.legacy_token) is True
+ assert _decryptable(self.salt_only, "not-even-a-token") is False
+
+ def test_classify_leaf_maps_each_token_to_its_bucket(self):
+ cases: list[tuple[str, str]] = [
+ (self.clean_token, CLEAN),
+ (self.legacy_token, LEGACY),
+ (self.other_token, UNREADABLE),
+ ("leaked-plaintext", PLAINTEXT),
+ ]
+ for leaf, expected in cases:
+ assert _classify_leaf(leaf, self.salt_only, self.legacy) == expected, leaf
+
+
+class TestAuditCoerceRaw(SimpleTestCase):
+ # A raw cursor returns jsonb as a JSON string under Django's psycopg config; _coerce_raw decodes it
+ # so per-leaf tokens are walked individually instead of the whole document reading as one opaque leaf.
+
+ def test_jsonb_string_is_parsed_only_for_json_columns(self):
+ # is_json_column=True → parse so siblings become distinct leaves
+ assert Command._coerce_raw('{"a": "tok1", "b": "tok2"}', True) == {"a": "tok1", "b": "tok2"}
+ # is_json_column=False → a text column already holds the single token, leave it untouched
+ assert Command._coerce_raw("a-single-token", False) == "a-single-token"
+
+ def test_passthrough_for_non_string_and_unparseable_values(self):
+ assert Command._coerce_raw(None, True) is None # NULL jsonb
+ assert Command._coerce_raw({"a": "tok"}, True) == {"a": "tok"} # already-parsed dict survives
+ assert Command._coerce_raw("not-json", True) == "not-json" # invalid JSON falls through unchanged
+
+
+@override_settings(
+ ENCRYPTION_SALT_KEYS=[ENCRYPTION_KEY], SECRET_KEY=SECRET, SECRET_KEY_FALLBACKS=[], SALT_KEY=[SALT_RAW]
+)
+class TestAuditCommandEndToEnd(BaseTest):
+ # Drives the whole Command against real Integration.sensitive_config rows. Ciphertext is injected
+ # via raw SQL so each row lands in a known classification — the ORM would re-encrypt under the
+ # current salt key, collapsing exactly the legacy-vs-clean distinction the audit measures.
+
+ FIELD = "posthog.Integration.sensitive_config"
+
+ def setUp(self):
+ super().setUp()
+ self._next_suffix = 0
+
+ def _make_integration(self, raw_value: object) -> int:
+ self._next_suffix += 1
+ integration = Integration.objects.create(
+ team=self.team, kind="slack", integration_id=f"audit-test-{self._next_suffix}", errors=""
+ )
+ connection = connections[router.db_for_write(Integration)]
+ quote = connection.ops.quote_name
+ table = quote(Integration._meta.db_table)
+ # cast to Any: sensitive_config is wrapped in field_access_control, so the django-stubs
+ # plugin doesn't see it as a model field and rejects the get_field string literal.
+ column = quote(cast(Any, Integration)._meta.get_field("sensitive_config").column)
+ pk_column = quote(Integration._meta.pk.column)
+ with connection.cursor() as cursor:
+ cursor.execute(
+ f"UPDATE {table} SET {column} = %s::jsonb WHERE {pk_column} = %s",
+ [json.dumps(raw_value), integration.pk],
+ )
+ return integration.pk
+
+ def _clean(self, plaintext="secret"):
+ return _salt_fernet(ENCRYPTION_KEY).encrypt(plaintext.encode("utf-8")).decode("utf-8")
+
+ def _legacy(self, plaintext="secret"):
+ return _secret_derived_fernet(SECRET, SALT_RAW).encrypt(plaintext.encode("utf-8")).decode("utf-8")
+
+ def _other(self, plaintext="secret"):
+ return _salt_fernet(OTHER_KEY).encrypt(plaintext.encode("utf-8")).decode("utf-8")
+
+ def _run_json(self, **options) -> dict:
+ out = StringIO()
+ call_command("audit_encrypted_field_keys", field=self.FIELD, json=True, stdout=out, **options)
+ payload = json.loads(out.getvalue())
+ assert len(payload["fields"]) == 1, "--field should restrict the run to a single field"
+ return payload
+
+ def test_mixed_rows_are_counted_and_legacy_blocks_rotation(self):
+ legacy_pk = self._make_integration({"k": self._legacy()})
+ self._make_integration({"k": self._clean()})
+ self._make_integration({"k": self._other()})
+ self._make_integration({"k": "leaked-plaintext"})
+ self._make_integration({}) # empty jsonb — no leaf to classify
+
+ payload = self._run_json()
+ report = payload["fields"][0]
+
+ assert report["scanned"] == 5
+ assert report["counts"] == {CLEAN: 1, LEGACY: 1, PLAINTEXT: 1, UNREADABLE: 1, EMPTY: 1}
+ assert payload["safe_to_drop_secret_key"] is False
+ assert str(legacy_pk) in report["samples"][LEGACY]
+ assert report["error"] is None
+
+ def test_json_field_is_walked_per_leaf_through_the_db(self):
+ # Regression: a jsonb column comes back from the cursor as a JSON string. Without parsing it, the
+ # whole document reads as one non-token leaf (plaintext) and a legacy leaf inside would be missed,
+ # letting safe_to_drop_secret_key report true while stranded JSON tokens still exist.
+ self._make_integration({"a": self._clean(), "b": self._legacy(), "nested": {"c": self._clean()}})
+ self._make_integration({"a": self._clean(), "nested": {"c": self._clean()}})
+
+ payload = self._run_json()
+ report = payload["fields"][0]
+
+ assert report["counts"] == {CLEAN: 1, LEGACY: 1, PLAINTEXT: 0, UNREADABLE: 0, EMPTY: 0}
+ assert payload["safe_to_drop_secret_key"] is False
+
+ def test_clean_and_empty_only_is_safe_to_drop(self):
+ self._make_integration({"k": self._clean()})
+ self._make_integration({})
+
+ payload = self._run_json()
+
+ assert payload["safe_to_drop_secret_key"] is True
+ assert payload["fields"][0]["counts"][LEGACY] == 0
+
+ def test_plaintext_and_unreadable_do_not_block_rotation(self):
+ # Only LEGACY strands rows on rotation; plaintext / unreadable are flagged but still safe to drop
+ self._make_integration({"k": self._clean()})
+ self._make_integration({"k": "leaked-plaintext"})
+ self._make_integration({"k": self._other()})
+
+ payload = self._run_json()
+ report = payload["fields"][0]
+
+ assert payload["safe_to_drop_secret_key"] is True
+ assert report["counts"][PLAINTEXT] == 1
+ assert report["counts"][UNREADABLE] == 1
+
+ def test_limit_caps_rows_scanned(self):
+ for _ in range(4):
+ self._make_integration({"k": self._clean()})
+
+ report = self._run_json(limit=2)["fields"][0]
+
+ assert report["scanned"] == 2
+
+ def test_small_batch_size_paginates_across_every_row(self):
+ for _ in range(3):
+ self._make_integration({"k": self._clean()})
+
+ # batch_size=1 forces the keyset-pagination WHERE pk > %s branch on every row
+ report = self._run_json(batch_size=1)["fields"][0]
+
+ assert report["scanned"] == 3
+ assert report["counts"][CLEAN] == 3
+
+ def test_samples_option_caps_recorded_pks(self):
+ for _ in range(3):
+ self._make_integration({"k": self._legacy()})
+
+ report = self._run_json(samples=2)["fields"][0]
+
+ assert report["counts"][LEGACY] == 3
+ assert len(report["samples"][LEGACY]) == 2
+
+ def test_console_output_summarizes_and_warns_on_legacy(self):
+ self._make_integration({"k": self._legacy()})
+ self._make_integration({"k": self._clean()})
+
+ out = StringIO()
+ call_command("audit_encrypted_field_keys", field=self.FIELD, stdout=out, no_color=True)
+ text = out.getvalue()
+
+ assert self.FIELD in text
+ assert "legacy=1" in text
+ assert "clean=1" in text
+ assert "still depend on a SECRET_KEY-derived key" in text
+
+ @override_settings(
+ ENCRYPTION_SALT_KEYS=[ENCRYPTION_KEY],
+ SECRET_KEY="rotated-secret",
+ SECRET_KEY_FALLBACKS=[SECRET],
+ SALT_KEY=[SALT_RAW],
+ )
+ def test_row_under_rotated_secret_key_stays_legacy_via_fallback(self):
+ # The crux of the feature: after SECRET_KEY rotates (old key moved to fallbacks), a row encrypted
+ # with the old key must still classify as LEGACY — not UNREADABLE — so rotation isn't reported safe
+ self._make_integration({"k": self._legacy()})
+
+ report = self._run_json()["fields"][0]
+
+ assert report["counts"][LEGACY] == 1
+ assert report["counts"][UNREADABLE] == 0
+
+
+class TestAuditCommandErrors(SimpleTestCase):
+ @override_settings(ENCRYPTION_SALT_KEYS=[], SALT_KEY=[SALT_RAW])
+ def test_empty_encryption_salt_keys_raises_before_any_db_access(self):
+ with self.assertRaises(CommandError) as ctx:
+ call_command("audit_encrypted_field_keys")
+ assert "ENCRYPTION_SALT_KEYS is empty" in str(ctx.exception)
diff --git a/posthog/settings/access.py b/posthog/settings/access.py
index dbeff32583b4..a82cabd133b7 100644
--- a/posthog/settings/access.py
+++ b/posthog/settings/access.py
@@ -102,7 +102,8 @@ SANDBOX_JWT_PRIVATE_KEY_SECONDARY: str | None = os.getenv("SANDBOX_JWT_PRIVATE_K
# These are legacy values only kept around for backwards compatibility with self hosted versions
SALT_KEY = get_list(os.getenv("SALT_KEY", "0123456789abcdefghijklmnopqrstuvwxyz"))
-# We provide a default as it is needed for hobby deployments
+# We provide a default as it is needed for hobby deployments. Each entry must be exactly 32 bytes
+# (used directly as a Fernet key) — enforced by check_encryption_salt_keys in encrypted_fields.py.
ENCRYPTION_SALT_KEYS = get_list(os.getenv("ENCRYPTION_SALT_KEYS", "00beef0000beef0000beef0000beef00"))
INTERNAL_IPS = ["127.0.0.1", "172.18.0.1"] # Docker IP