: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(workflows): stop masked re-saves wiping legacy plaintext secret inputs (#83804)
Harley Alexandera4091bbaa08a
diff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.pyindex 055e8e7db481..173a31ba4750 100644--- a/posthog/cdp/validation.py+++ b/posthog/cdp/validation.py@@ -590,7 +590,7 @@ class InputsSerializer(serializers.DictField):def run_child_validation(self, data):result = {}- errors = {}+ errors: dict[str, Any] = {}existing_secret_inputs = self.context.get("encrypted_inputs")# Note this should always be the child of a dict serializer with a sibling 'inputs_schema' field so we can validate against the relevant schema@@ -605,9 +605,20 @@ class InputsSerializer(serializers.DictField):key = str(schema["key"])value = data.get(key) or {}- # We only load the existing secret if the schema is secret and the given value has "secret" set- if schema.get("secret") and existing_secret_inputs and ((value and value.get("secret")) or value == {}):- value = existing_secret_inputs.get(schema["key"]) or {}+ if schema.get("secret"):+ # A {"secret": true} value with no "value" is the read-back mask, meaning "keep the+ # stored secret". One that also carries a "value" is a rotation and must win, so it+ # falls through to normal validation.+ is_masked = isinstance(value, dict) and bool(value.get("secret")) and "value" not in value+ if is_masked or value == {}:+ existing_value = (existing_secret_inputs or {}).get(key)+ if existing_value:+ value = existing_value+ elif is_masked:+ # Nothing stored to keep. Silently dropping the input here has disabled+ # webhook auth in production - fail so the caller re-enters the value.+ errors[key] = "No value is saved for this secret input. Enter the value again."+ continueself.context["schema"] = schemadiff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex f3b6ed4a001c..9c8623560ca7 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -323,6 +323,24 @@ def partition_flow_secrets(return stripped, encrypted+def plaintext_secret_map(actions: Any, template_cache: Optional[TemplateCache] = None) -> dict[str, dict]:+ # The secret inputs still sitting in plaintext inside an actions blob, as an {action_id: {key:+ # value}} map. Non-empty only for legacy rows written before encryption shipped - the recovery+ # base that lets a masked re-save migrate their secrets instead of wiping them.+ if not isinstance(actions, list):+ return {}+ return partition_flow_secrets(actions, template_cache)[1]+++def existing_secret_map(instance: "HogFlow", template_cache: Optional[TemplateCache] = None) -> dict[str, dict]:+ # Every stored secret a masked re-save may need to recover, later sources winning: legacy+ # plaintext (live, then draft), then the encrypted live map, then the encrypted draft map.+ result = plaintext_secret_map(instance.actions, template_cache)+ result = merge_secret_maps(result, plaintext_secret_map((instance.draft or {}).get("actions"), template_cache))+ result = merge_secret_maps(result, instance.encrypted_inputs)+ return merge_secret_maps(result, instance.draft_encrypted_inputs)++def merge_secret_maps(base: Optional[dict], overlay: Optional[dict]) -> dict[str, dict]:# Per-action, per-key merge of two {action_id: {key: value}} maps; overlay wins on conflicts.result: dict[str, dict] = {action_id: dict(values) for action_id, values in (base or {}).items()}@@ -331,6 +349,23 @@ def merge_secret_maps(base: Optional[dict], overlay: Optional[dict]) -> dict[strreturn result+def recover_or_drop_masked_inputs(inputs: Any, secret_keys: set[str], existing: dict) -> None:+ # A lenient (web draft) save keeps the raw inputs when validation fails. A {"secret": true}+ # read-back marker in that raw payload must never persist as a stored value - the worker would+ # treat the marker object as the real input (e.g. compare it against a webhook's auth header and+ # reject every request). Swap it for the stored secret, or drop the key when there is none.+ if not isinstance(inputs, dict):+ return+ for key in secret_keys:+ value = inputs.get(key)+ if isinstance(value, dict) and value.get("secret") and "value" not in value:+ stored = existing.get(key)+ if stored:+ inputs[key] = stored+ else:+ inputs.pop(key, None)++def mask_secret_action_inputs(actions: list[dict], secrets_by_action: dict[str, dict], template_cache: Optional[TemplateCache] = None) -> list[dict]:@@ -1209,6 +1244,12 @@ class HogFlowActionSerializer(serializers.Serializer):if not strict:if function_config_serializer.is_valid():data["config"]["inputs"] = function_config_serializer.validated_data["inputs"]+ else:+ recover_or_drop_masked_inputs(+ inputs,+ {schema["key"] for schema in (input_schema or []) if schema.get("secret")},+ (self.context.get("existing_encrypted_inputs") or {}).get(data.get("id")) or {},+ )else:function_config_serializer.is_valid(raise_exception=True)data["config"]["inputs"] = function_config_serializer.validated_data["inputs"]@@ -1932,13 +1973,12 @@ class HogFlowSerializer(HogFlowMinimalSerializer):self.context["is_draft"] = True# Existing decrypted secrets, keyed by action id, so child action validation can recover a- # resent {"secret": true} marker. Merge live over draft (draft wins) so an in-progress draft- # edit recovers the value the client actually saw. Must be set before super() runs, since the- # nested action serializers validate inside it.+ # resent {"secret": true} marker. Includes legacy plaintext still inside the stored actions+ # (rows written before encryption shipped) as the base, then the encrypted live and draft+ # maps (draft wins) so an in-progress draft edit recovers the value the client actually saw.+ # Must be set before super() runs, since the nested action serializers validate inside it.if instance is not None:- self.context["existing_encrypted_inputs"] = merge_secret_maps(- instance.encrypted_inputs, instance.draft_encrypted_inputs- )+ self.context["existing_encrypted_inputs"] = existing_secret_map(instance, template_cache={})# Warehouse-table triggers are row-scoped: step inputs may use the `{record.x}` alias for the# synced row. Flag it before child action validation so function-input compilation rewrites it.diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex d6222fe9ff0e..06c6632f75ad 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -6,6 +6,7 @@ from typing import Any, Optionalfrom posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import MagicMock, PropertyMock, patch+from django.core.management import call_commandfrom django.db import connectionfrom django.test import override_settings@@ -4272,6 +4273,9 @@ class TestHogFlowSecretInputs(APIBaseTest):[("resent_mask_preserves", {"secret": True}, "SUPER-SECRET"),("new_value_replaces", {"value": "ROTATED"}, "ROTATED"),+ # A client that merges its new value into the masked object it read back must win over+ # the stored value - silently keeping the old token makes rotations appear to succeed.+ ("mask_with_new_value_replaces", {"secret": True, "value": "ROTATED"}, "ROTATED"),])def test_secret_update(self, _name, api_key_input, expected_stored):@@ -4602,3 +4606,210 @@ class TestHogFlowSecretInputs(APIBaseTest):rev_inputs = next(a for a in revision["content"]["actions"] if a["type"] == "function")["config"]["inputs"]assert "api_key" not in rev_inputsassert "LEGACY-SECRET" not in json.dumps(revision)++ def _create_legacy_flow(self, status=HogFlow.State.DRAFT, trigger_secret: bool = False) -> HogFlow:+ # A row written before encryption shipped: plaintext secret still inside actions (and the+ # derived trigger, for a function-shaped trigger), encrypted_inputs never populated.+ if trigger_secret:+ trigger_config = {+ "type": "webhook",+ "template_id": _SECRET_TEMPLATE_ID,+ "inputs": {"url": {"value": "https://example.com"}, "api_key": {"value": "LEGACY-SECRET"}},+ }+ actions = [+ {"id": "trigger_node", "name": "trigger", "type": "trigger", "config": trigger_config},+ {"id": "exit_node", "name": "exit", "type": "exit", "config": {}},+ ]+ edges = [{"from": "trigger_node", "to": "exit_node", "type": "continue"}]+ else:+ trigger_config = {+ "type": "event",+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},+ }+ actions = [+ {"id": "trigger_node", "name": "trigger", "type": "trigger", "config": trigger_config},+ {+ "id": "action_1",+ "name": "action_1",+ "type": "function",+ "config": {+ "template_id": _SECRET_TEMPLATE_ID,+ "inputs": {"url": {"value": "https://example.com"}, "api_key": {"value": "LEGACY-SECRET"}},+ },+ },+ ]+ edges = [{"from": "trigger_node", "to": "action_1", "type": "continue"}]+ return HogFlow.objects.create(+ team=self.team,+ name="Legacy flow",+ status=status,+ version=1,+ actions=actions,+ trigger=trigger_config,+ edges=edges,+ )++ def test_legacy_plaintext_secret_survives_masked_resave(self):+ # The client GETs the flow (secret masked), then PUTs the same graph back. The stored secret+ # must migrate into encrypted_inputs, not be wiped because there was nothing to recover from.+ flow = self._create_legacy_flow()+ body = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow.id}").json()+ assert self._function_inputs(body)["api_key"] == {"secret": True}++ resave = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow.id}",+ {"actions": body["actions"], "edges": body["edges"]},+ )+ assert resave.status_code == 200, resave.json()++ flow.refresh_from_db()+ assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == "LEGACY-SECRET"+ stored_inputs = next(a for a in flow.actions if a["id"] == "action_1")["config"]["inputs"]+ assert "api_key" not in stored_inputs++ def test_legacy_plaintext_secret_survives_masked_graph_patch(self):+ # The programmatic path: an MCP client edits one action via /graph, echoing back the masked+ # marker it read. The stored plaintext secret must be recovered, not dropped.+ flow = self._create_legacy_flow()+ resave = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow.id}/graph",+ {+ "operations": [+ {+ "op": "update_action",+ "id": "action_1",+ "patch": {"config": {"inputs": {"api_key": {"secret": True}}}},+ }+ ]+ },+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert resave.status_code == 200, resave.json()++ flow.refresh_from_db()+ assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == "LEGACY-SECRET"+ stored_inputs = next(a for a in flow.actions if a["id"] == "action_1")["config"]["inputs"]+ assert "api_key" not in stored_inputs++ def test_legacy_webhook_trigger_auth_survives_masked_resave(self):+ # The incident shape: a pre-encryption webhook trigger whose auth secret lives in plaintext in+ # actions and the derived trigger column. A masked re-save silently removed it from every+ # column, leaving the webhook endpoint unauthenticated.+ flow = self._create_legacy_flow(trigger_secret=True)+ body = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow.id}").json()+ assert body["trigger"]["inputs"]["api_key"] == {"secret": True}++ resave = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow.id}",+ {"actions": body["actions"], "edges": body["edges"]},+ )+ assert resave.status_code == 200, resave.json()++ flow.refresh_from_db()+ assert flow.encrypted_inputs["trigger_node"]["api_key"]["value"] == "LEGACY-SECRET"+ assert "api_key" not in (flow.trigger.get("inputs") or {})+ trigger_inputs = next(a for a in flow.actions if a["id"] == "trigger_node")["config"]["inputs"]+ assert "api_key" not in trigger_inputs++ def test_masked_secret_with_no_stored_value_is_rejected_for_strict_callers(self):+ # A programmatic caller pasting a masked graph into a new flow (duplicate-by-hand) has no+ # stored value to recover. Silently creating the flow without the secret turns an authed+ # webhook into an open one - reject instead so the caller re-enters the value.+ payload = self._flow_payload()+ self._function_inputs(payload)["api_key"] = {"secret": True}+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", payload, HTTP_X_POSTHOG_CLIENT="mcp")+ assert response.status_code == 400, response.json()+ assert "api_key" in json.dumps(response.json())++ def test_lenient_draft_save_never_persists_marker_as_value(self):+ # When a web draft save fails validation, the raw inputs are kept as-is. A masked marker in+ # that raw payload must not be stored as the input's value - the worker would compare the+ # marker object against the request header and reject every webhook call.+ flow = self._create_legacy_flow()+ body = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow.id}").json()+ inputs = self._function_inputs(body)+ inputs["api_key"] = {"secret": True}+ # An unterminated hog template makes input validation fail, forcing the lenient raw-keep path.+ inputs["url"] = {"value": "{event.properties.url", "templating": "hog"}++ resave = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow.id}",+ {"actions": body["actions"], "edges": body["edges"]},+ )+ assert resave.status_code == 200, resave.json()++ flow.refresh_from_db()+ stored = json.dumps({"actions": flow.actions, "trigger": flow.trigger, "draft": flow.draft})+ assert '"secret": true' not in stored.lower()+ for secret_map in (flow.encrypted_inputs, flow.draft_encrypted_inputs):+ stored_value = ((secret_map or {}).get("action_1") or {}).get("api_key")+ assert stored_value is None or stored_value.get("value") == "LEGACY-SECRET"++ def test_legacy_secret_survives_stage_draft_and_publish(self):+ # An active legacy flow edited through the web builder: the edit stages a draft (masked+ # marker in the payload), then publish promotes it. The secret must end up encrypted on the+ # live row, not dropped along the way.+ flow = self._create_legacy_flow(status=HogFlow.State.ACTIVE)+ body = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow.id}").json()+ assert self._function_inputs(body)["api_key"] == {"secret": True}++ stage = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow.id}",+ {"actions": body["actions"], "edges": body["edges"], "stage_draft": True},+ )+ assert stage.status_code == 200, stage.json()+ flow.refresh_from_db()+ assert flow.draft is not None++ self._publish_confirmed(flow.id)++ flow.refresh_from_db()+ assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == "LEGACY-SECRET"+ assert "LEGACY-SECRET" not in json.dumps({"actions": flow.actions, "trigger": flow.trigger})++ def test_migrate_command_moves_legacy_plaintext_to_encrypted(self):+ flow = self._create_legacy_flow(trigger_secret=True)+ untouched = self._create(api_key="ALREADY-ENCRYPTED")++ call_command("migrate_hog_flow_secret_inputs", "--team-id", str(self.team.id))+ flow.refresh_from_db()+ assert flow.encrypted_inputs is None, "dry-run must not write"++ call_command("migrate_hog_flow_secret_inputs", "--team-id", str(self.team.id), "--live")++ flow = HogFlow.objects.get(id=flow.id)+ assert flow.encrypted_inputs["trigger_node"]["api_key"]["value"] == "LEGACY-SECRET"+ assert "LEGACY-SECRET" not in json.dumps({"actions": flow.actions, "trigger": flow.trigger})++ already_encrypted = HogFlow.objects.get(id=untouched)+ assert already_encrypted.encrypted_inputs["action_1"]["api_key"]["value"] == "ALREADY-ENCRYPTED"++ def test_migrate_command_moves_draft_plaintext_and_keeps_encrypted_precedence(self):+ # A legacy row can hold plaintext in its staged draft too, and can hold a stale plaintext+ # copy of a secret that already moved to encrypted storage. The draft plaintext must land in+ # draft_encrypted_inputs, and the already-encrypted value must win over the stale plaintext.+ flow = self._create_legacy_flow()+ flow.encrypted_inputs = {"action_1": {"api_key": {"value": "ENCRYPTED-WINS"}}}+ flow.draft = {+ "actions": [+ {+ "id": "action_1",+ "name": "action_1",+ "type": "function",+ "config": {+ "template_id": _SECRET_TEMPLATE_ID,+ "inputs": {"url": {"value": "https://example.com"}, "api_key": {"value": "DRAFT-SECRET"}},+ },+ }+ ]+ }+ flow.save(update_fields=["encrypted_inputs", "draft"])++ call_command("migrate_hog_flow_secret_inputs", "--team-id", str(self.team.id), "--live")++ flow = HogFlow.objects.get(id=flow.id)+ assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == "ENCRYPTED-WINS"+ assert flow.draft_encrypted_inputs["action_1"]["api_key"]["value"] == "DRAFT-SECRET"+ stored = json.dumps({"actions": flow.actions, "trigger": flow.trigger, "draft": flow.draft})+ assert "LEGACY-SECRET" not in stored+ assert "DRAFT-SECRET" not in storeddiff --git a/products/workflows/backend/management/commands/migrate_hog_flow_secret_inputs.py b/products/workflows/backend/management/commands/migrate_hog_flow_secret_inputs.pynew file mode 100644index 000000000000..7f859fee71f3--- /dev/null+++ b/products/workflows/backend/management/commands/migrate_hog_flow_secret_inputs.py@@ -0,0 +1,113 @@+import uuid+from typing import Any++from django.core.management.base import BaseCommand, CommandParser+from django.core.paginator import Paginator+from django.db import transaction++import structlog++from products.workflows.backend.api.hog_flow import (+ TemplateCache,+ merge_secret_maps,+ plaintext_secret_map,+ strip_secrets_from_content,+)+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow++logger = structlog.get_logger(__name__)+++class Command(BaseCommand):+ help = (+ "Move legacy plaintext secret inputs (rows written before encryption shipped) out of "+ "actions/trigger/draft into the encrypted columns. Dry-run by default; pass --live to write."+ )++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--team-id", type=int, help="Only process flows for this team")+ parser.add_argument("--hog-flow-id", type=str, help="Only process this flow")+ parser.add_argument("--live", action="store_true", help="Actually write changes (default is dry-run)")+ parser.add_argument("--page-size", type=int, default=500)++ def handle(self, *args: Any, **options: Any) -> None:+ live = options["live"]+ queryset = HogFlow.objects.all()+ if options.get("hog_flow_id"):+ queryset = queryset.filter(id=options["hog_flow_id"])+ elif options.get("team_id"):+ queryset = queryset.filter(team_id=options["team_id"])++ migrated = 0+ scanned = 0+ errors = 0+ # Templates are a shared global registry, so one cache serves the whole run.+ template_cache: TemplateCache = {}+ paginator = Paginator(queryset.order_by("id"), options["page_size"])+ for page_num in paginator.page_range:+ for flow in paginator.page(page_num).object_list:+ scanned += 1+ try:+ live_plaintext = plaintext_secret_map(flow.actions, template_cache)+ draft_plaintext = plaintext_secret_map((flow.draft or {}).get("actions"), template_cache)+ if not live_plaintext and not draft_plaintext:+ continue++ keys_desc = {+ action_id: sorted(values) for action_id, values in (live_plaintext | draft_plaintext).items()+ }+ self.stdout.write(+ f"{'MIGRATE' if live else 'DRY-RUN'} flow={flow.id} team={flow.team_id} "+ f"status={flow.status} secret_keys={keys_desc}"+ )+ if not live:+ migrated += 1+ continue++ if self._migrate_locked(flow.id, template_cache):+ migrated += 1+ except Exception as e:+ errors += 1+ logger.error(+ "Error migrating hog flow secret inputs",+ hog_flow_id=str(flow.id),+ team_id=flow.team_id,+ error=str(e),+ exc_info=True,+ )+ self.stdout.write(self.style.ERROR(f"ERROR flow={flow.id}: {e}"))++ summary = f"Scanned {scanned} flows; {'migrated' if live else 'would migrate'} {migrated}; errors {errors}"+ self.stdout.write(self.style.SUCCESS(summary))++ def _migrate_locked(self, flow_id: uuid.UUID, template_cache: TemplateCache) -> bool:+ # API saves to these columns all lock the row (select_for_update) - do the same, and rebuild+ # the secret maps from the locked row, so a concurrent edit or rotation in the window between+ # the scan and this write is never overwritten with stale content.+ with transaction.atomic():+ flow = HogFlow.objects.select_for_update().get(id=flow_id)+ live_plaintext = plaintext_secret_map(flow.actions, template_cache)+ draft_plaintext = plaintext_secret_map((flow.draft or {}).get("actions"), template_cache)+ if not live_plaintext and not draft_plaintext:+ return False++ # Only rewrite the secret columns, not updated_at: this is a backend storage migration, not a+ # user-facing edit. Bumping the stamp would fail the optimistic-concurrency check on any open+ # editor's next save and re-sort untouched flows to the top of the updated_at-ordered list.+ update_fields: list[str] = []+ if live_plaintext:+ content = {"actions": flow.actions, "trigger": flow.trigger}+ stripped = strip_secrets_from_content(content, template_cache)+ flow.actions = content["actions"]+ flow.trigger = content["trigger"]+ # Values already moved to encrypted storage win over stale plaintext copies.+ flow.encrypted_inputs = merge_secret_maps(stripped, flow.encrypted_inputs)+ update_fields += ["actions", "trigger", "encrypted_inputs"]+ if draft_plaintext:+ draft = dict(flow.draft or {})+ stripped = strip_secrets_from_content(draft, template_cache)+ flow.draft = draft+ flow.draft_encrypted_inputs = merge_secret_maps(stripped, flow.draft_encrypted_inputs)+ update_fields += ["draft", "draft_encrypted_inputs"]+ flow.save(update_fields=update_fields)+ return True