: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(cdp): mask destination values in activity logs (#109381)
Daniel Marchukf45630dfdbff
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.mdindex 461919dbea8d..a304541903d5 100644--- a/docs/internal/activity-logging.md+++ b/docs/internal/activity-logging.md@@ -127,6 +127,14 @@ Four registries in `activity_log.py` tune it per scope:Exclude relations that hold execution results or storage bookkeeping, such as a notebook's widget snapshots.Reading their fail-closed managers can require team context that background writes do not have.+Destination activity logs record changes to `mappings` without their values.+For `inputs` they keep each key and record only whether its value changed, so the history can name the changed input.+Rows written before a field joined `field_with_masked_contents` still store its values.+Code that returns a row's `detail` to a user must read `ActivityLog.safe_detail`, which masks those fields in old rows too.+The activity log API, the advanced activity logs API and its exports, the notifications feed, and the PostHog AI context all do.+The `system.activity_logs` SQL table and the search filter read the stored `detail`, so old rows need rewriting to stay masked there.+These protections do not revoke exposed credentials.+## Writes the signal cannot seeThe mixin hooks `save()` and `delete()`.diff --git a/ee/hogai/context/activity_log/context.py b/ee/hogai/context/activity_log/context.pyindex da59acc4c9be..c98069995626 100644--- a/ee/hogai/context/activity_log/context.py+++ b/ee/hogai/context/activity_log/context.py@@ -230,7 +230,7 @@ class ActivityLogContext:return entry.item_id or "(unknown)"def _format_changes(self, entry: ActivityLog) -> str:- detail = entry.detail+ detail = entry.safe_detailif not detail or not isinstance(detail, dict):return ""diff --git a/ee/hogai/context/activity_log/test/test_context.py b/ee/hogai/context/activity_log/test/test_context.pyindex fa588e6e6b10..0736225ba188 100644--- a/ee/hogai/context/activity_log/test/test_context.py+++ b/ee/hogai/context/activity_log/test/test_context.py@@ -277,24 +277,40 @@ class TestActivityLogContext(ActivityLogTestBase):[("created_change",+ "FeatureFlag",[{"field": "enabled", "action": "created", "after": True}],"enabled: set to True",),("deleted_change",+ "FeatureFlag",[{"field": "description", "action": "deleted", "before": "old desc"}],"description: removed (was old desc)",),("changed_value",+ "FeatureFlag",[{"field": "name", "action": "changed", "before": "old", "after": "new"}],"name: old -> new",),+ (+ "destination_inputs_masked",+ "HogFunction",+ [+ {+ "field": "inputs",+ "action": "changed",+ "before": {"api_key": {"value": "old-value"}},+ "after": {"api_key": {"value": "new-value"}},+ }+ ],+ 'inputs: {"api_key": "masked"} -> {"api_key": "changed"}',+ ),])- async def test_format_changes(self, _name, changes, expected_text):+ async def test_format_changes(self, _name, scope, changes, expected_text):await self._create_log(- scope="FeatureFlag",+ scope=scope,activity="updated",item_id="1",detail={"name": "test", "changes": changes},diff --git a/frontend/src/scenes/hog-functions/misc/activityDescriptions.test.tsx b/frontend/src/scenes/hog-functions/misc/activityDescriptions.test.tsxindex 134d7c9768ca..511dd84c7acf 100644--- a/frontend/src/scenes/hog-functions/misc/activityDescriptions.test.tsx+++ b/frontend/src/scenes/hog-functions/misc/activityDescriptions.test.tsx@@ -34,6 +34,28 @@ describe('hogFunctionActivityDescriber', () => {summary: 'updated input: region',notification: 'A user updated the input region for the hog function: Example destination',},+ {+ name: 'names the changed keys of masked inputs and skips the compiled code',+ changes: [+ {+ field: 'inputs',+ before: { region: 'masked', format: 'masked' },+ after: { region: 'changed', format: 'masked' },+ },+ { field: 'transpiled', before: 'masked', after: 'masked' },+ ],+ summary: 'updated input: region',+ notification: 'A user updated the input region for the hog function: Example destination',+ },+ {+ name: 'describes masked inputs and mappings without values',+ changes: [+ { field: 'inputs', before: 'masked', after: 'masked' },+ { field: 'mappings', before: 'masked', after: 'masked' },+ ],+ summary: 'updated inputs, and updated mappings',+ notification: 'A user updated the hog function: Example destinationupdated inputsupdated mappings',+ },{name: 'retains source-code links and multi-change notifications',changes: [diff --git a/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx b/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsxindex c0e9ef2d441d..cc2bbe5b4f92 100644--- a/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx+++ b/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx@@ -66,14 +66,19 @@ export function DiffLink({ before, after, language, children }: DiffLinkProps):type HogFunctionChange = { inline: string | JSX.Element; inlist: string | JSX.Element }+function inputValue(input: unknown): unknown {+ return isObject(input) ? (input as { value?: unknown }).value : input+}+function describeHogFunctionInputs(change: ActivityChange): HogFunctionChange {- const beforeValues = isObject(change.before) ? (change.before as Record<string, { value?: unknown }>) : {}- const afterValues = isObject(change.after) ? (change.after as Record<string, { value?: unknown }>) : {}+ const beforeValues = isObject(change.before) ? (change.before as Record<string, unknown>) : {}+ const afterValues = isObject(change.after) ? (change.after as Record<string, unknown>) : {}const changedFields = Object.entries(afterValues).map(([key, value]) => {- const before = JSON.stringify(beforeValues[key]?.value)- const after = JSON.stringify(value?.value)+ // Masked rows store a plain string per key instead of the input value+ const before = JSON.stringify(inputValue(beforeValues[key]))+ const after = JSON.stringify(inputValue(value))if (before !== after) {return (@@ -136,7 +141,12 @@ function describeHogFunctionField(change: ActivityChange, objectNoun: string): Hcase 'encrypted_inputs':return { inline: 'updated encrypted inputs for', inlist: 'updated encrypted inputs' }case 'inputs':+ if (!isObject(change.before) && !isObject(change.after)) {+ return { inline: 'updated inputs for', inlist: 'updated inputs' }+ }return describeHogFunctionInputs(change)+ case 'mappings':+ return { inline: 'updated mappings for', inlist: 'updated mappings' }case 'deleted': {const verb = change.after ? 'deleted' : 'undeleted'return { inline: verb, inlist: `${verb} the ${objectNoun}` }@@ -178,6 +188,10 @@ function describeHogFunctionUpdate(logItem: ActivityLogItem, objectNoun: string)}continue}+ // Older rows logged the compiled site code, which follows from the inputs and source already listed.+ if (change.field === 'transpiled') {+ continue+ }changes.push(describeHogFunctionField(change, objectNoun))}const functionName = nameOrLinkToHogFunction(logItem?.item_id, logItem?.detail.name)diff --git a/posthog/api/advanced_activity_logs/ocsf.py b/posthog/api/advanced_activity_logs/ocsf.pyindex 4ec10690b2cd..0a07400d1519 100644--- a/posthog/api/advanced_activity_logs/ocsf.py+++ b/posthog/api/advanced_activity_logs/ocsf.py@@ -75,7 +75,7 @@ def _classify(activity: str) -> tuple[int, int]:def _changes(instance: ActivityLog) -> list[dict[str, Any]]:- detail = instance.detail or {}+ detail = instance.safe_detail or {}return [change for change in (detail.get("changes") or []) if isinstance(change, dict)]@@ -86,7 +86,7 @@ class ActivityLogOCSFSerializer(serializers.ModelSerializer):def to_representation(self, instance: ActivityLog) -> dict[str, Any]:class_uid, activity_id = _classify(instance.activity)- detail = instance.detail or {}+ detail = instance.safe_detail or {}changes = _changes(instance)changed_fields = [change["field"] for change in changes if change.get("field")]diff --git a/posthog/api/advanced_activity_logs/viewset.py b/posthog/api/advanced_activity_logs/viewset.pyindex 325b5f0d8152..1c99c68100c0 100644--- a/posthog/api/advanced_activity_logs/viewset.py+++ b/posthog/api/advanced_activity_logs/viewset.py@@ -170,6 +170,11 @@ class ActivityLogSerializer(serializers.ModelSerializer):"created_at",]+ def to_representation(self, instance: ActivityLog) -> dict:+ data = super().to_representation(instance)+ data["detail"] = instance.safe_detail+ return data+def get_unread(self, obj: ActivityLog) -> bool:"""is the date of this log item newer than the user's bookmark"""if "user" not in self.context:@@ -552,7 +557,7 @@ class ActivityLogFlatExportSerializer(serializers.ModelSerializer):]def get_detail(self, obj):- return json.dumps(obj.detail) if obj.detail else ""+ return json.dumps(obj.safe_detail) if obj.detail else ""class StaticFiltersSerializer(serializers.Serializer):diff --git a/posthog/api/my_notifications.py b/posthog/api/my_notifications.pyindex 54c923cd75a6..365a657b7ef6 100644--- a/posthog/api/my_notifications.py+++ b/posthog/api/my_notifications.py@@ -43,6 +43,9 @@ INTERESTING_CHANGES = [class MyNotificationsSerializer(serializers.ModelSerializer):user = UserBasicSerializer()unread = serializers.SerializerMethodField()+ detail = serializers.JSONField(+ source="safe_detail", read_only=True, help_text="What changed, with the values of masked fields hidden."+ )class Meta:model = ActivityLogdiff --git a/posthog/api/test/test_activity_log.py b/posthog/api/test/test_activity_log.pyindex 33dd48843e31..7d4c5d755d48 100644--- a/posthog/api/test/test_activity_log.py+++ b/posthog/api/test/test_activity_log.py@@ -211,6 +211,71 @@ class TestActivityLog(APIBaseTest, QueryMatchingTest):class TestActivityLogAuditLogsGate(APIBaseTest):+ @parameterized.expand(+ [+ ("activity_log/",),+ ("advanced_activity_logs/",),+ ("advanced_activity_logs/?is_csv_export=1",),+ ("advanced_activity_logs/?schema=ocsf&include_values=true",),+ ]+ )+ def test_legacy_destination_values_are_masked(self, endpoint: str) -> None:+ detail = {+ "name": "Example destination",+ "changes": [+ {+ "type": "HogFunction",+ "field": field,+ "action": "changed",+ "before": "example-private-before",+ "after": "example-private-after",+ }+ for field in ("inputs", "mappings", "draft", "encrypted_inputs", "draft_encrypted_inputs", "transpiled")+ ]+ + [+ {"type": "HogFunction", "field": "name", "action": "changed", "before": "Old name", "after": "New name"}+ ],+ }+ entry = ActivityLog.objects.create(+ team_id=self.team.id,+ organization_id=self.organization.id,+ user=self.user,+ scope="HogFunction",+ activity="updated",+ item_id="example-function",+ detail=detail,+ )+ flow_entry = ActivityLog.objects.create(+ team_id=self.team.id,+ organization_id=self.organization.id,+ user=self.user,+ scope="HogFlow",+ activity="updated",+ item_id="example-flow",+ detail={+ "name": "Example workflow",+ "changes": [+ {+ "type": "HogFlow",+ "field": "actions",+ "action": "changed",+ "before": [{"config": {"inputs": {"token": {"value": "example-private-flow"}}}}],+ "after": [],+ }+ ],+ },+ )+ response = self.client.get(f"/api/projects/{self.team.id}/{endpoint}")+ assert response.status_code == status.HTTP_200_OK, response.content+ body = response.content.decode()+ assert str(entry.id) in body+ assert str(flow_entry.id) in body+ assert "example-private" not in body+ assert "masked" in body+ assert "New name" in body+ entry.refresh_from_db()+ assert entry.detail == detail+@parameterized.expand([("activity_log",), ("advanced_activity_logs",)])def test_endpoint_blocked_on_cloud_without_audit_logs_feature(self, endpoint: str) -> None:self.organization.available_product_features = []diff --git a/posthog/api/test/test_my_notifications.py b/posthog/api/test/test_my_notifications.pyindex af35cf3a742a..6048c542a6a3 100644--- a/posthog/api/test/test_my_notifications.py+++ b/posthog/api/test/test_my_notifications.py@@ -8,8 +8,11 @@ from rest_framework import statusfrom posthog.api.my_notifications import NOTIFICATION_HISTORY_WINDOWfrom posthog.models import NotificationViewed, User+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.test.insight_queries import default_pageview_query+from products.cdp.backend.models.hog_functions.hog_function import HogFunction+def _feature_flag_json_payload(key: str) -> dict:return {@@ -290,6 +293,40 @@ class TestMyNotifications(APIBaseTest, QueryMatchingTest):assert changes.json()["last_read"] == "2023-08-17T04:24:25.000123Z"assert [c["unread"] for c in changes.json()["results"]] == [True, True]+ def test_masks_destination_values_in_rows_written_before_the_mask(self) -> None:+ destination = HogFunction.objects.create(+ team=self.team, created_by=self.user, name="Example destination", type="destination", hog="return 1"+ )+ with time_machine.travel("2023-08-17T05:00:00Z", tick=False):+ ActivityLog.objects.create(+ team_id=self.team.id,+ organization_id=self.organization.id,+ user=self.other_user,+ scope="HogFunction",+ activity="updated",+ item_id=str(destination.id),+ detail={+ "name": "Example destination",+ "changes": [+ {+ "type": "HogFunction",+ "field": "inputs",+ "action": "changed",+ "before": {"api_key": {"value": "example-private-before"}},+ "after": {"api_key": {"value": "example-private-after"}},+ }+ ],+ },+ )+ changes = self.client.get(f"/api/projects/{self.team.id}/my_notifications")++ assert changes.status_code == status.HTTP_200_OK+ newest = changes.json()["results"][0]+ assert newest["item_id"] == str(destination.id)+ assert newest["detail"]["changes"][0]["before"] == {"api_key": "masked"}+ assert newest["detail"]["changes"][0]["after"] == {"api_key": "changed"}+ assert "example-private" not in changes.content.decode()+def test_changes_older_than_the_history_window_are_not_shown(self) -> None:with time_machine.travel("2023-08-17", tick=False) as frozen_time:frozen_time.shift(NOTIFICATION_HISTORY_WINDOW + timedelta(days=1))diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex d4840d6e8b73..e8008ba3cdfe 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -18,6 +18,7 @@ from django.utils import timezoneimport structlogfrom prometheus_client import Counter+from posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.activity_logging.utils import (ACTIVITY_LOG_CLIENT_MAX_LENGTH,@@ -284,6 +285,63 @@ class ActivityLog(UUIDTModel):detail = models.JSONField(encoder=ActivityDetailEncoder, null=True)created_at = models.DateTimeField(default=timezone.now)+ @property+ def safe_detail(self) -> Optional[dict[str, Any]]:+ """The detail with the values of masked fields hidden, including rows written before the mask."""+ masked_fields = {+ *field_with_masked_contents.get(cast(AuditableScope, self.scope), []),+ *read_masked_fields.get(self.scope, []),+ }+ if not masked_fields or not isinstance(self.detail, dict) or not isinstance(self.detail.get("changes"), list):+ return self.detail+ changes = []+ for change in self.detail["changes"]:+ if isinstance(change, dict) and change.get("field") in masked_fields:+ masked = mask_change_values(self.scope, change["field"], change.get("before"), change.get("after"))+ change = {**change, "before": masked.before, "after": masked.after}+ changes.append(change)+ return {**self.detail, "changes": changes}+++# Fields older rows still hold in plaintext although new rows no longer record them.+read_masked_fields: dict[str, list[str]] = {+ # Site functions inline their input values into the compiled JavaScript.+ "HogFunction": ["transpiled"],+}++# Fields whose keys stay readable, so a reader still sees which entry changed.+key_masked_fields: dict[str, list[str]] = {+ "HogFunction": ["inputs"],+}+++@frozen+class MaskedChange:+ before: Any+ after: Any+++def mask_change_values(scope: str, field: str, before: Any, after: Any) -> MaskedChange:+ """Hide a masked field's values. A key-masked field keeps its keys and marks the changed ones."""+ if field in key_masked_fields.get(scope, []) and isinstance(before or {}, dict) and isinstance(after or {}, dict):+ before_values = before or {}+ after_values = after or {}+ masked_before = dict.fromkeys(before_values, "masked") if before is not None else None+ masked_after = (+ {+ key: "masked"+ if key in before_values+ and json.dumps(before_values[key], sort_keys=True, default=str)+ == json.dumps(value, sort_keys=True, default=str)+ else "changed"+ for key, value in after_values.items()+ }+ if after is not None+ else None+ )+ return MaskedChange(before=masked_before, after=masked_after)+ return MaskedChange(before="masked" if before is not None else None, after="masked" if after is not None else None)+common_field_exclusions = ["id",@@ -303,6 +361,8 @@ common_field_exclusions = [field_with_masked_contents: dict[AuditableScope, list[str]] = {"AccountView": ["name", "content", "text_content"],"HogFunction": [+ "inputs",+ "mappings",# Encrypted secret inputs (Fernet ciphertext) — a diff would be noise at best and# leak-adjacent at worst; record that they changed, never the values."encrypted_inputs",@@ -724,7 +784,11 @@ field_exclusions: dict[AuditableScope, list[str]] = {"errors_calculating",],"HogFunction": [+ # Compiled output of `hog`, which the diff records on its own. For site functions the+ # transpiled JavaScript also inlines the input values that `field_with_masked_contents`+ # hides, so a diff of it would put those values back into the log."bytecode",+ "transpiled","icon_url",# Bookkeeping for the draft/revision cycle: `draft` already records that config was staged,# and the per-version audit lives in the revisions endpoints.@@ -1160,8 +1224,13 @@ def changes_between(left_is_none = left is None or (empty_values is not None and left in empty_values)right_is_none = right is None or (empty_values is not None and right in empty_values)- left_value = "masked" if field_name in masked_fields else left- right_value = "masked" if field_name in masked_fields else right+ change_values = (+ mask_change_values(model_type, field_name, left, right)+ if field_name in masked_fields+ else MaskedChange(before=left, after=right)+ )+ left_value = change_values.before+ right_value = change_values.after# Use the override name if it existsdisplay_name = field_name_overrides.get(model_type, {}).get(field_name, field_name)diff --git a/posthog/models/activity_logging/serializers.py b/posthog/models/activity_logging/serializers.pyindex 0e0f9710f038..82c08f0cf7b9 100644--- a/posthog/models/activity_logging/serializers.py+++ b/posthog/models/activity_logging/serializers.py@@ -49,7 +49,7 @@ class ActivityLogSerializer(serializers.Serializer):activity = serializers.CharField(read_only=True)scope = serializers.CharField(read_only=True)item_id = serializers.CharField(read_only=True)- detail = DetailSerializer(required=False)+ detail = DetailSerializer(source="safe_detail", required=False)created_at = serializers.DateTimeField(read_only=True)is_system = serializers.BooleanField(read_only=True, help_text="Whether the activity was performed by the system rather than a user."diff --git a/products/cdp/backend/api/test/test_hog_function_drafts.py b/products/cdp/backend/api/test/test_hog_function_drafts.pyindex 31bdf5768892..5bcba7b22858 100644--- a/products/cdp/backend/api/test/test_hog_function_drafts.py+++ b/products/cdp/backend/api/test/test_hog_function_drafts.py@@ -6,6 +6,7 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import status+from posthog.cdp.templates.helpers import mock_transpilefrom posthog.models.activity_logging.activity_log import ActivityLogfrom products.cdp.backend.api.hog_function import HogFunctionViewSet@@ -324,6 +325,60 @@ class TestHogFunctionDrafts(DraftTestCase):assert stored_draft is not Noneassert "token" not in stored_draft["inputs"]+ @parameterized.expand([("inputs",), ("mappings",)])+ def test_input_values_are_masked_in_activity_logs(self, field: str) -> None:+ function_id = self._create(enabled=False)+ payload = (+ {"inputs": {"url": {"value": "https://example.com/private-input"}, "token": {"secret": True}}}+ if field == "inputs"+ else {+ "mappings": [+ {+ "inputs_schema": [{"key": "message", "type": "string"}],+ "inputs": {"message": {"value": "example-private-input"}},+ }+ ]+ }+ )++ self._live_edit(function_id, payload)++ logs = ActivityLog.objects.filter(+ team_id=self.team.id, scope="HogFunction", item_id=function_id, activity="updated"+ )+ changes = [+ change+ for log in logs+ for change in (log.detail["changes"] if log.detail else [])+ if change["field"] == field+ ]+ assert changes+ if field == "inputs":+ assert all(change["after"]["url"] == "changed" for change in changes)+ assert all(set(change["after"].values()) <= {"masked", "changed"} for change in changes)+ else:+ assert all(change["after"] == "masked" for change in changes)+ assert all("private-input" not in str(log.detail) for log in logs)++ @patch("posthog.cdp.site_functions.transpile", side_effect=mock_transpile)+ def test_site_function_transpiled_output_is_not_written_to_activity_logs(self, _mock_transpile) -> None:+ function_id = self._create(+ type="site_destination",+ hog="export function onEvent() {}",+ inputs_schema=[{"key": "url", "type": "string", "label": "Webhook URL", "required": True}],+ inputs={"url": {"value": "https://example.com/private-input"}},+ )++ self._live_edit(function_id, {"hog": "export function onEvent() { return 1; }"})++ logs = ActivityLog.objects.filter(+ team_id=self.team.id, scope="HogFunction", item_id=function_id, activity="updated"+ )+ changed_fields = {change["field"] for log in logs for change in (log.detail["changes"] if log.detail else [])}+ assert "hog" in changed_fields+ assert "transpiled" not in changed_fields+ assert all("private-input" not in str(log.detail) for log in logs)+def test_enabling_with_a_draft_open_is_refused_for_coercible_booleans(self):function_id = self._create()self._stage(function_id, {"hog": EDITED_HOG})