: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(flags): use a dedicated encryption key for flag payloads (#61233)
Phil Haack992fc625a300
diff --git a/posthog/helpers/encrypted_flag_payloads.py b/posthog/helpers/encrypted_flag_payloads.pydeleted file mode 100644index 4603bfe3ebb1..000000000000--- a/posthog/helpers/encrypted_flag_payloads.py+++ /dev/null@@ -1,50 +0,0 @@-from django.conf import settings--from posthog.auth import PersonalAPIKeyAuthentication-from posthog.temporal.common.codec import EncryptionCodec--REDACTED_PAYLOAD_VALUE = '"********* (encrypted)"'---def get_decrypted_flag_payloads_protected(request, encrypted_payloads: dict) -> dict:- # We only decode encrypted flag payloads if the request is made with a personal API key- is_personal_api_request = isinstance(request.successful_authenticator, PersonalAPIKeyAuthentication)- return get_decrypted_flag_payloads(encrypted_payloads, should_decrypt=is_personal_api_request)---def get_decrypted_flag_payloads(encrypted_payloads: dict, should_decrypt: bool) -> dict:- decrypted_payloads = {}- for key, value in (encrypted_payloads or {}).items():- decrypted_payloads[key] = get_decrypted_flag_payload(value, should_decrypt=should_decrypt)-- return decrypted_payloads---def get_decrypted_flag_payload(encrypted_payload: str | object, should_decrypt: bool) -> str:- codec = EncryptionCodec.from_settings(settings)- return (- codec.decrypt(str(encrypted_payload).encode("utf-8")).decode("utf-8")- if should_decrypt- else REDACTED_PAYLOAD_VALUE- )---def encrypt_flag_payloads(validated_data: dict):- if not validated_data.get("has_encrypted_payloads", False):- return-- if "filters" not in validated_data:- return-- if "payloads" not in validated_data["filters"]:- return-- payloads = validated_data["filters"]["payloads"]-- codec = EncryptionCodec.from_settings(settings)-- for key, value in payloads.items():- try:- payloads[key] = codec.encrypt(value.encode("utf-8")).decode("utf-8")- except Exception as e:- raise ValueError(f"Failed to encrypt payload for key {key}") from ediff --git a/posthog/management/commands/reencrypt_flag_payloads.py b/posthog/management/commands/reencrypt_flag_payloads.pynew file mode 100644index 000000000000..7447de37e7ee--- /dev/null+++ b/posthog/management/commands/reencrypt_flag_payloads.py@@ -0,0 +1,104 @@+from django.core.management.base import BaseCommand+from django.db import transaction+from django.db.models import QuerySet++import structlog+from cryptography.fernet import InvalidToken++from products.feature_flags.backend.encrypted_flag_payloads import FlagPayloadCodec, flag_payload_codec+from products.feature_flags.backend.models.feature_flag import FeatureFlag++logger = structlog.get_logger(__name__)+++class Command(BaseCommand):+ help = (+ "Re-encrypt remote-config feature flag payloads with the primary key in FLAGS_SECRET_KEYS. "+ "Run after prepending a new key to FLAGS_SECRET_KEYS (keeping the old key in the list) "+ "and before dropping the old key from FLAGS_SECRET_KEYS. Safe to re-run; idempotent."+ )++ def add_arguments(self, parser):+ parser.add_argument("--team-id", default=None, type=int, help="Limit to a specific team ID")+ parser.add_argument("--limit", default=None, type=int, help="Process at most this many flags")+ parser.add_argument("--batch-size", default=100, type=int, help="DB iterator chunk size")+ parser.add_argument("--live-run", action="store_true", help="Apply changes (default is dry-run)")++ def handle(self, *args, **options) -> None:+ live_run: bool = options["live_run"]+ team_id: int | None = options["team_id"]+ limit: int | None = options["limit"]+ batch_size: int = options["batch_size"]++ # rotate() decrypts with any key in FLAGS_SECRET_KEYS, then re-encrypts+ # with the primary (first) key — exactly the re-encryption we need.+ codec = flag_payload_codec()++ mode = "LIVE RUN" if live_run else "DRY RUN"+ self.stdout.write(f"Starting reencrypt_flag_payloads ({mode})")++ scanned = updated = skipped = 0+ for flag in self._get_flags(team_id, limit).iterator(chunk_size=batch_size):+ scanned += 1+ try:+ changed = self._reencrypt(flag.pk, codec) if live_run else self._needs_reencrypt(flag, codec)+ except InvalidToken as e:+ # A payload no key can decrypt (corrupt, or already-plaintext). Skip+ # the whole flag rather than write a half-rotated payloads dict.+ # Narrow to InvalidToken so DB and programming errors propagate+ # instead of being silently counted as skips on a "successful" run.+ skipped += 1+ logger.warning(+ "reencrypt_flag_payloads.skip", flag_id=flag.id, team_id=flag.team_id, error=str(e), exc_info=True+ )+ self.stderr.write(f" ! skipped flag {flag.id} (team {flag.team_id}): {e}")+ continue+ if changed:+ updated += 1++ verb = "re-encrypted" if live_run else "would re-encrypt"+ self.stdout.write(f"Done. scanned={scanned} {verb}={updated} skipped={skipped}")++ def _needs_reencrypt(self, flag: FeatureFlag, codec: FlagPayloadCodec) -> bool:+ """Dry-run check on the streamed snapshot: would this flag's payloads be rotated?"""+ payloads = (flag.filters or {}).get("payloads") or {}+ return self._rotate_payloads(payloads, codec) is not None++ def _reencrypt(self, flag_pk: int, codec: FlagPayloadCodec) -> bool:+ """Rotate one flag's payloads under a row lock, returning True if anything changed.++ Re-read ``filters`` inside the lock so we merge the rotation into the current+ value rather than a stale streamed snapshot — otherwise a concurrent edit to+ other filter fields between the scan and the write would be silently lost.+ """+ with transaction.atomic():+ flag = FeatureFlag.objects.select_for_update().only("id", "filters").get(pk=flag_pk)+ filters = flag.filters or {}+ rotated = self._rotate_payloads(filters.get("payloads") or {}, codec)+ if rotated is None:+ return False+ # update() rather than save(): plaintext is unchanged, so we want no+ # activity-log entry and no cache churn (these flags are excluded from+ # the flags cache and the /remote_config endpoint reads live from the DB).+ FeatureFlag.objects.filter(pk=flag_pk).update(filters={**filters, "payloads": rotated})+ return True++ def _rotate_payloads(self, payloads: dict, codec: FlagPayloadCodec) -> dict | None:+ """Return rotated payloads, or None when there is nothing to do.++ None means every payload already decrypts on the primary key, so rotating+ would only churn ciphertext without advancing the migration. Raises+ InvalidToken if a payload cannot be decrypted by any key (corrupt or+ already-plaintext).+ """+ if not payloads or all(codec.is_encrypted_with_primary(v.encode("utf-8")) for v in payloads.values()):+ return None+ return {key: codec.rotate(value.encode("utf-8")).decode("utf-8") for key, value in payloads.items()}++ def _get_flags(self, team_id: int | None, limit: int | None) -> QuerySet[FeatureFlag]:+ flags = FeatureFlag.objects.filter(has_encrypted_payloads=True).only("id", "team_id", "filters").order_by("id")+ if team_id is not None:+ flags = flags.filter(team_id=team_id)+ if limit is not None:+ flags = flags[:limit]+ return flagsdiff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.pyindex b148a19772c3..6c6f10c0a7b2 100644--- a/posthog/settings/feature_flags.py+++ b/posthog/settings/feature_flags.py@@ -2,12 +2,23 @@ import osimport jsonfrom contextlib import suppress+from posthog.settings.access import SECRET_KEYfrom posthog.settings.utils import get_from_env, get_list# Used mostly by the hobby install to have some feature flags enabled by default# NOTE: This only affects the frontend, the same FFs will still be considered disabled on the backendPERSISTED_FEATURE_FLAGS = get_list(os.getenv("PERSISTED_FEATURE_FLAGS", ""))+# Encryption keys for remote-config feature flag payloads, kept separate from+# Temporal's keys (posthog/settings/temporal.py) so the two rotate independently.+# An ordered list: the first key encrypts new payloads, every key can decrypt. That+# is what lets us rotate without a hard cutover: prepend a new key, re-encrypt existing+# payloads (manage.py reencrypt_flag_payloads), then drop the old key. Defaults to+# [SECRET_KEY] so self-hosted installs, which encrypt flag payloads with SECRET_KEY,+# keep working with no configuration. An empty or unset value floors to [SECRET_KEY]+# so a key is always present.+FLAGS_SECRET_KEYS: list[str] = get_list(os.getenv("FLAGS_SECRET_KEYS", "")) or [SECRET_KEY]+# Per-team local evaluation rate limits, e.g. {"123": "1200/minute", "456": "2400/hour"}LOCAL_EVAL_RATE_LIMITS: dict[int, str] = {}with suppress(Exception):diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex eb4c60c272ed..72f40f097247 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -53,11 +53,6 @@ from posthog.event_usage import report_user_actionfrom posthog.exceptions import Conflictfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.dashboard_templates import add_enriched_insights_to_feature_flag_dashboard-from posthog.helpers.encrypted_flag_payloads import (- REDACTED_PAYLOAD_VALUE,- encrypt_flag_payloads,- get_decrypted_flag_payloads_protected,-)from posthog.models import Teamfrom posthog.models.activity_logging.activity_log import Detail, changes_between, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import ActivityLogPaginatedResponseSerializer, activity_page_response@@ -83,6 +78,11 @@ from posthog.views import format_bytesfrom products.dashboards.backend.api.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.encrypted_flag_payloads import (+ REDACTED_PAYLOAD_VALUE,+ encrypt_flag_payloads,+ get_decrypted_flag_payloads_protected,+)from products.feature_flags.backend.flag_analytics import increment_request_countfrom products.feature_flags.backend.flag_status import FeatureFlagStatusCheckerfrom products.feature_flags.backend.local_evaluation import (diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.pyindex ae6fd857bc23..3be988bc1f78 100644--- a/products/feature_flags/backend/api/organization_feature_flag.py+++ b/products/feature_flags/backend/api/organization_feature_flag.py@@ -12,13 +12,13 @@ from posthog.api.documentation import _FallbackSerializer, extend_schemafrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import action-from posthog.helpers.encrypted_flag_payloads import get_decrypted_flag_payloadsfrom posthog.models import Teamfrom posthog.models.cohort import Cohort, CohortOrEmptyfrom posthog.models.filters.filter import Filterfrom posthog.user_permissions import UserPermissionsfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.encrypted_flag_payloads import get_decrypted_flag_payloadsfrom products.feature_flags.backend.flag_analytics import get_cached_evaluations_7d_by_teamfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.scheduled_change import ScheduledChangediff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 70c49b1c8e39..28d3423a2249 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -26,7 +26,6 @@ from rest_framework.relations import ManyRelatedFieldfrom posthog import redisfrom posthog.api.cohort import get_cohort_actors_for_feature_flagfrom posthog.constants import AvailableFeature-from posthog.helpers.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE, get_decrypted_flag_payloadfrom posthog.models import GroupTypeMapping, TaggedItem, Userfrom posthog.models.cohort import Cohortfrom posthog.models.cohort.cohort import CohortType@@ -44,6 +43,7 @@ from products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer, extract_etag_from_header+from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE, get_decrypted_flag_payloadfrom products.feature_flags.backend.flag_status import FeatureFlagStatusfrom products.feature_flags.backend.models.feature_flag import (FeatureFlag,diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.pyindex fc14e806b38e..de559034677b 100644--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py@@ -884,7 +884,7 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):def test_copy_encrypted_payloads_flag(self):"""Test that copying a flag with encrypted payloads decrypts them before copying."""- from posthog.helpers.encrypted_flag_payloads import encrypt_flag_payloads+ from products.feature_flags.backend.encrypted_flag_payloads import encrypt_flag_payloadsurl = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"target_project = self.team_2@@ -927,14 +927,17 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):self.assertTrue(copied_flag.has_encrypted_payloads)# Verify the encrypted payload can be decrypted back to the original value- from posthog.helpers.encrypted_flag_payloads import get_decrypted_flag_payload+ from products.feature_flags.backend.encrypted_flag_payloads import get_decrypted_flag_payloaddecrypted_payload = get_decrypted_flag_payload(copied_flag.filters["payloads"]["true"], should_decrypt=True)self.assertEqual(decrypted_payload, '{"key": "secret_value"}')def test_copy_encrypted_payloads_flag_to_multiple_projects(self):"""Test that copying a flag with encrypted payloads to multiple projects works correctly."""- from posthog.helpers.encrypted_flag_payloads import encrypt_flag_payloads, get_decrypted_flag_payload+ from products.feature_flags.backend.encrypted_flag_payloads import (+ encrypt_flag_payloads,+ get_decrypted_flag_payload,+ )url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"diff --git a/products/feature_flags/backend/encrypted_flag_payloads.py b/products/feature_flags/backend/encrypted_flag_payloads.pynew file mode 100644index 000000000000..abced9bcd662--- /dev/null+++ b/products/feature_flags/backend/encrypted_flag_payloads.py@@ -0,0 +1,145 @@+import base64+from collections.abc import Iterable++from django.conf import settings++from cryptography.fernet import Fernet, InvalidToken, MultiFernet++from posthog.auth import PersonalAPIKeyAuthentication++REDACTED_PAYLOAD_VALUE = '"********* (encrypted)"'+++def _prepare_key(key: str | bytes) -> bytes:+ """Derive a Fernet key from raw key material.++ Pads (left, with NUL bytes) or truncates the input to the 32 bytes Fernet requires,+ then URL-safe base64-encodes it. The input is raw key material, not an already-encoded key.+ """+ key_bytes = key.encode() if isinstance(key, str) else key+ return base64.urlsafe_b64encode((b"\0" * max(32 - len(key_bytes), 0) + key_bytes)[:32])+++class FlagPayloadCodec:+ """Symmetric Fernet encryption for feature flag payloads, with key rotation.++ A thin wrapper over ``MultiFernet``: the primary key encrypts new payloads while+ fallback keys decrypt older ones, so the keys in ``FLAGS_SECRET_KEYS`` can rotate+ without a hard cutover. Deliberately independent of Temporal's ``EncryptionCodec`` —+ flag payloads have their own key lifecycle (``FLAGS_SECRET_KEYS``) and need none of+ the Temporal ``PayloadCodec`` machinery (async ``encode``/``decode``, protobuf+ ``Payload``).+ """++ def __init__(self, primary: Fernet, fallbacks: Iterable[Fernet]) -> None:+ self.primary = primary+ self.fernet = MultiFernet([primary, *fallbacks])++ @classmethod+ def from_keys(+ cls,+ key: str | bytes,+ fallback_keys: Iterable[str | bytes],+ *,+ require_min_length: bool = True,+ ) -> "FlagPayloadCodec":+ """Build a codec from raw key material.++ Keys are padded or truncated to 32 bytes and base64-encoded as Fernet requires.+ The first key encrypts new payloads; fallback keys are only tried when decryption+ with the primary key fails — keeping old keys as fallbacks is what makes key+ rotation possible without a hard cutover.++ Args:+ key: The preferred encryption key.+ fallback_keys: Additional keys tried only when decrypting with key fails.+ require_min_length: When True, raise if any key is shorter than 32 bytes.+ Disable only in TEST or DEBUG, where short keys are padded.++ Raises:+ ValueError: If require_min_length is True and any key is under 32 bytes.+ """+ fallbacks = list(fallback_keys)+ if require_min_length and any(len(k if isinstance(k, bytes) else k.encode()) < 32 for k in (key, *fallbacks)):+ raise ValueError("Keys must be at least 32 bytes")+ return cls(Fernet(_prepare_key(key)), [Fernet(_prepare_key(k)) for k in fallbacks])++ def encrypt(self, data: bytes) -> bytes:+ return self.fernet.encrypt(data)++ def decrypt(self, data: bytes) -> bytes:+ return self.fernet.decrypt(data)++ def rotate(self, data: bytes) -> bytes:+ """Re-encrypt a token onto the primary key, decrypting it with any known key first."""+ return self.fernet.rotate(data)++ def is_encrypted_with_primary(self, data: bytes) -> bool:+ """Return True if data decrypts with the primary key alone (no fallback needed).++ Lets callers skip re-encrypting tokens already on the current key:+ ``MultiFernet.rotate`` emits fresh ciphertext regardless of which key a token+ is on, so without this check a re-encryption pass rewrites every row on rerun.+ """+ try:+ self.primary.decrypt(data)+ except InvalidToken:+ return False+ return True+++def flag_payload_codec() -> FlagPayloadCodec:+ # FLAGS_SECRET_KEYS is ordered and always non-empty: the first key encrypts,+ # the rest are decrypt-only fallbacks.+ keys = settings.FLAGS_SECRET_KEYS+ return FlagPayloadCodec.from_keys(+ keys[0],+ keys[1:],+ require_min_length=not settings.TEST and not settings.DEBUG,+ )+++def get_decrypted_flag_payloads_protected(request, encrypted_payloads: dict) -> dict:+ # We only decode encrypted flag payloads if the request is made with a personal API key+ is_personal_api_request = isinstance(request.successful_authenticator, PersonalAPIKeyAuthentication)+ return get_decrypted_flag_payloads(encrypted_payloads, should_decrypt=is_personal_api_request)+++def get_decrypted_flag_payloads(encrypted_payloads: dict, should_decrypt: bool) -> dict:+ # Build the codec once and share it across every payload rather than rebuilding+ # it per entry. When redacting we never decrypt, so skip building it at all.+ codec = flag_payload_codec() if should_decrypt else None+ return {+ key: get_decrypted_flag_payload(value, should_decrypt=should_decrypt, codec=codec)+ for key, value in (encrypted_payloads or {}).items()+ }+++def get_decrypted_flag_payload(+ encrypted_payload: str | object, should_decrypt: bool, codec: FlagPayloadCodec | None = None+) -> str:+ if not should_decrypt:+ return REDACTED_PAYLOAD_VALUE+ codec = codec or flag_payload_codec()+ return codec.decrypt(str(encrypted_payload).encode("utf-8")).decode("utf-8")+++def encrypt_flag_payloads(validated_data: dict):+ if not validated_data.get("has_encrypted_payloads", False):+ return++ if "filters" not in validated_data:+ return++ if "payloads" not in validated_data["filters"]:+ return++ payloads = validated_data["filters"]["payloads"]++ codec = flag_payload_codec()++ for key, value in payloads.items():+ try:+ payloads[key] = codec.encrypt(value.encode("utf-8")).decode("utf-8")+ except Exception as e:+ raise ValueError(f"Failed to encrypt payload for key {key}") from ediff --git a/products/feature_flags/backend/flag_matching.py b/products/feature_flags/backend/flag_matching.pyindex b3064e9047ba..90e86d0c3683 100644--- a/products/feature_flags/backend/flag_matching.py+++ b/products/feature_flags/backend/flag_matching.py@@ -23,7 +23,6 @@ from django.db.models.query import QuerySetimport structlogfrom posthog.database_healthcheck import DATABASE_FOR_FLAG_MATCHING-from posthog.helpers.encrypted_flag_payloads import get_decrypted_flag_payloadfrom posthog.models.cohort import Cohort, CohortOrEmptyfrom posthog.models.filters import Filterfrom posthog.models.filters.mixins.utils import cached_property@@ -35,6 +34,8 @@ from posthog.models.utils import execute_with_timeoutfrom posthog.person_db_router import PERSONS_DB_FOR_READ, PERSONS_DB_FOR_WRITEfrom posthog.queries.base import match_property, properties_to_Q, sanitize_property_key+from products.feature_flags.backend.encrypted_flag_payloads import get_decrypted_flag_payload+from .models.feature_flag import FeatureFlag, FeatureFlagHashKeyOverridelogger = structlog.get_logger(__name__)diff --git a/products/feature_flags/backend/test/test_encrypted_flag_payloads.py b/products/feature_flags/backend/test/test_encrypted_flag_payloads.pynew file mode 100644index 000000000000..5c15c10ca611--- /dev/null+++ b/products/feature_flags/backend/test/test_encrypted_flag_payloads.py@@ -0,0 +1,61 @@+import pytest++from cryptography.fernet import InvalidToken++from products.feature_flags.backend.encrypted_flag_payloads import FlagPayloadCodec+++def test_from_keys_round_trip():+ """from_keys produces an encryptor that round-trips and encrypts with the primary key only."""+ codec = FlagPayloadCodec.from_keys(b"a" * 32, [b"b" * 32])+ payload = b"flag-payload"++ token = codec.encrypt(payload)++ assert codec.decrypt(token) == payload+ # Encryption uses the primary key only: an encryptor holding just the primary key decrypts+ # the token, while one holding only the fallback key cannot.+ assert FlagPayloadCodec.from_keys(b"a" * 32, []).decrypt(token) == payload+ with pytest.raises(InvalidToken):+ FlagPayloadCodec.from_keys(b"b" * 32, []).decrypt(token)+++def test_from_keys_decrypts_with_fallback_then_rotates():+ """A token from an old key decrypts via fallback, and rotate() re-encrypts under the new primary key.++ This is the rotation path reencrypt_flag_payloads relies on: keep the old key as a+ fallback, rotate every payload, then the new key alone suffices and the old key can be dropped.+ """+ old = FlagPayloadCodec.from_keys(b"o" * 32, [])+ rotated = FlagPayloadCodec.from_keys(b"n" * 32, [b"o" * 32])++ token = old.encrypt(b"flag-payload")+ assert rotated.decrypt(token) == b"flag-payload"++ new_token = rotated.rotate(token)++ new_only = FlagPayloadCodec.from_keys(b"n" * 32, [])+ assert new_only.decrypt(new_token) == b"flag-payload"+ with pytest.raises(InvalidToken):+ FlagPayloadCodec.from_keys(b"o" * 32, []).decrypt(new_token)+++def test_is_encrypted_with_primary():+ """is_encrypted_with_primary is True only when the token decrypts on the primary key alone."""+ rotated = FlagPayloadCodec.from_keys(b"n" * 32, [b"o" * 32])+ old = FlagPayloadCodec.from_keys(b"o" * 32, [])++ on_primary = rotated.encrypt(b"flag-payload")+ on_fallback = old.encrypt(b"flag-payload")++ assert rotated.is_encrypted_with_primary(on_primary) is True+ assert rotated.is_encrypted_with_primary(on_fallback) is False++[email protected]("require_min_length,raises", [(True, True), (False, False)])+def test_from_keys_min_length_enforcement(require_min_length: bool, raises: bool):+ if raises:+ with pytest.raises(ValueError):+ FlagPayloadCodec.from_keys(b"short", [], require_min_length=require_min_length)+ else:+ FlagPayloadCodec.from_keys(b"short", [], require_min_length=require_min_length)diff --git a/products/feature_flags/backend/test/test_reencrypt_flag_payloads.py b/products/feature_flags/backend/test/test_reencrypt_flag_payloads.pynew file mode 100644index 000000000000..4f0c12683016--- /dev/null+++ b/products/feature_flags/backend/test/test_reencrypt_flag_payloads.py@@ -0,0 +1,115 @@+from posthog.test.base import BaseTest++from django.core.management import call_command+from django.test import override_settings++from cryptography.fernet import InvalidToken++from posthog.management.commands.reencrypt_flag_payloads import Command++from products.feature_flags.backend.encrypted_flag_payloads import (+ FlagPayloadCodec,+ flag_payload_codec,+ get_decrypted_flag_payload,+)+from products.feature_flags.backend.models.feature_flag import FeatureFlag++OLD_KEY = "old-flags-secret-key-0123456789abcdefghij"+NEW_KEY = "new-flags-secret-key-0123456789abcdefghij"+PAYLOAD = '"super-secret-config"'+++def _codec(key: str) -> FlagPayloadCodec:+ return FlagPayloadCodec.from_keys(key, [], require_min_length=False)+++class TestReencryptFlagPayloads(BaseTest):+ def _make_flag(self, key: str, encrypt_with: str, payload: str = PAYLOAD) -> FeatureFlag:+ token = _codec(encrypt_with).encrypt(payload.encode("utf-8")).decode("utf-8")+ return FeatureFlag.objects.create(+ team=self.team,+ key=key,+ created_by=self.user,+ is_remote_configuration=True,+ has_encrypted_payloads=True,+ filters={"groups": [], "payloads": {"true": token}},+ )++ def _run(self, *args: str) -> None:+ call_command("reencrypt_flag_payloads", "--team-id", str(self.team.id), *args)++ def test_live_run_reencrypts_with_new_main_key(self):+ flag = self._make_flag("rc-flag", encrypt_with=OLD_KEY)++ with override_settings(FLAGS_SECRET_KEYS=[NEW_KEY, OLD_KEY]):+ self._run("--live-run")++ flag.refresh_from_db()+ new_token = flag.filters["payloads"]["true"].encode("utf-8")++ # The new key alone now decrypts it, so the old key can be safely dropped.+ assert _codec(NEW_KEY).decrypt(new_token).decode("utf-8") == PAYLOAD+ with self.assertRaises(InvalidToken):+ _codec(OLD_KEY).decrypt(new_token)++ def test_dry_run_leaves_payload_untouched(self):+ flag = self._make_flag("rc-flag", encrypt_with=OLD_KEY)+ original = flag.filters["payloads"]["true"]++ with override_settings(FLAGS_SECRET_KEYS=[NEW_KEY, OLD_KEY]):+ self._run() # no --live-run++ flag.refresh_from_db()+ assert flag.filters["payloads"]["true"] == original++ def test_skips_flag_no_key_can_decrypt(self):+ # Payload encrypted with a key absent from FLAGS_SECRET_KEYS.+ flag = self._make_flag("rc-flag", encrypt_with="orphan-key-0123456789abcdefghijklmnop")+ original = flag.filters["payloads"]["true"]++ with override_settings(FLAGS_SECRET_KEYS=[NEW_KEY, OLD_KEY]):+ self._run("--live-run")++ flag.refresh_from_db()+ assert flag.filters["payloads"]["true"] == original++ def test_helper_decrypts_after_reencryption(self):+ self._make_flag("rc-flag", encrypt_with=OLD_KEY)++ with override_settings(FLAGS_SECRET_KEYS=[NEW_KEY, OLD_KEY]):+ self._run("--live-run")++ flag = FeatureFlag.objects.get(team=self.team, key="rc-flag")+ token = flag.filters["payloads"]["true"]+ # The production decrypt path (primary key in FLAGS_SECRET_KEYS) reads it back.+ assert get_decrypted_flag_payload(token, should_decrypt=True) == PAYLOAD++ def test_rerun_skips_already_rotated_rows(self):+ self._make_flag("rc-flag", encrypt_with=OLD_KEY)++ with override_settings(FLAGS_SECRET_KEYS=[NEW_KEY, OLD_KEY]):+ self._run("--live-run")+ first = FeatureFlag.objects.get(team=self.team, key="rc-flag").filters["payloads"]["true"]++ # Second pass: payloads already decrypt on the primary key, so nothing is rewritten.+ self._run("--live-run")+ second = FeatureFlag.objects.get(team=self.team, key="rc-flag").filters["payloads"]["true"]++ assert first == second++ def test_reencrypt_re_reads_filters_under_lock(self):+ # The command streams a snapshot of filters, but the live write must merge the+ # rotation into the *current* DB value so a concurrent edit to sibling fields+ # (here "groups") isn't clobbered by writing back the stale streamed blob.+ flag = self._make_flag("rc-flag", encrypt_with=OLD_KEY)+ FeatureFlag.objects.filter(pk=flag.pk).update(+ filters={"groups": [{"properties": [{"key": "x", "value": "y"}]}], "payloads": flag.filters["payloads"]}+ )++ with override_settings(FLAGS_SECRET_KEYS=[NEW_KEY, OLD_KEY]):+ assert Command()._reencrypt(flag.pk, flag_payload_codec()) is True++ flag.refresh_from_db()+ assert flag.filters["groups"] == [{"properties": [{"key": "x", "value": "y"}]}]+ new_token = flag.filters["payloads"]["true"].encode("utf-8")+ assert _codec(NEW_KEY).decrypt(new_token).decode("utf-8") == PAYLOAD