: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
fix(flags): require remote config for encrypted payloads (#57743)
Phil Haack248a2817ed2b
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsxindex 2b2b65068d73..cd8e26e1b1da 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx@@ -264,6 +264,14 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {: 'boolean'const onSelectFlagType = (value: string): void => {+ // Leaving remote config: the backend invariant requires+ // has_encrypted_payloads=true only on remote config flags,+ // and the prior ciphertext is no longer valid.+ const wasLeavingRemoteConfig =+ featureFlag?.is_remote_configuration === true &&+ value !== 'remote_config' &&+ featureFlag?.has_encrypted_payloads+if (value === 'remote_config') {setFeatureFlag({...featureFlag,@@ -287,6 +295,10 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {})setMultivariateEnabled(false)}++ if (wasLeavingRemoteConfig) {+ resetEncryptedPayload()+ }}const FLAG_TYPE_OPTIONS = [diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 74f3874e5b08..3cd40fd9df7a 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -9,6 +9,8 @@ import { initKeaTests } from '~/test/init'import { FeatureFlagType, PropertyFilterType, PropertyOperator } from '~/types'import { FeatureFlagFilters } from '~/types'+import { TemplateKey } from 'products/feature_flags/frontend/featureFlagTemplateConstants'+import { detectFeatureFlagChanges } from './featureFlagConfirmationLogic'import {NEW_FLAG,@@ -282,6 +284,157 @@ describe('featureFlagLogic', () => {})})+ describe('applyTemplate', () => {+ const EXPECTED_VARIANTS = partial({+ variants: [partial({ key: 'control' }), partial({ key: 'test' })],+ })++ const TEMPLATE_EXPECTATIONS: Array<{+ id: TemplateKey+ expectedMultivariate: unknown+ }> = [+ { id: 'simple', expectedMultivariate: null },+ { id: 'targeted', expectedMultivariate: null },+ { id: 'multivariate', expectedMultivariate: EXPECTED_VARIANTS },+ { id: 'targeted-multivariate', expectedMultivariate: EXPECTED_VARIANTS },+ ]++ it.each(TEMPLATE_EXPECTATIONS)(+ 'clears encrypted-payload state when switching a remote configuration flag to $id',+ async ({ id, expectedMultivariate }) => {+ const MOCK_REMOTE_CONFIG_FLAG: FeatureFlagType = {+ ...logic.values.featureFlag,+ is_remote_configuration: true,+ has_encrypted_payloads: true,+ filters: {+ ...logic.values.featureFlag.filters,+ payloads: { true: 'encrypted-ciphertext' },+ },+ }++ await expectLogic(logic, () => {+ logic.actions.setFeatureFlag(MOCK_REMOTE_CONFIG_FLAG)+ }).toDispatchActions(['setFeatureFlag'])++ await expectLogic(logic, () => {+ logic.actions.applyTemplate(id)+ })+ .toDispatchActions(['applyTemplate', 'setFeatureFlag', 'resetEncryptedPayload'])+ .toMatchValues({+ featureFlag: partial({+ is_remote_configuration: false,+ has_encrypted_payloads: false,+ filters: partial({+ multivariate: expectedMultivariate,+ payloads: { true: '' },+ }),+ }),+ })++ // The encrypted ciphertext must not survive under any payload key.+ expect(Object.values(logic.values.featureFlag.filters.payloads ?? {})).not.toContain(+ 'encrypted-ciphertext'+ )+ }+ )++ it('preserves variant payloads when applying a template to a non-encrypted flag', async () => {+ const MOCK_NON_ENCRYPTED_FLAG: FeatureFlagType = {+ ...logic.values.featureFlag,+ is_remote_configuration: false,+ has_encrypted_payloads: false,+ filters: {+ ...logic.values.featureFlag.filters,+ payloads: { control: '{"x":1}', test: '{"y":2}' },+ },+ }++ await expectLogic(logic, () => {+ logic.actions.setFeatureFlag(MOCK_NON_ENCRYPTED_FLAG)+ }).toDispatchActions(['setFeatureFlag'])++ await expectLogic(logic, () => {+ logic.actions.applyTemplate('multivariate')+ })+ .toDispatchActions(['applyTemplate', 'setFeatureFlag'])+ .toMatchValues({+ featureFlag: partial({+ is_remote_configuration: false,+ has_encrypted_payloads: false,+ filters: partial({+ payloads: { control: '{"x":1}', test: '{"y":2}' },+ }),+ }),+ })+ })+ })++ describe('setRemoteConfigEnabled', () => {+ it('clears encrypted-payload state when toggling remote config off', async () => {+ const MOCK_REMOTE_CONFIG_FLAG: FeatureFlagType = {+ ...logic.values.featureFlag,+ is_remote_configuration: true,+ has_encrypted_payloads: true,+ filters: {+ ...logic.values.featureFlag.filters,+ payloads: { true: 'encrypted-ciphertext' },+ },+ }++ await expectLogic(logic, () => {+ logic.actions.setFeatureFlag(MOCK_REMOTE_CONFIG_FLAG)+ }).toDispatchActions(['setFeatureFlag'])++ await expectLogic(logic, () => {+ logic.actions.setRemoteConfigEnabled(false)+ })+ .toDispatchActions(['setRemoteConfigEnabled', 'resetEncryptedPayload'])+ .toMatchValues({+ featureFlag: partial({+ is_remote_configuration: false,+ has_encrypted_payloads: false,+ filters: partial({+ payloads: { true: '' },+ }),+ }),+ })++ // The encrypted ciphertext must not survive under any payload key.+ expect(Object.values(logic.values.featureFlag.filters.payloads ?? {})).not.toContain('encrypted-ciphertext')+ })++ it('does not reset encrypted payload state when toggling off a non-encrypted flag', async () => {+ const MOCK_REMOTE_CONFIG_PLAIN_FLAG: FeatureFlagType = {+ ...logic.values.featureFlag,+ is_remote_configuration: true,+ has_encrypted_payloads: false,+ filters: {+ ...logic.values.featureFlag.filters,+ payloads: { true: 'plain-payload' },+ },+ }++ await expectLogic(logic, () => {+ logic.actions.setFeatureFlag(MOCK_REMOTE_CONFIG_PLAIN_FLAG)+ }).toDispatchActions(['setFeatureFlag'])++ await expectLogic(logic, () => {+ logic.actions.setRemoteConfigEnabled(false)+ })+ .toDispatchActions(['setRemoteConfigEnabled'])+ .toNotHaveDispatchedActions(['resetEncryptedPayload'])+ .toMatchValues({+ featureFlag: partial({+ is_remote_configuration: false,+ has_encrypted_payloads: false,+ filters: partial({+ payloads: { true: 'plain-payload' },+ }),+ }),+ })+ })+ })+describe('change detection', () => {it('detects active status changes', () => {const originalFlag = { ...MOCK_FEATURE_FLAG, active: false }diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 66162bc7135f..0f0a6c8605b7 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -1944,6 +1944,11 @@ export const featureFlagLogic = kea<featureFlagLogicType>([const templateGroups = templateValues.filters?.groups ?? []const mergedGroups = defaultGroups.length > 0 ? [...defaultGroups, ...templateGroups] : templateGroups+ const leavingRemoteConfigEncrypted =+ values.featureFlag.is_remote_configuration === true &&+ templateValues.is_remote_configuration === false &&+ values.featureFlag.has_encrypted_payloads === true+actions.setFeatureFlag({...values.featureFlag,...templateValues,@@ -1954,6 +1959,13 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},} as FeatureFlagType)+ if (leavingRemoteConfigEncrypted) {+ // Leaving remote config: the backend invariant requires+ // has_encrypted_payloads=true only on remote config flags,+ // and the prior ciphertext is no longer valid.+ actions.resetEncryptedPayload()+ }+actions.setTemplateExpanded(false)actions.applyUrlTemplate(templateId)@@ -2104,6 +2116,11 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},{})+ } else if (values.featureFlag.has_encrypted_payloads) {+ // Leaving remote config: the backend invariant requires+ // has_encrypted_payloads=true only on remote config flags,+ // and the prior ciphertext is no longer valid.+ actions.resetEncryptedPayload()}},saveDescriptionInline: async ({ name }) => {diff --git a/posthog/api/feature_flag.py b/posthog/api/feature_flag.pyindex c2ce307a9558..258483cdfc8a 100644--- a/posthog/api/feature_flag.py+++ b/posthog/api/feature_flag.py@@ -1,6 +1,7 @@from __future__ import annotationsimport re+import copyimport jsonimport mathimport time@@ -770,6 +771,8 @@ class FeatureFlagSerializer("""Validate feature flag creation/update including evaluation tag requirements."""attrs = super().validate(attrs)+ self._validate_encrypted_payloads_require_remote_config(attrs)+# Validate team-wide flag count limit before any early returns, since it# applies to all creates regardless of creation context (surveys, etc.)self._validate_flag_limits()@@ -825,6 +828,21 @@ class FeatureFlagSerializer(return attrs+ def _validate_encrypted_payloads_require_remote_config(self, attrs: dict) -> None:+ """Encrypted payloads are only valid on remote configuration flags."""+ # Resolve effective values: use incoming attrs, falling back to instance for updates+ has_encrypted = attrs.get(+ "has_encrypted_payloads",+ getattr(self.instance, "has_encrypted_payloads", False) if self.instance else False,+ )+ is_remote = attrs.get(+ "is_remote_configuration",+ getattr(self.instance, "is_remote_configuration", False) if self.instance else False,+ )++ if has_encrypted and not is_remote:+ raise serializers.ValidationError("Encrypted payloads require the flag to be a remote configuration.")+def validate_key(self, value):exclude_kwargs = {}if self.instance:@@ -1514,13 +1532,62 @@ class FeatureFlagSerializer(filters = validated_data.get("filters", instance.filters) or {}validated_data["filters"] = self._update_super_groups_for_key_change(validated_key, old_key, filters)- if validated_data.get("has_encrypted_payloads", False):- if validated_data["filters"]["payloads"]["true"] == REDACTED_PAYLOAD_VALUE:- # Don't write the redacted payload to the db, keep the current value instead- validated_data["filters"]["payloads"]["true"] = instance.filters["payloads"]["true"]+ # Resolve `has_encrypted_payloads` against the instance so a partial PATCH+ # that omits the boolean still routes through the right path.+ effective_has_encrypted = validated_data.get("has_encrypted_payloads", instance.has_encrypted_payloads)++ if effective_has_encrypted:+ # Ensure downstream helpers (e.g. encrypt_flag_payloads) see the+ # flag even when the client didn't echo it back in this PATCH.+ validated_data["has_encrypted_payloads"] = True+ filters = validated_data.get("filters")+ new_true_payload = ((filters or {}).get("payloads") or {}).get("true")++ if not new_true_payload or new_true_payload == REDACTED_PAYLOAD_VALUE:+ # Preserve the existing encrypted payload when the request didn't+ # supply a fresh one — either because `filters.payloads` was+ # omitted (partial PATCH from the V2 form), the redacted+ # placeholder was echoed back, or an empty string slipped past+ # `validate_filters` (defense in depth: the public API rejects+ # `""` as invalid JSON upstream, but direct serializer callers+ # could still land here). Only re-inject when `filters` is+ # being sent, so a filters-less PATCH stays a partial update.+ if filters is not None:+ existing_true_payload = (instance.filters or {}).get("payloads", {}).get("true")+ if not existing_true_payload:+ raise exceptions.ValidationError(+ "An encrypted payload is required when has_encrypted_payloads is true."+ )+ payloads = filters.get("payloads") or {}+ payloads["true"] = existing_true_payload+ filters["payloads"] = payloadselse:encrypt_flag_payloads(validated_data)+ elif instance.has_encrypted_payloads:+ # Downgrading from encrypted to non-encrypted. Strip leftover+ # ciphertext so a partial PATCH that only flipped the bit doesn't+ # leave the prior encrypted blob exposed as a normal payload on+ # subsequent reads (redaction is gated on has_encrypted_payloads).+ filters = validated_data.get("filters")+ if filters is None:+ # Client didn't send filters; inject a copy of instance.filters+ # with the encrypted "true" payload removed.+ new_filters = copy.deepcopy(instance.filters or {})+ payloads = new_filters.get("payloads") or {}+ payloads.pop("true", None)+ new_filters["payloads"] = payloads+ validated_data["filters"] = new_filters+ else:+ # Client sent filters. Drop an empty/missing/redacted echo at+ # "true"; a fresh non-empty plaintext is left alone (the user+ # explicitly set a new payload during the downgrade).+ payloads = filters.get("payloads") or {}+ true_val = payloads.get("true")+ if not true_val or true_val == REDACTED_PAYLOAD_VALUE:+ payloads.pop("true", None)+ filters["payloads"] = payloads+# Opportunistically strip legacy holdout_groups key (replaced by holdout in Phase 1-4).# Uses the same inject-into-validated_data pattern as _update_super_groups_for_key_change.previous_filters = validated_data.get("filters") or instance.filtersdiff --git a/posthog/api/test/test_feature_flag.py b/posthog/api/test/test_feature_flag.pyindex 1df3cec14829..10787c98f994 100644--- a/posthog/api/test/test_feature_flag.py+++ b/posthog/api/test/test_feature_flag.py@@ -26,6 +26,7 @@ from posthog import redisfrom posthog.api.cohort import get_cohort_actors_for_feature_flagfrom posthog.api.feature_flag import FeatureFlagSerializer, extract_etag_from_headerfrom posthog.constants import AvailableFeature+from posthog.helpers.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE, get_decrypted_flag_payloadfrom posthog.models import FeatureFlag, GroupTypeMapping, TaggedItem, Userfrom posthog.models.cohort import Cohortfrom posthog.models.cohort.cohort import CohortType@@ -899,6 +900,84 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):instance = FeatureFlag.objects.get(id=response_data["id"])self.assertEqual(instance.filters["groups"][0]["rollout_percentage"], 100)+ @patch("posthog.api.feature_flag.report_user_action")+ def test_create_encrypted_payloads_requires_remote_configuration(self, mock_report_user_action):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {+ "key": "encrypted-without-remote",+ "name": "Encrypted Without Remote",+ "has_encrypted_payloads": True,+ "is_remote_configuration": False,+ "filters": {"groups": [{"rollout_percentage": 100}], "payloads": {"true": '"secret"'}},+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("remote configuration", response.json()["detail"])++ @patch("posthog.api.feature_flag.report_user_action")+ def test_create_encrypted_payloads_with_remote_configuration_succeeds(self, mock_report_user_action):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {+ "key": "encrypted-with-remote",+ "name": "Encrypted With Remote",+ "has_encrypted_payloads": True,+ "is_remote_configuration": True,+ "filters": {"groups": [{"rollout_percentage": 100}], "payloads": {"true": '"secret"'}},+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ @patch("posthog.api.feature_flag.report_user_action")+ def test_update_remote_config_flag_to_non_remote_with_encrypted_payloads_fails(self, mock_report_user_action):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {+ "key": "rc-encrypted",+ "name": "RC Encrypted",+ "has_encrypted_payloads": True,+ "is_remote_configuration": True,+ "filters": {"groups": [{"rollout_percentage": 100}], "payloads": {"true": '"secret"'}},+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ flag_id = response.json()["id"]++ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag_id}/",+ {"is_remote_configuration": False},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("remote configuration", response.json()["detail"])++ @patch("posthog.api.feature_flag.report_user_action")+ def test_update_non_remote_flag_to_encrypted_payloads_fails(self, mock_report_user_action):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {+ "key": "non-remote-flag",+ "name": "Non Remote",+ "is_remote_configuration": False,+ "filters": {"groups": [{"rollout_percentage": 100}], "payloads": {"true": '"data"'}},+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ flag_id = response.json()["id"]++ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag_id}/",+ {"has_encrypted_payloads": True},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("remote configuration", response.json()["detail"])+@patch("posthog.api.feature_flag.report_user_action")def test_create_feature_flag_with_analytics_dashboards(self, mock_report_user_action):dashboard = Dashboard.objects.create(team=self.team, name="private dashboard", created_by=self.user)@@ -1937,6 +2016,189 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/nonexistent_key/remote_config")self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ def _create_encrypted_flag(self, stored_payload: str = "original-encrypted-value") -> FeatureFlag:+ return FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="my-encrypted-flag",+ name="Encrypted Flag",+ active=True,+ filters={+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "payloads": {"true": stored_payload},+ },+ is_remote_configuration=True,+ has_encrypted_payloads=True,+ )++ @parameterized.expand(+ [+ (+ "filters_omitted",+ {"name": "Updated Name"},+ ),+ (+ "payloads_omitted",+ {+ "has_encrypted_payloads": True,+ "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]},+ },+ ),+ (+ "true_key_missing",+ {+ "has_encrypted_payloads": True,+ "filters": {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "payloads": {},+ },+ },+ ),+ (+ "redacted_placeholder_echoed",+ {+ "has_encrypted_payloads": True,+ "filters": {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "payloads": {"true": REDACTED_PAYLOAD_VALUE},+ },+ },+ ),+ ]+ )+ def test_update_encrypted_flag_preserves_payload(self, _name: str, patch_body: dict) -> None:+ flag = self._create_encrypted_flag()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ patch_body,+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ flag.refresh_from_db()+ self.assertEqual(flag.filters["payloads"]["true"], "original-encrypted-value")+ self.assertTrue(flag.has_encrypted_payloads)++ def test_update_encrypted_flag_encrypts_fresh_plaintext_payload(self):+ flag = self._create_encrypted_flag()++ plaintext = '"new-secret-value"'+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {+ "has_encrypted_payloads": True,+ "filters": {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "payloads": {"true": plaintext},+ },+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ flag.refresh_from_db()+ stored = flag.filters["payloads"]["true"]+ self.assertNotEqual(stored, plaintext)+ self.assertNotEqual(stored, "original-encrypted-value")+ # Verify the stored ciphertext actually round-trips back to the plaintext.+ decrypted = get_decrypted_flag_payload(stored, should_decrypt=True)+ self.assertEqual(decrypted, plaintext)++ def test_update_encrypted_flag_downgrade_clears_payload(self):+ flag = self._create_encrypted_flag()++ # Mirrors what the frontend sends after `resetEncryptedPayload`: the+ # form's prepare step (`indexToVariantKeyFeatureFlagPayloads`) strips+ # the falsy `true` key, so the wire body has an empty `payloads` dict.+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {+ "has_encrypted_payloads": False,+ "is_remote_configuration": False,+ "filters": {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "payloads": {},+ },+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ flag.refresh_from_db()+ self.assertFalse(flag.has_encrypted_payloads)+ self.assertFalse(flag.is_remote_configuration)+ # The prior ciphertext must not survive a downgrade.+ self.assertNotIn("true", flag.filters["payloads"])++ def test_update_encrypted_flag_partial_downgrade_clears_ciphertext(self):+ # Even when the client sends only the boolean flip and no filters,+ # the server must strip the leftover ciphertext so it is not served+ # unredacted on subsequent reads (redaction is gated on+ # has_encrypted_payloads).+ flag = self._create_encrypted_flag()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {"has_encrypted_payloads": False, "is_remote_configuration": False},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ flag.refresh_from_db()+ self.assertFalse(flag.has_encrypted_payloads)+ self.assertNotIn("true", (flag.filters or {}).get("payloads", {}))++ def test_update_encrypted_flag_encrypts_when_boolean_omitted(self):+ # A partial PATCH that supplies a fresh `payloads.true` plaintext but+ # omits `has_encrypted_payloads` must still encrypt; the instance is+ # already encrypted, and falling through to the un-encrypted branch+ # would write plaintext on a row marked as encrypted.+ flag = self._create_encrypted_flag()++ plaintext = '"another-secret"'+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {+ "filters": {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "payloads": {"true": plaintext},+ },+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ flag.refresh_from_db()+ stored = flag.filters["payloads"]["true"]+ self.assertNotEqual(stored, plaintext)+ decrypted = get_decrypted_flag_payload(stored, should_decrypt=True)+ self.assertEqual(decrypted, plaintext)++ def test_update_encrypted_flag_rejects_enabling_without_payload(self):+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="my-flag",+ name="Flag",+ active=True,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {+ "has_encrypted_payloads": True,+ "is_remote_configuration": True,+ "filters": {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "payloads": {"true": REDACTED_PAYLOAD_VALUE},+ },+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+def test_get_conflicting_changes(self):feature_flag = FeatureFlag.objects.create(team=self.team,diff --git a/posthog/migrations/1148_backfill_encrypted_payloads_invariant.py b/posthog/migrations/1148_backfill_encrypted_payloads_invariant.pynew file mode 100644index 000000000000..b65c08a9bb61--- /dev/null+++ b/posthog/migrations/1148_backfill_encrypted_payloads_invariant.py@@ -0,0 +1,64 @@+from django.db import migrations++import structlog++logger = structlog.get_logger(__name__)+++def backfill_encrypted_payloads_invariant(apps, schema_editor):+ """Clear has_encrypted_payloads on flags that aren't remote configurations.++ The two booleans were independently settable via the API and a frontend+ template-switch path, so a small number of rows ended up with+ has_encrypted_payloads=true while is_remote_configuration=false. The new+ model and serializer validation rejects this combination, so existing rows+ must be reconciled before validation can run for any save path.++ Verified for PostHog Cloud (US: 8 rows, EU: 3 rows) that all violating+ rows have empty `filters.payloads`, so the bit-flip is lossless there.+ For self-hosted installs the same may not hold: a row with non-empty+ `filters.payloads.true` would, after the flip, expose its previously+ redacted ciphertext as a normal payload (redaction in to_representation+ is gated on has_encrypted_payloads). To stay safe-by-construction we+ partition the candidates and only flip rows whose `filters.payloads.true`+ is empty/null. Anything with a non-empty value is left in place and+ surfaced via a warning log for manual reconciliation.++ Updates the FK queryset directly to skip ModelActivityMixin signals —+ this is a janitorial fix, not user activity.+ """+ FeatureFlag = apps.get_model("posthog", "FeatureFlag")+ candidates = FeatureFlag.objects.filter(has_encrypted_payloads=True).exclude(is_remote_configuration=True)++ safe_to_clear = []+ needs_review = []+ for flag_id, filters in candidates.values_list("id", "filters"):+ true_payload = ((filters or {}).get("payloads") or {}).get("true")+ if not true_payload:+ safe_to_clear.append(flag_id)+ else:+ needs_review.append(flag_id)++ if needs_review:+ logger.warning(+ "backfill_encrypted_payloads_invariant_skipped",+ skipped_flag_ids=needs_review[:50],+ skipped_count=len(needs_review),+ )++ updated = FeatureFlag.objects.filter(id__in=safe_to_clear).update(has_encrypted_payloads=False)++ if updated:+ logger.info("backfill_encrypted_payloads_invariant", updated_flags=updated)+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1147_columnconfiguration_order_by")]++ operations = [+ migrations.RunPython(+ backfill_encrypted_payloads_invariant,+ migrations.RunPython.noop,+ elidable=True,+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 87f940da0f72..afc3436a50cd 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1147_columnconfiguration_order_by+1148_backfill_encrypted_payloads_invariantdiff --git a/posthog/models/feature_flag/feature_flag.py b/posthog/models/feature_flag/feature_flag.pyindex bcca8379f570..5003f447702c 100644--- a/posthog/models/feature_flag/feature_flag.py+++ b/posthog/models/feature_flag/feature_flag.py@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Any, Optional, castfrom django.contrib.auth.base_user import AbstractBaseUserfrom django.contrib.postgres.aggregates import ArrayAggfrom django.core.cache import cache+from django.core.exceptions import ValidationErrorfrom django.db import DatabaseError, models, transactionfrom django.db.models import Q, QuerySetfrom django.db.models.signals import post_delete, post_save@@ -132,6 +133,17 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, modelsdef __str__(self):return f"{self.key} ({self.pk})"+ def clean(self) -> None:+ """Reject encrypted payloads on non-remote-config flags.++ Django does not invoke clean() from save(), so this fires only from+ admin and explicit full_clean() callers. The HTTP path is gated by+ FeatureFlagSerializer._validate_encrypted_payloads_require_remote_config.+ """+ super().clean()+ if self.has_encrypted_payloads and not self.is_remote_configuration:+ raise ValidationError("Encrypted payloads require the flag to be a remote configuration.")+@classmethoddef get_file_system_unfiled(cls, team: "Team") -> QuerySet["FeatureFlag"]:base_qs = cls.objects.filter(team=team, deleted=False)diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex bc838a6962ae..2c9996ca2b2f 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -724,6 +724,7 @@'access','aggregation_group_type_index','analytics_dashboards',+ 'clean','conditions','created_by_id','deleted',