: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
chore(workflows): move the secret input helpers behind the facade (#109022)
Harley Alexander83a7e7e238ae
diff --git a/products/workflows/backend/facade/secrets.py b/products/workflows/backend/facade/secrets.pynew file mode 100644index 000000000000..d112803a1a76--- /dev/null+++ b/products/workflows/backend/facade/secrets.py@@ -0,0 +1,30 @@+"""Secret function-action inputs: split out of a workflow's actions for encryption, masked on read,+and folded back in for inline test runs."""++from products.workflows.backend.services.hog_flow_secrets import (+ TemplateCache,+ mask_derived_trigger,+ mask_secret_action_inputs,+ merge_secret_maps,+ partition_flow_secrets,+ plaintext_secret_map,+ recover_or_drop_masked_inputs,+ rehydrate_flow_secrets,+ secret_keys_for_action,+ strip_content_secrets,+ strip_secrets_from_content,+)++__all__ = [+ "TemplateCache",+ "mask_derived_trigger",+ "mask_secret_action_inputs",+ "merge_secret_maps",+ "partition_flow_secrets",+ "plaintext_secret_map",+ "recover_or_drop_masked_inputs",+ "rehydrate_flow_secrets",+ "secret_keys_for_action",+ "strip_content_secrets",+ "strip_secrets_from_content",+]diff --git a/products/workflows/backend/management/commands/migrate_hog_flow_secret_inputs.py b/products/workflows/backend/management/commands/migrate_hog_flow_secret_inputs.pyindex edf56a9324e4..1e8078408755 100644--- a/products/workflows/backend/management/commands/migrate_hog_flow_secret_inputs.py+++ b/products/workflows/backend/management/commands/migrate_hog_flow_secret_inputs.py@@ -7,13 +7,13 @@ from django.db import transactionimport structlog-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow-from products.workflows.backend.presentation.views.hog_flow import (+from products.workflows.backend.facade.secrets import (TemplateCache,merge_secret_maps,plaintext_secret_map,strip_secrets_from_content,)+from products.workflows.backend.models.hog_flow.hog_flow import HogFlowlogger = structlog.get_logger(__name__)diff --git a/products/workflows/backend/management/commands/refresh_hog_flows.py b/products/workflows/backend/management/commands/refresh_hog_flows.pyindex 15f858809c6a..6e72a17ba0d5 100644--- a/products/workflows/backend/management/commands/refresh_hog_flows.py+++ b/products/workflows/backend/management/commands/refresh_hog_flows.py@@ -9,15 +9,15 @@ from django.test import RequestFactoryimport structlog-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow-from products.workflows.backend.presentation.views.hog_flow import (- HogFlowSerializer,+from products.workflows.backend.facade.secrets import (TemplateCache,mask_secret_action_inputs,merge_secret_maps,partition_flow_secrets,plaintext_secret_map,)+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.presentation.views.hog_flow import HogFlowSerializerlogger = structlog.get_logger(__name__)diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 7d48913e0257..af8810ac6b84 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -124,6 +124,18 @@ from products.tasks.backend.facade.workflow_tasks import (validate_skill_names,)from products.workflows.backend.facade.api import create_batch_job+from products.workflows.backend.facade.secrets import (+ TemplateCache,+ mask_derived_trigger,+ mask_secret_action_inputs,+ merge_secret_maps,+ plaintext_secret_map,+ recover_or_drop_masked_inputs,+ rehydrate_flow_secrets,+ secret_keys_for_action,+ strip_content_secrets,+ strip_secrets_from_content,+)from products.workflows.backend.metrics import (GUARDRAIL_LABELS,GUARDRAIL_METRICS,@@ -367,78 +379,6 @@ def snapshot_flow_content(flow: HogFlow) -> dict:return strip_content_secrets(snapshot, template_cache={})-# --- Secret function-action inputs --------------------------------------------------------------# Function/email/sms steps (and function-shaped triggers) can carry secret inputs - API keys, auth-# headers - declared `secret: true` on their template's inputs_schema. We split those values out of-# the plaintext `actions` blob into the encrypted `encrypted_inputs` column (keyed by action id then-# input key), mirroring HogFunction.encrypted_inputs. The worker re-merges them at execution time.-_FUNCTION_TRIGGER_CONFIG_TYPES = frozenset({"webhook", "manual", "tracking_pixel"})---# A per-call {template_id: template_or_None} memo. Resolving a template is a DB query, and both the-# read (masking) and write (stripping) paths touch every action, so callers pass one of these to-# dedupe lookups - within a flow, and across a whole list page when stashed on the serializer context.-TemplateCache = dict[str, Optional[Any]]---def _function_template_for_action(action: dict, template_cache: Optional[TemplateCache] = None) -> Optional[Any]:- # A function step, or a trigger whose source is function-shaped, resolves a template whose- # inputs_schema tells us which inputs are secret. Everything else has no secret inputs.- config = action.get("config") or {}- action_type = action.get("type", "") or ""- is_function = "function" in action_type or (- action_type == "trigger" and config.get("type") in _FUNCTION_TRIGGER_CONFIG_TYPES- )- if not is_function:- return None- template_id = config.get("template_id", "") or ""- if template_cache is None:- return HogFunctionTemplate.get_template(template_id)- if template_id not in template_cache:- template_cache[template_id] = HogFunctionTemplate.get_template(template_id)- return template_cache[template_id]---def _secret_keys_for_action(action: dict, template_cache: Optional[TemplateCache] = None) -> set[str]:- template = _function_template_for_action(action, template_cache)- if not template:- return set()- return {schema["key"] for schema in (template.inputs_schema or []) if schema.get("secret")}---def partition_flow_secrets(- actions: list[dict], template_cache: Optional[TemplateCache] = None-) -> tuple[list[dict], dict[str, dict]]:- """Split secret inputs out of each action's config.inputs.-- Returns (stripped_actions, encrypted_map) where encrypted_map is {action_id: {input_key: value}}.- The input list is not mutated. The map is rebuilt from scratch each call - never merged onto a- prior map - so secrets for deleted or renamed actions drop out rather than orphaning.- """- stripped: list[dict] = []- encrypted: dict[str, dict] = {}- for original in actions:- action = deepcopy(original)- secret_keys = _secret_keys_for_action(action, template_cache)- if secret_keys:- inputs = (action.get("config") or {}).get("inputs")- if isinstance(inputs, dict):- moved = {key: inputs.pop(key) for key in list(inputs) if key in secret_keys}- if moved:- encrypted[action["id"]] = moved- stripped.append(action)- 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.@@ -448,67 +388,6 @@ def existing_secret_map(instance: "HogFlow", template_cache: Optional[TemplateCareturn 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()}- for action_id, values in (overlay or {}).items():- result[action_id] = {**result.get(action_id, {}), **values}- return 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]:- # Replace every set secret input with the {"secret": True} presence marker for read-back. Mutates- # the given action dicts (must be a copy - callers deepcopy first). A value counts as set if it- # lives in the encrypted map or, for legacy rows written before the split, still sits in plaintext.- for flow_action in actions:- secret_keys = _secret_keys_for_action(flow_action, template_cache)- if not secret_keys:- continue- inputs = (flow_action.get("config") or {}).get("inputs")- if not isinstance(inputs, dict):- continue- action_id = flow_action.get("id")- action_secrets = secrets_by_action.get(action_id, {}) if isinstance(action_id, str) else {}- for key in secret_keys:- if action_secrets.get(key) or inputs.get(key):- inputs[key] = {"secret": True}- return actions---def _mask_derived_trigger(content: dict, template_cache: Optional[TemplateCache] = None) -> None:- # The `trigger` representation is derived from the trigger action, so once that action's inputs are- # masked, re-derive `trigger` from it. Keeps a function-shaped trigger's secret from leaking on the- # separately-serialized trigger field. No-op when there's no trigger action or no `trigger` key.- actions = content.get("actions")- if "trigger" not in content or not isinstance(actions, list):- return- trigger_action = next(- (a for a in actions if isinstance(a, dict) and a.get("type") == "trigger"),- None,- )- if trigger_action is not None:- content["trigger"] = trigger_action.get("config")--def mask_trigger_config(instance: "HogFlow", secrets_by_action: dict[str, dict], template_cache: Optional[TemplateCache] = None) -> Any:@@ -530,32 +409,6 @@ def mask_trigger_config(return masked[0].get("config")-def strip_secrets_from_content(content: dict, template_cache: Optional[TemplateCache] = None) -> dict[str, dict]:- # Move secret inputs out of content["actions"] into an encrypted map, updating content["actions"]- # (stripped) and the derived content["trigger"] in place. Returns the {action_id: {key: value}} map.- # Shared by the live write, the draft write, and (map discarded) the snapshot/compare paths.- actions = content.get("actions")- if not isinstance(actions, list):- return {}- stripped, encrypted = partition_flow_secrets(actions, template_cache)- content["actions"] = stripped- if "trigger" in content:- trigger_action = next((action for action in stripped if action.get("type") == "trigger"), None)- if trigger_action is not None:- content["trigger"] = trigger_action.get("config")- return encrypted---def strip_content_secrets(content: dict, template_cache: Optional[TemplateCache] = None) -> dict:- # Return a copy of a content snapshot with secret inputs stripped from actions (and the trigger- # re-derived). Used to snapshot revisions secret-free and to compare two snapshots secret-free, so a- # resent secret validation recovers into `actions` doesn't read as a content change against the- # stored (stripped) snapshot and spuriously bump the revision.- normalized = dict(content)- strip_secrets_from_content(normalized, template_cache)- return normalized--def strip_proposal_secrets(content: dict, live_content: dict, template_cache: Optional[TemplateCache] = None) -> dict:"""Strip secret inputs from a proposal's content, classifying each step against the live step itpatches. A patch carries only the fields it changes, so it can set a secret input without the@@ -571,26 +424,11 @@ def strip_proposal_secrets(content: dict, live_content: dict, template_cache: Opinputs = (item.get("config") or {}).get("inputs") if isinstance(item, dict) else Noneif live_step is None or not isinstance(inputs, dict):continue- for key in _secret_keys_for_action(_deep_merge(deepcopy(live_step), item), template_cache):+ for key in secret_keys_for_action(_deep_merge(deepcopy(live_step), item), template_cache):inputs.pop(key, None)return stripped-def rehydrate_flow_secrets(actions: list[dict], secrets_by_action: dict[str, dict]) -> list[dict]:- # Fold decrypted secrets back into each action's config.inputs. Used for inline test runs that- # ship a config to the executor directly, bypassing the worker's manager (which decrypts normally).- result: list[dict] = []- for original in actions:- action = deepcopy(original)- action_id = action.get("id")- action_secrets = secrets_by_action.get(action_id) if isinstance(action_id, str) else None- config = action.get("config")- if action_secrets and isinstance(config, dict) and isinstance(config.get("inputs"), dict):- config["inputs"] = {**config["inputs"], **action_secrets}- result.append(action)- return result--# A batch audience is a one-time snapshot of everyone matching the conditions at run time, so each# condition must resolve to a concrete set of persons/groups. Feature flag evaluation is dynamic# (rollout %, distinct_id hashing, super-conditions, holdouts) and has no such fixed membership, so a@@ -2911,7 +2749,7 @@ class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Moddraft["actions"] = mask_secret_action_inputs(draft["actions"], merge_secret_maps(live_secrets, draft_secrets), template_cache)- _mask_derived_trigger(draft, template_cache)+ mask_derived_trigger(draft, template_cache)data["draft"] = draftreturn datadiff --git a/products/workflows/backend/services/hog_flow_secrets.py b/products/workflows/backend/services/hog_flow_secrets.pynew file mode 100644index 000000000000..95cd998f6fbd--- /dev/null+++ b/products/workflows/backend/services/hog_flow_secrets.py@@ -0,0 +1,176 @@+from copy import deepcopy+from typing import Any, Optional++from products.cdp.backend.models.hog_function_template import HogFunctionTemplate++# Function/email/sms steps (and function-shaped triggers) can carry secret inputs - API keys, auth+# headers - declared `secret: true` on their template's inputs_schema. We split those values out of+# the plaintext `actions` blob into the encrypted `encrypted_inputs` column (keyed by action id then+# input key), mirroring HogFunction.encrypted_inputs. The worker re-merges them at execution time.+_FUNCTION_TRIGGER_CONFIG_TYPES = frozenset({"webhook", "manual", "tracking_pixel"})+++# A per-call {template_id: template_or_None} memo. Resolving a template is a DB query, and both the+# read (masking) and write (stripping) paths touch every action, so callers pass one of these to+# dedupe lookups - within a flow, and across a whole list page when stashed on the serializer context.+TemplateCache = dict[str, Optional[Any]]+++def _function_template_for_action(action: dict, template_cache: Optional[TemplateCache] = None) -> Optional[Any]:+ # A function step, or a trigger whose source is function-shaped, resolves a template whose+ # inputs_schema tells us which inputs are secret. Everything else has no secret inputs.+ config = action.get("config") or {}+ action_type = action.get("type", "") or ""+ is_function = "function" in action_type or (+ action_type == "trigger" and config.get("type") in _FUNCTION_TRIGGER_CONFIG_TYPES+ )+ if not is_function:+ return None+ template_id = config.get("template_id", "") or ""+ if template_cache is None:+ return HogFunctionTemplate.get_template(template_id)+ if template_id not in template_cache:+ template_cache[template_id] = HogFunctionTemplate.get_template(template_id)+ return template_cache[template_id]+++def secret_keys_for_action(action: dict, template_cache: Optional[TemplateCache] = None) -> set[str]:+ template = _function_template_for_action(action, template_cache)+ if not template:+ return set()+ return {schema["key"] for schema in (template.inputs_schema or []) if schema.get("secret")}+++def partition_flow_secrets(+ actions: list[dict], template_cache: Optional[TemplateCache] = None+) -> tuple[list[dict], dict[str, dict]]:+ """Split secret inputs out of each action's config.inputs.++ Returns (stripped_actions, encrypted_map) where encrypted_map is {action_id: {input_key: value}}.+ The input list is not mutated. The map is rebuilt from scratch each call - never merged onto a+ prior map - so secrets for deleted or renamed actions drop out rather than orphaning.+ """+ stripped: list[dict] = []+ encrypted: dict[str, dict] = {}+ for original in actions:+ action = deepcopy(original)+ secret_keys = secret_keys_for_action(action, template_cache)+ if secret_keys:+ inputs = (action.get("config") or {}).get("inputs")+ if isinstance(inputs, dict):+ moved = {key: inputs.pop(key) for key in list(inputs) if key in secret_keys}+ if moved:+ encrypted[action["id"]] = moved+ stripped.append(action)+ 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 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()}+ for action_id, values in (overlay or {}).items():+ result[action_id] = {**result.get(action_id, {}), **values}+ return 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]:+ # Replace every set secret input with the {"secret": True} presence marker for read-back. Mutates+ # the given action dicts (must be a copy - callers deepcopy first). A value counts as set if it+ # lives in the encrypted map or, for legacy rows written before the split, still sits in plaintext.+ for flow_action in actions:+ secret_keys = secret_keys_for_action(flow_action, template_cache)+ if not secret_keys:+ continue+ inputs = (flow_action.get("config") or {}).get("inputs")+ if not isinstance(inputs, dict):+ continue+ action_id = flow_action.get("id")+ action_secrets = secrets_by_action.get(action_id, {}) if isinstance(action_id, str) else {}+ for key in secret_keys:+ if action_secrets.get(key) or inputs.get(key):+ inputs[key] = {"secret": True}+ return actions+++def mask_derived_trigger(content: dict, template_cache: Optional[TemplateCache] = None) -> None:+ # The `trigger` representation is derived from the trigger action, so once that action's inputs are+ # masked, re-derive `trigger` from it. Keeps a function-shaped trigger's secret from leaking on the+ # separately-serialized trigger field. No-op when there's no trigger action or no `trigger` key.+ actions = content.get("actions")+ if "trigger" not in content or not isinstance(actions, list):+ return+ trigger_action = next(+ (a for a in actions if isinstance(a, dict) and a.get("type") == "trigger"),+ None,+ )+ if trigger_action is not None:+ content["trigger"] = trigger_action.get("config")+++def strip_secrets_from_content(content: dict, template_cache: Optional[TemplateCache] = None) -> dict[str, dict]:+ # Move secret inputs out of content["actions"] into an encrypted map, updating content["actions"]+ # (stripped) and the derived content["trigger"] in place. Returns the {action_id: {key: value}} map.+ # Shared by the live write, the draft write, and (map discarded) the snapshot/compare paths.+ actions = content.get("actions")+ if not isinstance(actions, list):+ return {}+ stripped, encrypted = partition_flow_secrets(actions, template_cache)+ content["actions"] = stripped+ if "trigger" in content:+ trigger_action = next((action for action in stripped if action.get("type") == "trigger"), None)+ if trigger_action is not None:+ content["trigger"] = trigger_action.get("config")+ return encrypted+++def strip_content_secrets(content: dict, template_cache: Optional[TemplateCache] = None) -> dict:+ # Return a copy of a content snapshot with secret inputs stripped from actions (and the trigger+ # re-derived). Used to snapshot revisions secret-free and to compare two snapshots secret-free, so a+ # resent secret validation recovers into `actions` doesn't read as a content change against the+ # stored (stripped) snapshot and spuriously bump the revision.+ normalized = dict(content)+ strip_secrets_from_content(normalized, template_cache)+ return normalized+++def rehydrate_flow_secrets(actions: list[dict], secrets_by_action: dict[str, dict]) -> list[dict]:+ # Fold decrypted secrets back into each action's config.inputs. Used for inline test runs that+ # ship a config to the executor directly, bypassing the worker's manager (which decrypts normally).+ result: list[dict] = []+ for original in actions:+ action = deepcopy(original)+ action_id = action.get("id")+ action_secrets = secrets_by_action.get(action_id) if isinstance(action_id, str) else None+ config = action.get("config")+ if action_secrets and isinstance(config, dict) and isinstance(config.get("inputs"), dict):+ config["inputs"] = {**config["inputs"], **action_secrets}+ result.append(action)+ return result