: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): validate destination inputs and protect stored secrets (#102673)
Daniel Marchuk21d4b7b23192
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.mdindex bbcd6cd5a8d1..fe7bbc7e57ce 100644--- a/docs/internal/activity-logging.md+++ b/docs/internal/activity-logging.md@@ -135,6 +135,15 @@ The activity log API, the advanced activity logs API and its exports, the notifiThe `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.+Destination mappings do not support secret inputs.+Set secrets in the destination's top-level inputs so encryption and masking also apply to drafts and revisions.+The API rejects mapping schemas that declare secret inputs before it validates their values.+Input schema keys must be unique, including in mappings and workflow function inputs.+Changing an input from secret to non-secret does not copy its stored value into plaintext storage.+An explicit replacement value can be stored as a non-secret input.+Existing duplicate input keys do not block disabling or deleting a destination, but requests cannot add a duplicate key.+Destination, draft, and revision responses mask secret mapping values from old records, including defaults.+New browser configuration builds leave out a site function while one of its secret values would reach the browser.That covers a secret still stored in plaintext inputs, and a mapping secret or its default.Regenerate existing browser configurations after deployment to replace cached JavaScript.diff --git a/posthog/cdp/test/test_validation.py b/posthog/cdp/test/test_validation.pyindex 3e8c3e229ffb..ce548ccd55fa 100644--- a/posthog/cdp/test/test_validation.py+++ b/posthog/cdp/test/test_validation.py@@ -12,9 +12,10 @@ from posthog.hogql import astfrom posthog.cdp.filters import RUNTIME_CONTRACTfrom posthog.cdp.validation import (+ FunctionInputsSerializer,HogFunctionFiltersSerializer,InputsSchemaItemSerializer,- MappingsSerializer,+ InputsSchemaSerializer,RecordAliasRewriter,compile_hog,generate_template_bytecode,@@ -28,7 +29,7 @@ from common.hogvm.python.operation import HOGQL_BYTECODE_VERSIONdef validate_inputs(schema, inputs, function_type="destination", is_dwh_source=False, context_extra=None):- serializer = MappingsSerializer(+ serializer = FunctionInputsSerializer(data={"inputs_schema": schema,"inputs": inputs,@@ -146,6 +147,24 @@ class TestHogFunctionValidation(ClickhouseTestMixin, APIBaseTest, QueryMatchingT},]+ @parameterized.expand(+ [("same", ["message", "message"]), ("whitespace", ["message", " message "]), ("coerced", [42, "42"])]+ )+ def test_duplicate_input_schema_keys_are_rejected(self, _name: str, keys: list[str | int]) -> None:+ with self.assertRaisesMessage(ValidationError, "Each input key must be unique"):+ InputsSchemaSerializer().run_validation([{"key": key, "type": "string"} for key in keys])++ @parameterized.expand([("boolean", False), ("string", "false"), ("zero", "0")])+ def test_false_secret_flags_do_not_restore_stored_values(self, _name: str, secret_flag: bool | str) -> None:+ assert (+ validate_inputs(+ [{"key": "credential", "type": "string", "secret": secret_flag}],+ {},+ context_extra={"encrypted_inputs": {"credential": {"value": "example-private-value"}}},+ )+ == {}+ )+def test_validate_inputs(self):inputs_schema = create_example_inputs_schema()inputs = create_example_inputs()@@ -899,7 +918,7 @@ class TestHogFunctionValidation(ClickhouseTestMixin, APIBaseTest, QueryMatchingT},),]:- serializer = MappingsSerializer(+ serializer = FunctionInputsSerializer(data={"inputs_schema": inputs_schema,"inputs": inputs,@@ -926,7 +945,7 @@ class TestHogFunctionValidation(ClickhouseTestMixin, APIBaseTest, QueryMatchingT{"key": "secret_field", "type": "string", "required": True, "secret": True},]- serializer = MappingsSerializer(+ serializer = FunctionInputsSerializer(data={"inputs_schema": inputs_schema,"inputs": {"secret_field": input_value},diff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.pyindex 709411f7e862..c7179825b626 100644--- a/posthog/cdp/validation.py+++ b/posthog/cdp/validation.py@@ -649,6 +649,59 @@ class InputsSchemaItemSerializer(serializers.Serializer):# TODO Validate choices if type=choice+DUPLICATE_INPUT_KEYS_ERROR = "Each input key must be unique. Remove duplicate keys."+++def duplicate_input_keys(schemas: Any) -> set[str]:+ seen: set[str] = set()+ duplicates: set[str] = set()+ for schema in schemas or []:+ if not isinstance(schema, dict) or "key" not in schema:+ continue+ key = str(schema["key"]).strip()+ if key in seen:+ duplicates.add(key)+ seen.add(key)+ return duplicates+++def added_duplicate_input_keys(schemas: Any, stored_schemas: Any) -> set[str]:+ """Keys the schema repeats more often than the stored schema already did."""++ def counts(items: Any) -> dict[str, int]:+ result: dict[str, int] = {}+ for schema in items or []:+ if isinstance(schema, dict) and "key" in schema:+ key = str(schema["key"]).strip()+ result[key] = result.get(key, 0) + 1+ return result++ stored = counts(stored_schemas)+ return {key for key, count in counts(schemas).items() if count > 1 and count > stored.get(key, 0)}+++class InputsSchemaSerializer(serializers.ListField):+ """A function's input schema.++ Turn `unique_keys` off wherever the caller does not always send the schema. The hog function+ serializer injects the stored schema into every update, so a row saved before this rule would+ fail a request that only disables or deletes it. That serializer checks uniqueness itself and+ compares against the stored schema.+ """++ child = InputsSchemaItemSerializer()++ def __init__(self, *args: Any, unique_keys: bool = True, **kwargs: Any) -> None:+ self.unique_keys = unique_keys+ super().__init__(*args, **kwargs)++ def to_internal_value(self, data: Any) -> list[dict[str, Any]]:+ schemas = super().to_internal_value(data)+ if self.unique_keys and duplicate_input_keys(schemas):+ raise serializers.ValidationError(DUPLICATE_INPUT_KEYS_ERROR)+ return schemas++@extend_schema_field({})class AnyInputField(serializers.Field):def to_internal_value(self, data):@@ -903,6 +956,9 @@ class InputsSerializer(serializers.DictField):except:raise serializers.ValidationError("Missing inputs_schema.")+ assert isinstance(parent_serializer, serializers.Serializer)+ inputs_schema = parent_serializer.fields["inputs_schema"].run_validation(inputs_schema)+# Validate each input against the schemafor schema in inputs_schema:key = str(schema["key"])@@ -1128,11 +1184,9 @@ class HogFunctionFiltersSerializer(serializers.Serializer):return data-class MappingsSerializer(serializers.Serializer):- name = serializers.CharField(required=False)- inputs_schema = serializers.ListField(child=InputsSchemaItemSerializer(), required=False)+class FunctionInputsSerializer(serializers.Serializer):+ inputs_schema = InputsSchemaSerializer(required=False)inputs = InputsSerializer(required=False)- filters = HogFunctionFiltersSerializer(required=False)def to_internal_value(self, data):# Weirdly nested serializers don't get this set...@@ -1140,6 +1194,29 @@ class MappingsSerializer(serializers.Serializer):return super().to_internal_value(data)+class MappingsSerializer(FunctionInputsSerializer):+ name = serializers.CharField(required=False)+ filters = HogFunctionFiltersSerializer(required=False)+ # The hog function serializer compares repeated keys against the stored mappings, because the UI+ # resends every mapping on each save and some stored mappings already repeat a key.+ inputs_schema = InputsSchemaSerializer(required=False, unique_keys=False)++ def to_internal_value(self, data: Any) -> dict[str, Any]:+ if isinstance(data, dict) and "inputs_schema" in data:+ try:+ inputs_schema = self.fields["inputs_schema"].run_validation(data["inputs_schema"])+ except ValidationError as error:+ raise serializers.ValidationError({"inputs_schema": error.detail}) from error+ if any(schema.get("secret") for schema in inputs_schema):+ raise serializers.ValidationError(+ {+ "inputs_schema": "Mappings do not support secret inputs. Set secrets in the destination inputs instead."+ }+ )+ data = {**data, "inputs_schema": inputs_schema}+ return super().to_internal_value(data)++def topological_sort(nodes: list[str], edges: dict[str, list[str]]) -> list[str]:"""Perform a topological sort on the given graph.diff --git a/posthog/models/test/test_hog_function.py b/posthog/models/test/test_hog_function.pyindex 8a691fa68e52..032742c72ea4 100644--- a/posthog/models/test/test_hog_function.py+++ b/posthog/models/test/test_hog_function.py@@ -6,6 +6,8 @@ from unittest.mock import Mock, patchfrom django.test import TestCase+from parameterized import parameterized+from posthog.cdp.filters import RUNTIME_CONTRACTfrom posthog.models.file_system.file_system import FileSystemfrom posthog.models.team.team import Team@@ -39,6 +41,30 @@ class TestHogFunction(TestCase):assert item.hog == ""assert not item.enabled+ @parameterized.expand(+ [("secret_last", [False, True]), ("secret_first", [True, False]), ("no_longer_secret", [False])]+ )+ def test_stored_secrets_never_move_to_plaintext(self, _name: str, secret_flags: list[bool]) -> None:+ secret = {"value": "example-private-value"}+ function = HogFunction.objects.create(+ team=self.team,+ name="Secret storage",+ type="destination",+ inputs_schema=[{"key": "credential", "type": "string", "secret": True}],+ inputs={"credential": secret},+ )+ function.inputs_schema = [+ {"key": "message", "type": "string"},+ *[{"key": "credential", "type": "string", "secret": secret_flag} for secret_flag in secret_flags],+ ]+ function.inputs = {"credential": secret, "message": {"value": "example-public-value"}}++ function.save()++ function.refresh_from_db()+ assert function.inputs == {"message": {"value": "example-public-value"}}+ assert (function.encrypted_inputs or {}) == ({"credential": secret} if any(secret_flags) else {})+def test_hog_function_team_no_filters_compilation(self):item = HogFunction.objects.create(name="Test", team=self.team, type="destination")diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.pyindex 47850e2cbdf0..4aea8085c39a 100644--- a/products/cdp/backend/api/hog_function.py+++ b/products/cdp/backend/api/hog_function.py@@ -1,4 +1,5 @@import json+from copy import deepcopyfrom datetime import timedeltafrom typing import Any, Optional, cast@@ -37,10 +38,12 @@ from posthog.cdp.internal_events import (from posthog.cdp.services.icons import CDPIconsServicefrom posthog.cdp.site_functions import get_transpiled_functionfrom posthog.cdp.validation import (+ DUPLICATE_INPUT_KEYS_ERROR,HogFunctionFiltersSerializer,- InputsSchemaItemSerializer,+ InputsSchemaSerializer,InputsSerializer,MappingsSerializer,+ added_duplicate_input_keys,compile_hog,generate_template_bytecode,masked_secret_input_keys,@@ -158,6 +161,25 @@ def split_content_secrets(content: dict) -> dict:return {key: value for key, value in inputs.items() if key in secret_keys}+def mask_config_secrets(content: dict) -> dict:+ content = deepcopy(content)+ for config in [content, *(content.get("mappings") or [])]:+ if not isinstance(config, dict):+ continue+ schemas = config.get("inputs_schema") or []+ secret_keys = {schema["key"] for schema in schemas if schema.get("secret") and "key" in schema}+ for schema in schemas:+ if schema.get("key") in secret_keys:+ schema.pop("default", None)+ inputs = config.get("inputs") or {}+ for key in secret_keys:+ if key in inputs:+ inputs[key] = {"secret": True}+ if secret_keys and "transpiled" in content:+ content["transpiled"] = None+ return content++def snapshot_hog_function_content(hog_function: HogFunction) -> dict:snapshot = {field: getattr(hog_function, field) for field in DRAFT_CONTENT_FIELDS}# Defensively strip: a row written before secret inputs were encrypted still has plaintext@@ -347,6 +369,15 @@ class HogFunctionMaskingSerializer(serializers.Serializer):return super().validate(attrs)+def _stored_mapping_for(mapping: dict, index: int, stored_mappings: list[dict]) -> Optional[dict]:+ # Only a stored mapping with the same name counts as this mapping's earlier version. Position breaks+ # ties between equal names, so a new mapping placed where an old one was cannot take its allowance.+ candidates = [stored for stored in stored_mappings if stored.get("name") == mapping.get("name")]+ if index < len(stored_mappings) and any(stored is stored_mappings[index] for stored in candidates):+ return stored_mappings[index]+ return candidates[0] if len(candidates) == 1 else None++_AlertMarkers = tuple[frozenset[tuple[object, object]], frozenset[str]]@@ -394,9 +425,9 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):allow_null=True,help_text="Function type: destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, transformation, or transformation_log.",)- inputs_schema = serializers.ListField(- child=InputsSchemaItemSerializer(required=True),+ inputs_schema = InputsSchemaSerializer(required=False,+ unique_keys=False,help_text="Schema defining the configurable input parameters for this function.",)inputs = InputsSerializer(required=False, help_text="Values for each input defined in inputs_schema.")@@ -665,6 +696,19 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):current_filters = instance.filters if isinstance(instance, HogFunction) else {}proposed_filters = attrs.get("filters", current_filters)+ # `to_internal_value` injects the stored schema whenever the request omits it, so the field+ # itself cannot reject duplicate keys: a row saved before the rule could no longer be+ # disabled or deleted. Only keys this request adds a duplicate of are rejected.+ if added_duplicate_input_keys(attrs.get("inputs_schema"), instance.inputs_schema if instance else None):+ raise serializers.ValidationError({"inputs_schema": DUPLICATE_INPUT_KEYS_ERROR})+ stored_mappings = [m for m in (instance.mappings if instance else None) or [] if isinstance(m, dict)]+ for index, mapping in enumerate(attrs.get("mappings") or []):+ stored_mapping = _stored_mapping_for(mapping, index, stored_mappings)+ if added_duplicate_input_keys(mapping.get("inputs_schema"), (stored_mapping or {}).get("inputs_schema")):+ raise serializers.ValidationError(+ {"mappings": {str(index): {"inputs_schema": [DUPLICATE_INPUT_KEYS_ERROR]}}}+ )+if not self.context.get("allow_managed_alert_destination"):# The alert API owns which alert a destination belongs to and removes a destination group# as a whole; a removed one is added back there, not restored here. Everything else about@@ -819,7 +863,7 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):data["inputs"] = inputsdata["draft"] = self._mask_draft_secrets(data.get("draft"), draft_encrypted_inputs, encrypted_inputs)- return data+ return mask_config_secrets(data)@staticmethoddef _mask_draft_secrets(@@ -838,7 +882,7 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):continueif draft_encrypted_inputs.get(key) or encrypted_inputs.get(key) or inputs.get(key):inputs[key] = {"secret": True}- return {**draft, "inputs": inputs}+ return mask_config_secrets({**draft, "inputs": inputs})def create(self, validated_data: dict, *args, **kwargs) -> HogFunction:# An in-process caller has no request to take the acting user from, so it passes@@ -891,6 +935,23 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):highest_order = self._get_highest_execution_order(instance.team_id, instance.type)validated_data["execution_order"] = highest_order + 1+ # `move_secret_inputs` keeps a stored secret out of the plaintext column by refusing any key+ # that still has an encrypted value, and the save has no request to tell a replacement the+ # caller typed from the secret it must not expose, so that value would reach neither column.+ # Drop the superseded entry here, where the request says which keys carry a real value.+ # A staged edit saves only its metadata here, so its inputs must not touch the live secrets.+ supplied = (+ explicit_secret_input_keys(getattr(self, "initial_data", {}).get("inputs"))+ if "inputs" in validated_data+ else set()+ )+ schemas = validated_data.get("inputs_schema", instance.inputs_schema) or []+ secret_keys = {schema["key"] for schema in schemas if schema.get("secret")}+ stored_secrets = instance.encrypted_inputs or {}+ superseded = (supplied - secret_keys) & stored_secrets.keys()+ if superseded:+ instance.encrypted_inputs = {key: value for key, value in stored_secrets.items() if key not in superseded}+# Standard updateres: HogFunction = super().update(instance, validated_data)@@ -947,6 +1008,11 @@ class HogFunctionRevisionSerializer(HogFunctionRevisionBasicSerializer):fields = [*HogFunctionRevisionBasicSerializer.Meta.fields, "content"]read_only_fields = fields+ def to_representation(self, instance: HogFunctionRevision) -> dict:+ data = super().to_representation(instance)+ data["content"] = mask_config_secrets(data["content"])+ return data+class HogFunctionRevisionRestoreRequestSerializer(serializers.Serializer):overwrite = serializers.BooleanField(diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.pyindex ea3202358521..8cde4005fb26 100644--- a/products/cdp/backend/api/test/test_hog_function.py+++ b/products/cdp/backend/api/test/test_hog_function.py@@ -1298,6 +1298,161 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert obj.encrypted_inputs["secret1"]["value"] == "I AM SECRET"assert obj.encrypted_inputs["secret2"]["value"] == "I AM ALSO SECRET"+ def test_secret_input_turned_public_keeps_a_new_value(self, *args):+ payload = {+ "type": "destination",+ "name": "Fetch URL",+ "hog": "fetch(inputs.url);",+ "inputs_schema": [{"key": "token", "type": "string", "label": "Token", "secret": True, "required": True}],+ "inputs": {"token": {"value": "I AM SECRET"}},+ }+ res = self.client.post(f"/api/projects/{self.team.id}/hog_functions/", data=payload)+ function_id = res.json()["id"]++ res = self.client.patch(+ f"/api/projects/{self.team.id}/hog_functions/{function_id}",+ data={+ "inputs_schema": [{"key": "token", "type": "string", "label": "Token", "required": True}],+ "inputs": {"token": {"value": "I AM PUBLIC NOW"}},+ },+ )++ assert res.status_code == status.HTTP_200_OK, res.json()+ assert res.json()["inputs"]["token"]["value"] == "I AM PUBLIC NOW"+ obj = HogFunction.objects.get(id=function_id)+ assert (obj.inputs or {})["token"]["value"] == "I AM PUBLIC NOW"+ assert (obj.encrypted_inputs or {}) == {}++ @parameterized.expand(+ [("disable", {"enabled": False}), ("delete", {"deleted": True}), ("rename", {"name": "Renamed"})]+ )+ def test_stored_duplicate_input_keys_do_not_block_updates(self, _name: str, payload: dict) -> None:+ function = HogFunction.objects.create(+ team=self.team,+ name="Legacy duplicates",+ type="destination",+ enabled=True,+ hog="print(inputs.message)",+ inputs_schema=[{"key": "message", "type": "string"}, {"key": "message", "type": "string"}],+ inputs={"message": {"value": "hello"}},+ )++ res = self.client.patch(f"/api/projects/{self.team.id}/hog_functions/{function.id}", data=payload)++ assert res.status_code == status.HTTP_200_OK, res.json()++ @parameterized.expand(+ [+ ("resend_stored_mapping", [], False, status.HTTP_200_OK),+ ("add_duplicate_to_mapping", [{"key": "added", "type": "string"}] * 2, False, status.HTTP_400_BAD_REQUEST),+ ("add_third_copy", [{"key": "click_id", "type": "string"}], False, status.HTTP_400_BAD_REQUEST),+ ("new_mapping_repeats_key", [], True, status.HTTP_400_BAD_REQUEST),+ ("new_mapping_in_the_stored_position", [], "replace", status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_stored_duplicate_mapping_keys_do_not_block_full_saves(+ self, _name: str, extra_schema: list[dict], add_mapping: bool | str, expected_status: int+ ) -> None:+ mapping = {+ "name": "Signed up",+ "inputs_schema": [{"key": "click_id", "type": "string"}, {"key": "click_id", "type": "string"}],+ "inputs": {"click_id": {"value": "{event.properties.click_id}"}},+ }+ function = HogFunction.objects.create(+ team=self.team,+ name="Legacy mapping duplicates",+ type="destination",+ hog="print(inputs.click_id)",+ inputs_schema=[],+ inputs={},+ mappings=[mapping],+ )++ res = self.client.patch(+ f"/api/projects/{self.team.id}/hog_functions/{function.id}",+ data={+ "name": "Renamed",+ "mappings": (+ [{**mapping, "name": "Logged in"}]+ if add_mapping == "replace"+ else [+ {**mapping, "inputs_schema": [*mapping["inputs_schema"], *extra_schema]},+ *([{**mapping, "name": "Logged in"}] if add_mapping else []),+ ]+ ),+ },+ )++ assert res.status_code == expected_status, res.json()+ if expected_status == status.HTTP_400_BAD_REQUEST:+ assert res.json()["attr"] == f"mappings__{1 if add_mapping is True else 0}__inputs_schema"++ @parameterized.expand(+ [+ ("clean", ["message"], ["added", "added"]),+ ("already_duplicated", ["message", "message"], ["added", "added"]),+ ("third_copy", ["message", "message"], ["message"]),+ ]+ )+ def test_newly_duplicated_input_key_is_rejected(+ self, _name: str, stored_keys: list[str], added_keys: list[str]+ ) -> None:+ function = HogFunction.objects.create(+ team=self.team,+ name="Legacy duplicates",+ type="destination",+ hog="print(inputs.message)",+ inputs_schema=[{"key": key, "type": "string"} for key in stored_keys],+ inputs={"message": {"value": "hello"}},+ )++ res = self.client.patch(+ f"/api/projects/{self.team.id}/hog_functions/{function.id}",+ data={+ "inputs_schema": [+ *({"key": key, "type": "string"} for key in [*stored_keys, *added_keys]),+ ]+ },+ )++ assert res.status_code == status.HTTP_400_BAD_REQUEST, res.json()+ assert res.json()["detail"] == "Each input key must be unique. Remove duplicate keys."++ @parameterized.expand(+ [("rename", {"name": "Renamed"}), ("disable", {"enabled": False}), ("delete", {"deleted": True})]+ )+ def test_stored_secret_mapping_does_not_block_updates(self, _name: str, payload: dict) -> None:+ mappings = [+ {+ "name": "Secret mapping",+ "inputs_schema": [{"key": "token", "type": "string", "label": "Token", "secret": True}],+ "inputs": {"token": {"value": "legacy-plaintext-value"}},+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},+ }+ ]+ function = HogFunction.objects.create(+ team=self.team,+ name="Legacy secret mapping",+ type="destination",+ enabled=True,+ hog="print(inputs.token)",+ inputs_schema=[],+ mappings=mappings,+ )++ res = self.client.patch(+ f"/api/projects/{self.team.id}/hog_functions/{function.id}",+ data={"mappings": mappings},+ )+ assert res.status_code == status.HTTP_400_BAD_REQUEST, res.json()++ res = self.client.patch(+ f"/api/projects/{self.team.id}/hog_functions/{function.id}",+ data=payload,+ )++ assert res.status_code == status.HTTP_200_OK, res.json()+def test_secret_inputs_updated_if_changed(self, *args):payload = {"type": "destination",@@ -2215,7 +2370,25 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):}}- def test_validates_mappings(self):+ @parameterized.expand(+ [+ ("required", {"required": True}, "inputs__required_field", "This field is required."),+ ("duplicate", {"key": "message"}, "inputs_schema", "Each input key must be unique. Remove duplicate keys."),+ (+ "secret",+ {"secret": True},+ "inputs_schema",+ "Mappings do not support secret inputs. Set secrets in the destination inputs instead.",+ ),+ (+ "secret_string",+ {"secret": "true"},+ "inputs_schema",+ "Mappings do not support secret inputs. Set secrets in the destination inputs instead.",+ ),+ ]+ )+ def test_validates_mappings(self, _name: str, schema_options: dict, error_attr: str, error_detail: str) -> None:payload = {"name": "TypeScript Destination Function","hog": "export function onLoad() { console.log(inputs.message); }",@@ -2225,7 +2398,7 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):"inputs": {"message": {"value": "Hello, TypeScript {arrayMap(a -> a, [1, 2, 3])}!"}},"inputs_schema": [{"key": "message", "type": "string", "label": "Message", "required": True},- {"key": "required_field", "type": "string", "label": "Required", "required": True},+ {"key": "required_field", "type": "string", "label": "Required", **schema_options},],},],@@ -2243,11 +2416,12 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert response.json() == {"type": "validation_error","code": "invalid_input",- "detail": "This field is required.",- "attr": "mappings__0__inputs__required_field",+ "detail": error_detail,+ "attr": f"mappings__0__{error_attr}",}- def test_compiles_valid_mappings(self):+ @parameterized.expand([("default", {}), ("false", {"secret": False}), ("string_false", {"secret": "false"})])+ def test_compiles_valid_mappings(self, _name: str, schema_options: dict) -> None:payload = {"name": "TypeScript Destination Function","hog": "print(inputs.message)",@@ -2256,7 +2430,7 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):{"inputs": {"message": {"value": "Hello, {arrayMap(a -> a, [1, 2, 3])}!"}},"inputs_schema": [- {"key": "message", "type": "string", "label": "Message", "required": True},+ {"key": "message", "type": "string", "label": "Message", "required": True, **schema_options},],"filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}],diff --git a/products/cdp/backend/api/test/test_hog_function_drafts.py b/products/cdp/backend/api/test/test_hog_function_drafts.pyindex 5bcba7b22858..f1433e168288 100644--- a/products/cdp/backend/api/test/test_hog_function_drafts.py+++ b/products/cdp/backend/api/test/test_hog_function_drafts.py@@ -18,7 +18,7 @@ RELOAD_PATH = "products.cdp.backend.models.hog_functions.hog_function.reload_hogLIVE_HOG = "fetch(inputs.url);"EDITED_HOG = "fetch(inputs.url, {'method': 'PUT'});"-BASE_FUNCTION = {+BASE_FUNCTION: dict[str, Any] = {"name": "Webhook","type": "destination","hog": LIVE_HOG,@@ -131,13 +131,23 @@ class TestHogFunctionDrafts(DraftTestCase):def test_agent_metadata_in_a_config_edit_still_applies_live(self):function_id = self._create()- self._stage(function_id, {"name": "Renamed", "enabled": False, "filters": {"source": "events"}})+ self._stage(+ function_id,+ {+ "name": "Renamed",+ "enabled": False,+ "filters": {"source": "events"},+ "inputs": {"url": {"value": "https://example.com/live"}, "token": {"value": "rotated-token"}},+ },+ )function = HogFunction.objects.get(id=function_id)assert function.name == "Renamed"assert function.enabled is Falseassert function.draft is not Noneassert function.draft["filters"]["source"] == "events"+ assert function.encrypted_inputs["token"]["value"] == "live-token"+ assert function.draft_encrypted_inputs["token"]["value"] == "rotated-token"def test_metadata_in_a_draft_edit_does_not_revert_a_concurrent_live_edit(self):function_id = self._create()@@ -379,6 +389,103 @@ class TestHogFunctionDrafts(DraftTestCase):assert "transpiled" not in changed_fieldsassert all("private-input" not in str(log.detail) for log in logs)+ @parameterized.expand(+ [+ ("live_secret_last", False, [False, True]),+ ("live_secret_first", False, [True, False]),+ ("draft_secret_last", True, [False, True]),+ ("draft_secret_first", True, [True, False]),+ ("enabled_raw_api_secret_last", True, [False, True], False),+ ("enabled_raw_api_secret_first", True, [True, False], False),+ ]+ )+ def test_duplicate_input_keys_are_rejected(+ self, _name: str, enabled: bool, secret_flags: list[bool], from_agent: bool = True+ ) -> None:+ function_id = self._create(enabled=enabled)+ function = HogFunction.objects.get(id=function_id)+ saved_inputs = function.inputs+ saved_secrets = function.encrypted_inputs+ revision_count = self._revisions(function_id).count()+ logs = ActivityLog.objects.filter(team_id=self.team.id, scope="HogFunction", item_id=function_id)+ log_count = logs.count()++ payload = {+ "inputs_schema": [+ BASE_FUNCTION["inputs_schema"][0],+ *[{"key": "token", "type": "string", "secret": secret} for secret in secret_flags],+ ]+ }+ response = (+ self._agent_patch(function_id, payload)+ if from_agent+ else self.client.patch(self._url(function_id), payload)+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "inputs_schema"+ function.refresh_from_db()+ assert function.inputs == saved_inputs+ assert function.encrypted_inputs == saved_secrets+ assert function.draft is None+ assert self._revisions(function_id).count() == revision_count+ assert logs.count() == log_count+ assert all("live-token" not in str(log.detail) for log in logs)+ response = self.client.get(self._url(function_id))+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["inputs"]["token"] == {"secret": True}+ assert "live-token" not in response.content.decode()++ @parameterized.expand(+ [+ ("live_mask", False, {"secret": True}),+ ("draft_mask", True, {"secret": True}),+ ("draft_display_mask", True, {"secret": True, "value": "********"}),+ ("draft_empty", True, {}),+ ("draft_new_value", True, {"value": "example-mapping-token"}),+ ("draft_schema_only", True, None),+ ]+ )+ def test_mapping_secret_inputs_are_rejected(self, _name: str, enabled: bool, input_value: dict | None) -> None:+ function_id = self._create(enabled=enabled)+ if enabled:+ self._stage(+ function_id,+ {+ "inputs": {+ "url": {"value": "https://example.com/live"},+ "token": {"value": "example-staged-token"},+ }+ },+ )+ function = HogFunction.objects.get(id=function_id)+ saved_draft = function.draft+ saved_secrets = function.encrypted_inputs+ saved_draft_secrets = function.draft_encrypted_inputs+ revision_count = self._revisions(function_id).count()+ mapping: dict[str, Any] = {+ "inputs_schema": [{"key": "token", "type": "string", "secret": True}],+ }+ if input_value is not None:+ mapping["inputs"] = {"token": input_value}++ response = self._agent_patch(function_id, {"mappings": [mapping]})++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "mappings__0__inputs_schema"+ function.refresh_from_db()+ assert function.mappings is None+ assert function.draft == saved_draft+ assert function.encrypted_inputs == saved_secrets+ assert function.draft_encrypted_inputs == saved_draft_secrets+ assert self._revisions(function_id).count() == revision_count+ response = self.client.get(self._url(function_id))+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["inputs"]["token"] == {"secret": True}+ for secret in ("live-token", "example-staged-token", "example-mapping-token"):+ assert secret not in response.content.decode()+ assert not self._revisions(function_id).filter(content__icontains=secret).exists()+def test_enabling_with_a_draft_open_is_refused_for_coercible_booleans(self):function_id = self._create()self._stage(function_id, {"hog": EDITED_HOG})@@ -485,6 +592,45 @@ class TestHogFunctionDrafts(DraftTestCase):class TestHogFunctionRevisions(DraftTestCase):+ @parameterized.expand([("secret_first", True), ("secret_last", False)])+ def test_legacy_mapping_secrets_are_masked_on_reads(self, _name: str, secret_first: bool) -> None:+ function_id = self._create()+ schemas = [+ {"key": "credential", "type": "string", "secret": True, "default": "example-private-default"},+ {"key": "credential", "type": "string", "default": "example-private-default"},+ ]+ if not secret_first:+ schemas.reverse()+ mappings = [+ {+ "name": "Page view",+ "inputs_schema": schemas,+ "inputs": {+ "credential": {"value": "example-private-value", "bytecode": ["example-private-value"]},+ "event_name": {"value": "page_view"},+ },+ }+ ]+ content = {"inputs_schema": [], "inputs": {}, "mappings": mappings}+ HogFunction.objects.filter(id=function_id).update(mappings=mappings, draft=content)+ function = HogFunction.objects.get(id=function_id)+ self._revisions(function_id).create(team_id=self.team.id, hog_function=function, version=1, content=content)++ for suffix in ("", "/revisions/1"):+ response = self.client.get(self._url(function_id, suffix))+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert "example-private" not in response.content.decode()+ data = response.json().get("content", response.json())+ assert data["mappings"][0]["inputs"]["credential"] == {"secret": True}+ assert data["mappings"][0]["inputs"]["event_name"] == {"value": "page_view"}+ response = self.client.get(self._url(), {"full": "true"})+ assert response.status_code == status.HTTP_200_OK+ assert "example-private" not in response.content.decode()+ function.refresh_from_db()+ assert function.mappings == mappings+ assert function.draft == content+ assert self._revisions(function_id).get(version=1).content == content+def test_first_live_config_change_also_snapshots_the_outgoing_config(self):function_id = self._create()diff --git a/products/cdp/backend/models/hog_functions/hog_function.py b/products/cdp/backend/models/hog_functions/hog_function.pyindex ac08b6eea409..09475222256b 100644--- a/products/cdp/backend/models/hog_functions/hog_function.py+++ b/products/cdp/backend/models/hog_functions/hog_function.py@@ -263,23 +263,24 @@ class HogFunction(FileSystemSyncMixin, UUIDTModel):return self.status- def move_secret_inputs(self):+ def move_secret_inputs(self) -> None:# Moves any secret inputs to the encrypted_inputs varraw_inputs = self.inputs or {}raw_encrypted_inputs = self.encrypted_inputs or {}final_inputs = {}final_encrypted_inputs = {}+ secret_keys = {schema["key"] for schema in self.inputs_schema or [] if schema.get("secret")}for schema in self.inputs_schema or []:value = raw_inputs.get(schema["key"])encrypted_value = raw_encrypted_inputs.get(schema["key"])- if not schema.get("secret"):- final_inputs[schema["key"]] = value- else:+ if schema["key"] in secret_keys:# We either store the incoming value if given or the encrypted valuefinal_encrypted_inputs[schema["key"]] = value or encrypted_value+ elif schema["key"] not in raw_encrypted_inputs:+ final_inputs[schema["key"]] = valueself.inputs = final_inputsself.encrypted_inputs = final_encrypted_inputsdiff --git a/products/cdp/frontend/generated/api.schemas.ts b/products/cdp/frontend/generated/api.schemas.tsindex e7a30f5e6efd..110533cba482 100644--- a/products/cdp/frontend/generated/api.schemas.ts+++ b/products/cdp/frontend/generated/api.schemas.ts@@ -398,9 +398,9 @@ export interface HogFunctionMaskingApi {export type MappingsApiInputs = { [key: string]: InputsItemApi }export interface MappingsApi {- name?: stringinputs_schema?: InputsSchemaItemApi[]inputs?: MappingsApiInputs+ name?: stringfilters?: HogFunctionFiltersApi}diff --git a/products/cdp/frontend/generated/api.zod.ts b/products/cdp/frontend/generated/api.zod.tsindex 4d338b283bf9..80aabdcffa98 100644--- a/products/cdp/frontend/generated/api.zod.ts+++ b/products/cdp/frontend/generated/api.zod.ts@@ -165,7 +165,6 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({mappings: zod.array(zod.object({- name: zod.string().optional(),inputs_schema: zod.array(zod.object({@@ -237,6 +236,7 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({})).optional(),+ name: zod.string().optional(),filters: zod.object({source: zod@@ -443,7 +443,6 @@ export const HogFunctionsUpdateBody = /* @__PURE__ */ zod.object({mappings: zod.array(zod.object({- name: zod.string().optional(),inputs_schema: zod.array(zod.object({@@ -515,6 +514,7 @@ export const HogFunctionsUpdateBody = /* @__PURE__ */ zod.object({})).optional(),+ name: zod.string().optional(),filters: zod.object({source: zod@@ -721,7 +721,6 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({mappings: zod.array(zod.object({- name: zod.string().optional(),inputs_schema: zod.array(zod.object({@@ -793,6 +792,7 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({})).optional(),+ name: zod.string().optional(),filters: zod.object({source: zod@@ -1003,7 +1003,6 @@ export const HogFunctionsEnableBackfillsCreateBody = /* @__PURE__ */ zod.object(mappings: zod.array(zod.object({- name: zod.string().optional(),inputs_schema: zod.array(zod.object({@@ -1081,6 +1080,7 @@ export const HogFunctionsEnableBackfillsCreateBody = /* @__PURE__ */ zod.object(})).optional(),+ name: zod.string().optional(),filters: zod.object({source: zod@@ -1372,7 +1372,6 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({mappings: zod.array(zod.object({- name: zod.string().optional(),inputs_schema: zod.array(zod.object({@@ -1450,6 +1449,7 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({})).optional(),+ name: zod.string().optional(),filters: zod.object({source: zoddiff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 439e78b8dac4..d0cac4566e2e 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -72,7 +72,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.auth import InternalAPIAuthenticationfrom posthog.cdp.filters import DATA_WAREHOUSE_SOURCES, compile_filters_exprfrom posthog.cdp.flag_gated_templates import FLAG_GATED_TEMPLATE_IDS, gated_template_enabled-from posthog.cdp.validation import HogFunctionFiltersSerializer, InputsSchemaItemSerializer, InputsSerializer+from posthog.cdp.validation import HogFunctionFiltersSerializer, InputsSchemaSerializer, InputsSerializerfrom posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.dataclasses import frozenfrom posthog.event_usage import AGENT_EVENT_SOURCES, EventSource, get_event_source, report_user_action@@ -976,7 +976,7 @@ class WorkflowStatsRowSerializer(serializers.Serializer):class HogFlowConfigFunctionInputsSerializer(serializers.Serializer):- inputs_schema = serializers.ListField(child=InputsSchemaItemSerializer(), required=False)+ inputs_schema = InputsSchemaSerializer(required=False)inputs = InputsSerializer(required=False)def to_internal_value(self, data):diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cece8f9b6aa8..960acd308cfb 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -54698,9 +54698,9 @@ export namespace Schemas {export type MappingsInputs = {[key: string]: InputsItem};export interface Mappings {- name?: string;inputs_schema?: InputsSchemaItem[];inputs?: MappingsInputs;+ name?: string;filters?: HogFunctionFilters;}diff --git a/services/mcp/src/generated/cdp_functions/api.ts b/services/mcp/src/generated/cdp_functions/api.tsindex 2c44d9e9778b..f679bc77f57c 100644--- a/services/mcp/src/generated/cdp_functions/api.ts+++ b/services/mcp/src/generated/cdp_functions/api.ts@@ -178,7 +178,6 @@ export const HogFunctionsCreateBody = () => zod.object({mappings: zod.array(zod.object({- name: zod.string().optional(),inputs_schema: zod.array(zod.object({@@ -245,6 +244,7 @@ export const HogFunctionsCreateBody = () => zod.object({})).optional(),+ name: zod.string().optional(),filters: zod.object({source: zod@@ -446,7 +446,6 @@ export const HogFunctionsPartialUpdateBody = () => zod.object({mappings: zod.array(zod.object({- name: zod.string().optional(),inputs_schema: zod.array(zod.object({@@ -513,6 +512,7 @@ export const HogFunctionsPartialUpdateBody = () => zod.object({})).optional(),+ name: zod.string().optional(),filters: zod.object({source: zod@@ -832,7 +832,6 @@ export const HogFunctionsInvocationsCreateBody = () => zod.object({mappings: zod.array(zod.object({- name: zod.string().optional(),inputs_schema: zod.array(zod.object({@@ -910,6 +909,7 @@ export const HogFunctionsInvocationsCreateBody = () => zod.object({})).optional(),+ name: zod.string().optional(),filters: zod.object({source: zoddiff --git a/services/mcp/src/generated/error_tracking_alerts/api.ts b/services/mcp/src/generated/error_tracking_alerts/api.tsindex 50f7da504017..27acc12da7fa 100644--- a/services/mcp/src/generated/error_tracking_alerts/api.ts+++ b/services/mcp/src/generated/error_tracking_alerts/api.ts@@ -178,7 +178,6 @@ export const HogFunctionsCreateBody = () => zod.object({mappings: zod.array(zod.object({- name: zod.string().optional(),inputs_schema: zod.array(zod.object({@@ -245,6 +244,7 @@ export const HogFunctionsCreateBody = () => zod.object({})).optional(),+ name: zod.string().optional(),filters: zod.object({source: zod@@ -437,7 +437,6 @@ export const HogFunctionsPartialUpdateBody = () => zod.object({mappings: zod.array(zod.object({- name: zod.string().optional(),inputs_schema: zod.array(zod.object({@@ -504,6 +503,7 @@ export const HogFunctionsPartialUpdateBody = () => zod.object({})).optional(),+ name: zod.string().optional(),filters: zod.object({source: zod