Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(flags): show remote config flag payload in session replay (#78383)

Gustavo H. Strassburger5896f15c9d58
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/EventFlagsTab.test.ts b/frontend/src/scenes/session-recordings/player/inspector/components/EventFlagsTab.test.ts
new file mode 100644
index 000000000000..367cf20e39fb
--- /dev/null
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/EventFlagsTab.test.ts
@@ -0,0 +1,29 @@
+import { reconstructionTarget } from './EventFlagsTab'
+
+describe('reconstructionTarget', () => {
+ const lookupKeys = { $feature_flag_id: 629210, $feature_flag_version: 5 }
+
+ it.each([
+ ['boolean flag looks up the "true" payload', true, 'true'],
+ ['multivariate flag looks up its variant payload', 'control', 'control'],
+ ])('%s', (_name, response, expectedKey) => {
+ expect(reconstructionTarget({ ...lookupKeys, $feature_flag_response: response })).toEqual({
+ flagId: 629210,
+ version: 5,
+ payloadKey: expectedKey,
+ })
+ })
+
+ it.each([
+ ['flag id missing', { $feature_flag_version: 5, $feature_flag_response: true }],
+ ['version missing', { $feature_flag_id: 629210, $feature_flag_response: true }],
+ ['flag evaluated to false', { ...lookupKeys, $feature_flag_response: false }],
+ ['response missing', lookupKeys],
+ [
+ 'SDK already sent the payload',
+ { ...lookupKeys, $feature_flag_response: true, $feature_flag_payload: '"1.0.0"' },
+ ],
+ ])('returns null when %s', (_name, properties) => {
+ expect(reconstructionTarget(properties)).toBeNull()
+ })
+})
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/EventFlagsTab.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/EventFlagsTab.tsx
new file mode 100644
index 000000000000..2b3dcf3a013e
--- /dev/null
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/EventFlagsTab.tsx
@@ -0,0 +1,75 @@
+import { useValues } from 'kea'
+
+import { SimpleKeyValueList } from 'lib/components/SimpleKeyValueList'
+
+import { flagPayloadLogic } from './flagPayloadLogic'
+
+export interface EventFlagsTabProps {
+ properties: Record<string, any>
+ promotedKeys?: string[]
+}
+
+export interface ReconstructionTarget {
+ flagId: number
+ version: number
+ payloadKey: string
+}
+
+/**
+ * Works out whether a flag's payload can be recovered from its version history, and under which
+ * key in the flag's `payloads` map. Returns null when the event lacks the lookup keys or already
+ * carries the payload itself.
+ */
+export function reconstructionTarget(properties: Record<string, any>): ReconstructionTarget | null {
+ if ('$feature_flag_payload' in properties) {
+ return null
+ }
+
+ const flagId = properties['$feature_flag_id']
+ const version = properties['$feature_flag_version']
+ const response = properties['$feature_flag_response']
+
+ if (typeof flagId !== 'number' || typeof version !== 'number') {
+ return null
+ }
+
+ // Boolean and remote config flags store their payload under "true"; multivariate flags
+ // store one per variant.
+ if (response === true) {
+ return { flagId, version, payloadKey: 'true' }
+ }
+ if (typeof response === 'string' && response !== '') {
+ return { flagId, version, payloadKey: response }
+ }
+ return null
+}
+
+/**
+ * Mobile and server SDKs send the flag id and version on `$feature_flag_called` but not the
+ * payload, so a remote config flag shows as enabled with no indication of what it served. The
+ * payload is reconstructed from the flag's version history instead of being sent on the event.
+ */
+export function EventFlagsTab({ properties, promotedKeys }: EventFlagsTabProps): JSX.Element {
+ const target = reconstructionTarget(properties)
+
+ if (!target) {
+ return <SimpleKeyValueList item={properties} promotedKeys={promotedKeys} />
+ }
+
+ return <ReconstructedFlagPayload properties={properties} promotedKeys={promotedKeys} target={target} />
+}
+
+function ReconstructedFlagPayload({
+ properties,
+ promotedKeys,
+ target,
+}: EventFlagsTabProps & { target: ReconstructionTarget }): JSX.Element {
+ const { flagPayload } = useValues(flagPayloadLogic(target))
+
+ return (
+ <SimpleKeyValueList
+ item={{ ...(flagPayload !== null ? { $feature_flag_payload: flagPayload } : {}), ...properties }}
+ promotedKeys={promotedKeys}
+ />
+ )
+}
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.tsx
index c6d6406b0e11..d972570add32 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.tsx
@@ -32,6 +32,7 @@ import { ItemTimeDisplay } from '../../../components/ItemTimeDisplay'
import { sessionRecordingPlayerLogic } from '../../sessionRecordingPlayerLogic'
import { InspectorListItemEvent } from '../playerInspectorLogic'
import { AIEventExpanded, AIEventSummary } from './AIEventItems'
+import { EventFlagsTab } from './EventFlagsTab'
import { PinPrimaryPropertyButton } from './PinPrimaryPropertyButton'
export interface ItemEventProps {
@@ -295,6 +296,8 @@ function SingleEventDetail({ item }: ItemEventProps): JSX.Element {
rowActions={primaryPropertyActions}
/>
)
+ case 'flags':
+ return <EventFlagsTab properties={properties} promotedKeys={promotedKeys} />
default:
return <SimpleKeyValueList item={properties} promotedKeys={promotedKeys} />
}
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/flagPayloadLogic.ts b/frontend/src/scenes/session-recordings/player/inspector/components/flagPayloadLogic.ts
new file mode 100644
index 000000000000..e2d99599e3f6
--- /dev/null
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/flagPayloadLogic.ts
@@ -0,0 +1,89 @@
+import { MakeLogicType, connect, kea, key, path, props } from 'kea'
+import type { LogicWrapper } from 'kea'
+import { lazyLoaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { featureFlagsVersionsRetrieve } from 'products/feature_flags/frontend/generated/api'
+
+export interface FlagPayloadLogicProps {
+ /** From the event's `$feature_flag_id` property. */
+ flagId: number
+ /** From the event's `$feature_flag_version` property. */
+ version: number
+ /**
+ * Key into the flag's `payloads` map, derived from `$feature_flag_response`. This is the
+ * served variant, or `'true'` for a boolean or remote config flag.
+ */
+ payloadKey: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface flagPayloadLogicValues {
+ currentProjectId: number | string // teamLogic
+ flagPayload: string | null
+ flagPayloadLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface flagPayloadLogicActions {
+ loadFlagPayload: () => any
+ loadFlagPayloadFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadFlagPayloadSuccess: (
+ flagPayload: string | null,
+ payload?: any
+ ) => {
+ flagPayload: string | null
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface flagPayloadLogicMeta {
+ key: string
+}
+
+export type flagPayloadLogicType = MakeLogicType<
+ flagPayloadLogicValues,
+ flagPayloadLogicActions,
+ FlagPayloadLogicProps,
+ flagPayloadLogicMeta
+>
+
+export const flagPayloadLogic: LogicWrapper<flagPayloadLogicType> = kea<flagPayloadLogicType>([
+ props({} as FlagPayloadLogicProps),
+ key((props: FlagPayloadLogicProps) => `${props.flagId}-${props.version}-${props.payloadKey}`),
+ path((key) => ['scenes', 'session-recordings', 'player', 'inspector', 'flagPayloadLogic', key]),
+ connect(() => ({
+ values: [teamLogic, ['currentProjectId']],
+ })),
+ lazyLoaders(({ props, values }) => ({
+ flagPayload: [
+ null as string | null,
+ {
+ loadFlagPayload: async (): Promise<string | null> => {
+ // Reconstruction is best-effort: encrypted payloads are refused, deleted flags
+ // 404, and gaps in the activity log 422. None of those are worth surfacing on a
+ // replay event, so fall back to showing nothing.
+ try {
+ const version = await featureFlagsVersionsRetrieve(
+ String(values.currentProjectId),
+ props.flagId,
+ props.version
+ )
+ const payloads = version.filters?.payloads as Record<string, string> | undefined
+ return payloads?.[props.payloadKey] ?? null
+ } catch {
+ return null
+ }
+ },
+ },
+ ],
+ })),
+])
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 65fb215d4042..a46eea7b70df 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -133,6 +133,8 @@ EARLY_EXIT_FLAG = "feature-flag-early-exit"
# to 100%. Remove the gate and make enforcement unconditional once fully rolled out.
ENFORCE_FEATURE_FLAG_WRITE_SCOPE_FLAG = "enforce-feature-flag-write-scope-cross-resource"
+ENCRYPTED_VERSION_HISTORY_UNAVAILABLE = "Version history is not available for flags with encrypted payloads."
+
def parse_created_by_ids(value: Any) -> list[int]:
"""Parse a `created_by_id` filter value into a list of user IDs.
@@ -3185,7 +3187,7 @@ class FeatureFlagViewSet(
],
responses={
200: FeatureFlagVersionResponseSerializer,
- 400: OpenApiResponse(description="Version history is not available for remote configuration flags."),
+ 400: OpenApiResponse(description=ENCRYPTED_VERSION_HISTORY_UNAVAILABLE),
404: OpenApiResponse(description="Version not found."),
422: OpenApiResponse(description="Activity log incomplete; cannot reconstruct this version."),
},
@@ -3199,9 +3201,11 @@ class FeatureFlagViewSet(
def versions(self, request: request.Request, version_number: str, **kwargs) -> Response:
feature_flag: FeatureFlag = self.get_object()
- if feature_flag.is_remote_configuration or feature_flag.has_encrypted_payloads:
+ # Only encrypted payloads are withheld. A plaintext remote configuration payload is already
+ # served to every SDK through normal flag evaluation, so gating it here protects nothing.
+ if feature_flag.has_encrypted_payloads:
return Response(
- {"detail": "Version history is not available for remote configuration or encrypted flags."},
+ {"detail": ENCRYPTED_VERSION_HISTORY_UNAVAILABLE},
status=status.HTTP_400_BAD_REQUEST,
)
@@ -3224,6 +3228,15 @@ class FeatureFlagViewSet(
status=status.HTTP_422_UNPROCESSABLE_ENTITY,
)
+ # `has_encrypted_payloads` is mutable: a flag can be downgraded to plaintext, which strips
+ # ciphertext from the live row but not from the activity log the reconstruction reads. Gate
+ # on the reconstructed version's own state so pre-downgrade versions don't return ciphertext.
+ if result["has_encrypted_payloads"]:
+ return Response(
+ {"detail": ENCRYPTED_VERSION_HISTORY_UNAVAILABLE},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
return Response(FeatureFlagVersionResponseSerializer(instance=result).data)
@validated_request(
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index dd4d74e4b325..d6293d7a5d22 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -13227,22 +13227,25 @@ class TestFeatureFlagVersions(APIBaseTest):
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
assert "incomplete" in response.json()["detail"].lower()
- @parameterized.expand(
- [
- ("remote_configuration", {"is_remote_configuration": True}),
- ("encrypted_payloads", {"has_encrypted_payloads": True}),
- ]
- )
- def test_unsupported_flag_returns_400(self, _name, update_kwargs):
+ def test_encrypted_payloads_flag_returns_400(self):
flag = self._create_flag_via_api()
flag_id = flag["id"]
- FeatureFlag.objects.filter(id=flag_id).update(**update_kwargs)
+ FeatureFlag.objects.filter(id=flag_id).update(has_encrypted_payloads=True)
response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag_id}/versions/1/")
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "not available" in response.json()["detail"].lower()
+ def test_plaintext_remote_config_flag_is_reachable(self):
+ flag = self._create_flag_via_api()
+ flag_id = flag["id"]
+
+ FeatureFlag.objects.filter(id=flag_id).update(is_remote_configuration=True)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag_id}/versions/1/")
+ assert response.status_code == status.HTTP_200_OK
+
class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
@patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_version_history.py b/products/feature_flags/backend/api/test/test_feature_flag_version_history.py
new file mode 100644
index 000000000000..af8f33f95c84
--- /dev/null
+++ b/products/feature_flags/backend/api/test/test_feature_flag_version_history.py
@@ -0,0 +1,78 @@
+from posthog.test.base import APIBaseTest
+
+from rest_framework import status
+
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+class TestFeatureFlagVersionHistoryAPI(APIBaseTest):
+ def _create_remote_config_flag(self, *, encrypted: bool = False) -> FeatureFlag:
+ return FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="ios-minimum-version",
+ name="Minimum app version required",
+ active=True,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": {"true": '"1.0.0"'},
+ },
+ is_remote_configuration=True,
+ has_encrypted_payloads=encrypted,
+ version=1,
+ )
+
+ def test_plaintext_remote_config_flag_returns_historical_payload(self):
+ flag = self._create_remote_config_flag()
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",
+ {
+ "filters": {
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": {"true": '"2.0.0"'},
+ }
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/versions/1/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ payload = response.json()
+ self.assertTrue(payload["is_historical"])
+ # The point of reconstruction: the payload served at the time, not the current one.
+ self.assertEqual(payload["filters"]["payloads"], {"true": '"1.0.0"'})
+
+ def test_encrypted_payload_flag_is_refused(self):
+ flag = self._create_remote_config_flag(encrypted=True)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/versions/1/")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertNotIn("filters", response.json())
+
+ def test_version_encrypted_before_downgrade_is_refused(self):
+ ciphertext = "gAAAAA-ciphertext-sentinel"
+ flag = self._create_remote_config_flag(encrypted=True)
+ flag.filters = {
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": {"true": ciphertext},
+ }
+ flag.save()
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",
+ {"has_encrypted_payloads": False},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ flag.refresh_from_db()
+ self.assertFalse(flag.has_encrypted_payloads)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/versions/1/")
+
+ # The live row is plaintext now, but version 1 still holds ciphertext in the activity log.
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertNotIn(ciphertext, response.content.decode())