: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
feat(workflows): encrypt secret function inputs on hog flow actions (#72913)
Harley Alexanderfdbf5b443b7d
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.tsindex f7a5231e30f6..71a72330099b 100644--- a/nodejs/src/cdp/cdp-api.test.ts+++ b/nodejs/src/cdp/cdp-api.test.ts@@ -838,6 +838,57 @@ describe('CDP API', () => {})})+ it('redacts a flow function action secret from mocked async function logs', async () => {+ const SECRET_TOKEN = 'super-secret-flow-token-xyz'++ await insertHogFunctionTemplate(hub.postgres, {+ id: 'template-cdp-api-flow-secret-fetch',+ name: 'Flow secret fetch',+ code: `fetch(inputs.url, { 'method': 'POST', 'headers': { 'Authorization': f'Bearer {inputs.access_token}' } })`,+ inputs_schema: [+ { key: 'url', type: 'string', label: 'URL', secret: false, required: true },+ { key: 'access_token', type: 'string', label: 'Access token', secret: true, required: true },+ ],+ })++ const flowConfiguration = {+ name: 'Flow with secret fetch',+ actions: [+ { id: 'trigger_node', name: 'Trigger', type: 'trigger', config: { type: 'event', filters: {} } },+ {+ id: 'fetch_node',+ name: 'Fetch',+ type: 'function',+ config: {+ template_id: 'template-cdp-api-flow-secret-fetch',+ inputs: {+ url: { value: 'https://example.com/hook' },+ access_token: { value: SECRET_TOKEN },+ },+ },+ },+ { id: 'exit_node', name: 'Exit', type: 'exit', config: {} },+ ],+ edges: [+ { from: 'trigger_node', to: 'fetch_node', type: 'continue' },+ { from: 'fetch_node', to: 'exit_node', type: 'continue' },+ ],+ }++ const res = await supertest(app).post(`/api/projects/${team.id}/hog_flows/new/invocations`).send({+ globals,+ mock_async_functions: true,+ configuration: flowConfiguration,+ current_action_id: 'fetch_node',+ })++ expect(res.status).toEqual(200)+ const allLogText = res.body.logs.map((log: any) => log.message).join('\n')+ expect(allLogText).not.toContain(SECRET_TOKEN)+ // Confirm redaction actually ran, rather than passing because no fetch log was emitted.+ expect(allLogText).toContain('***REDACTED***')+ })+describe('batch hogflow invocations', () => {let batchHogFlow: HogFlowdiff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex a32ad8a2f33d..827ec9771801 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -661,7 +661,14 @@ export class CdpApi {})}- const options: HogExecutorExecuteAsyncOptions = buildHogExecutorAsyncOptions(mock_async_functions, logs)+ // Redact the flow's decrypted secret inputs from the mocked async-function logs, so a test+ // run can't echo a stored credential (e.g. an Authorization header) back to the caller.+ const sensitiveValues = await this.hogFlowExecutor.getSensitiveValues(compoundConfiguration)+ const options: HogExecutorExecuteAsyncOptions = buildHogExecutorAsyncOptions(+ mock_async_functions,+ logs,+ sensitiveValues+ )options.sendEmailsInline = trueconst result = await this.hogFlowExecutor.executeCurrentAction(invocation, { hogExecutorOptions: options })diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 8594b75117d1..cf4e95c702a8 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -358,7 +358,7 @@ export function createCdpCoreServices(const valkeyShadow = createCdpValkeyShadowPools(config, redisName)const hogFunctionManager = new HogFunctionManagerService(deps.postgres, deps.pubSub, deps.encryptedFields)- const hogFlowManager = new HogFlowManagerService(deps.postgres, deps.pubSub)+ const hogFlowManager = new HogFlowManagerService(deps.postgres, deps.pubSub, deps.encryptedFields)const hogWatcherConfig = {hogCostTimingLowerMs: config.CDP_WATCHER_HOG_COST_TIMING_LOWER_MS,diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.tsindex 33f8cd6f3572..c62f04e6f67e 100644--- a/nodejs/src/cdp/schema/hogflow.ts+++ b/nodejs/src/cdp/schema/hogflow.ts@@ -278,6 +278,10 @@ export const HogFlowSchema = z.object({'exit_only_at_end',]),actions: z.array(HogFlowActionSchema),+ // Secret function inputs, split out of `actions` and stored Fernet-encrypted at rest, keyed by+ // action id then input key. Decrypted by the manager and merged back into `action.config.inputs`+ // before execution; never present on the plaintext `actions` blob.+ encrypted_inputs: z.record(z.string(), z.record(z.string(), CyclotronInputSchema)).optional().nullable(),abort_action: z.string().optional(),edges: z.array(HogFlowEdgeSchema),variables: z.array(CyclotronJobInputSchemaTypeSchema).optional().nullable(),diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex 82521206e4bd..919714401b72 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -99,6 +99,7 @@ export function createHogFlowInvocation(export class HogFlowExecutorService {private readonly actionHandlers: Record<HogFlowAction['type'], ActionHandler>private readonly duplicateObserver: HogFlowDuplicateObserverService | null+ private readonly hogFlowFunctionsService: HogFlowFunctionsServiceconstructor(hogFlowFunctionsService: HogFlowFunctionsService,@@ -106,6 +107,7 @@ export class HogFlowExecutorService {emailValidationService: EmailValidationService,duplicateObserver?: HogFlowDuplicateObserverService) {+ this.hogFlowFunctionsService = hogFlowFunctionsServicethis.duplicateObserver = duplicateObserver ?? nullconst hogFunctionHandler = new HogFunctionHandler(hogFlowFunctionsService,@@ -141,6 +143,11 @@ export class HogFlowExecutorService {}}+ // Decrypted secret input values across the flow's function actions, for redacting test-run logs.+ async getSensitiveValues(hogFlow: HogFlow): Promise<string[]> {+ return this.hogFlowFunctionsService.getSensitiveValues(hogFlow)+ }+async buildHogFlowInvocations(hogFlows: HogFlow[],triggerGlobals: HogFunctionInvocationGlobals@@ -473,9 +480,14 @@ export class HogFlowExecutorService {timestamp: DateTime.now(),})}+ // Deliberately an allowlisted context, not the full action/invocation: an action's+ // config.inputs can hold decrypted secrets (API keys, auth headers) that the encrypted_inputs+ // split keeps out of storage, and dumping them here would put them straight into worker logs.logger.debug('🦔', `[HogFlowActionRunner] Running action ${currentAction.type}`, {- action: currentAction,- invocation,+ hogFlowId: invocation.hogFlow.id,+ invocationId: invocation.id,+ actionId: currentAction.id,+ actionType: currentAction.type,})const handler = this.actionHandlers[currentAction.type]diff --git a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.tsindex a9fa7abe21b1..637bd13a03dd 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts@@ -51,6 +51,38 @@ export class HogFlowFunctionsService {return hogFunction}+ // Collect the decrypted secret input values across a flow's function actions, so a test+ // invocation with mocked async functions can redact them from the fetch args it echoes into logs+ // (otherwise a workflow editor could read a stored credential they were never shown).+ async getSensitiveValues(hogFlow: HogFlow): Promise<string[]> {+ const functionActionTypes: FunctionActionType[] = ['function', 'function_email', 'function_sms']+ const values: string[] = []+ for (const action of hogFlow.actions ?? []) {+ if (!functionActionTypes.includes(action.type as FunctionActionType)) {+ continue+ }+ const config = (action as Action).config+ const template = await this.hogFunctionTemplateManager.getHogFunctionTemplate(config.template_id)+ for (const schema of template?.inputs_schema ?? []) {+ if (!schema.secret) {+ continue+ }+ const value = config.inputs?.[schema.key]?.value+ if (typeof value === 'string') {+ values.push(value)+ } else if (value && typeof value === 'object') {+ // e.g. a headers dict {Authorization: "Bearer <key>"} - mask each string leaf+ Object.values(value).forEach((leaf) => {+ if (typeof leaf === 'string') {+ values.push(leaf)+ }+ })+ }+ }+ }+ return values+ }+async buildHogFunctionInvocation(invocation: CyclotronJobInvocationHogFlow,hogFunction: HogFunctionType,diff --git a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.tsindex d91be9505dea..93dfdebce7d0 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.ts@@ -25,7 +25,7 @@ describe('HogFlowManager', () => {beforeEach(async () => {hub = await createHub()await resetTestDatabase()- manager = new HogFlowManagerService(hub.postgres, hub.pubSub)+ manager = new HogFlowManagerService(hub.postgres, hub.pubSub, hub.encryptedFields)const team = await getTeam(hub.postgres, 2)@@ -181,4 +181,173 @@ describe('HogFlowManager', () => {expect(result[teamId1]).not.toContain(hogFlows[0].id)})})++ describe('encrypted inputs', () => {+ it('decrypts and merges secret inputs into the matching action before execution', async () => {+ const flow = await insertHogFlow(+ hub.postgres,+ new FixtureHogFlowBuilder()+ .withName('Flow with secret webhook')+ .withTeamId(teamId1)+ .withStatus('active')+ .withWorkflow({+ actions: {+ trigger: { type: 'trigger', config: { type: 'event', filters: {} } },+ send_webhook: {+ type: 'function',+ config: {+ template_id: 'template-webhook',+ inputs: { url: { value: 'https://example.com' } },+ },+ },+ exit: { type: 'exit', config: {} },+ },+ edges: [+ { from: 'trigger', to: 'send_webhook', type: 'continue' },+ { from: 'send_webhook', to: 'exit', type: 'continue' },+ ],+ })+ .build()+ )++ // The API stores secret inputs Fernet-encrypted, stripped out of the plaintext `actions`.+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogflow SET encrypted_inputs = $2 WHERE id = $1`,+ [+ flow.id,+ hub.encryptedFields.encrypt(+ JSON.stringify({ send_webhook: { api_key: { value: 'super-secret-key' } } })+ ),+ ],+ 'testKey'+ )+ manager['onHogFlowsReloaded'](teamId1, [flow.id])++ const loaded = await manager.getHogFlow(flow.id)+ const action = loaded?.actions.find((a) => a.id === 'send_webhook')+ expect(action).not.toBeUndefined()++ // Secret folded back in alongside the untouched plaintext input, keyed by action id.+ expect((action!.config as { inputs: Record<string, unknown> }).inputs).toEqual({+ url: { value: 'https://example.com' },+ api_key: { value: 'super-secret-key' },+ })+ // The ciphertext blob never rides along on the in-memory flow.+ expect(loaded).not.toHaveProperty('encrypted_inputs')+ })++ it('re-merges a webhook trigger secret into hogFlow.trigger, not just the trigger action', async () => {+ const flow = await insertHogFlow(+ hub.postgres,+ new FixtureHogFlowBuilder()+ .withName('Webhook-triggered flow')+ .withTeamId(teamId1)+ .withStatus('active')+ .withWorkflow({+ actions: {+ trigger: {+ type: 'trigger',+ config: { type: 'webhook', template_id: 'template-source-webhook', inputs: {} },+ },+ exit: { type: 'exit', config: {} },+ },+ edges: [{ from: 'trigger', to: 'exit', type: 'continue' }],+ })+ .build()+ )++ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogflow SET encrypted_inputs = $2 WHERE id = $1`,+ [+ flow.id,+ hub.encryptedFields.encrypt(+ JSON.stringify({ trigger: { auth_header: { value: 'Bearer secret' } } })+ ),+ ],+ 'testKey'+ )+ manager['onHogFlowsReloaded'](teamId1, [flow.id])++ const loaded = await manager.getHogFlow(flow.id)+ // The source-webhook consumer builds its function from hogFlow.trigger, so the secret must+ // land there too or a webhook trigger would run without its configured auth header.+ expect((loaded!.trigger as { inputs: Record<string, unknown> }).inputs).toEqual({+ auth_header: { value: 'Bearer secret' },+ })+ })++ it('lets the encrypted value take precedence over plaintext left in actions', async () => {+ const flow = await insertHogFlow(+ hub.postgres,+ new FixtureHogFlowBuilder()+ .withName('Flow with plaintext and encrypted secret')+ .withTeamId(teamId1)+ .withStatus('active')+ .withWorkflow({+ actions: {+ trigger: { type: 'trigger', config: { type: 'event', filters: {} } },+ // A row not yet re-saved since encryption shipped: the secret still sits in plaintext here...+ send_webhook: {+ type: 'function',+ config: {+ template_id: 'template-webhook',+ inputs: { api_key: { value: 'stale-plaintext' } },+ },+ },+ exit: { type: 'exit', config: {} },+ },+ edges: [+ { from: 'trigger', to: 'send_webhook', type: 'continue' },+ { from: 'send_webhook', to: 'exit', type: 'continue' },+ ],+ })+ .build()+ )++ // ...and also in the encrypted column with the current value.+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogflow SET encrypted_inputs = $2 WHERE id = $1`,+ [+ flow.id,+ hub.encryptedFields.encrypt(JSON.stringify({ send_webhook: { api_key: { value: 'current' } } })),+ ],+ 'testKey'+ )+ manager['onHogFlowsReloaded'](teamId1, [flow.id])++ const loaded = await manager.getHogFlow(flow.id)+ const action = loaded?.actions.find((a) => a.id === 'send_webhook')+ expect((action!.config as { inputs: Record<string, unknown> }).inputs).toEqual({+ api_key: { value: 'current' },+ })+ })++ it('keeps the flow (fail-open) when encrypted_inputs cannot be decrypted', async () => {+ const flow = await insertHogFlow(+ hub.postgres,+ new FixtureHogFlowBuilder()+ .withName('Undecryptable flow')+ .withTeamId(teamId1)+ .withStatus('active')+ .build()+ )++ // Not valid Fernet ciphertext (e.g. key skew / corruption): decrypt throws internally.+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogflow SET encrypted_inputs = $2 WHERE id = $1`,+ [flow.id, 'not-a-valid-fernet-token'],+ 'testKey'+ )+ manager['onHogFlowsReloaded'](teamId1, [flow.id])++ // The whole flow load must not throw - the flow is returned, just without its secrets.+ const loaded = await manager.getHogFlow(flow.id)+ expect(loaded).not.toBeNull()+ expect(loaded).not.toHaveProperty('encrypted_inputs')+ })+ })})diff --git a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.tsindex 9074081ceeeb..4c3ebdca8c5b 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts@@ -1,10 +1,24 @@+import { Counter } from 'prom-client'+import { HogFlow } from '~/cdp/schema/hogflow'import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'+import { parseJSON } from '~/common/utils/json-parse'import { LazyLoader } from '~/common/utils/lazy-loader'import { logger } from '~/common/utils/logger'+import { captureException } from '~/common/utils/posthog'import { PubSub } from '~/common/utils/pubsub'import { Team } from '~/types'+import { EncryptedFields } from '../../utils/encryption-utils'++// Nonzero means a flow's encrypted secret inputs couldn't be decrypted (most likely Fernet key skew+// between Django and the workers, or a corrupt blob). The flow still runs, but its secret-input steps+// run without their credentials, so this is worth alerting on.+const counterEncryptedInputsDecryptFailed = new Counter({+ name: 'cdp_hogflow_encrypted_inputs_decrypt_failed',+ help: 'A hog flow encrypted_inputs blob could not be decrypted; the flow runs without its secrets',+})+// TODO: Make sure we only have fields we truly needconst HOG_FLOW_FIELDS = ['id',@@ -21,6 +35,7 @@ const HOG_FLOW_FIELDS = ['exit_condition','edges','actions',+ 'encrypted_inputs','abort_action','billable_action_types','variables',@@ -35,7 +50,8 @@ export class HogFlowManagerService {constructor(private postgres: PostgresRouter,- private pubSub: PubSub+ private pubSub: PubSub,+ private encryptedFields: EncryptedFields) {// The reload-hog-flows pub/sub below is the primary invalidation; these ages bound how// stale a worker can run when it misses the publish (pod restart, Redis blip). Live edits@@ -181,8 +197,65 @@ export class HogFlowManagerService {}}}+ this.mergeEncryptedInputs(item)acc[item.id] = itemreturn acc}, {})}++ // Decrypts `encrypted_inputs` and folds each action's secret inputs back into+ // `action.config.inputs` so the executor sees a whole config. `encrypted_inputs` is authoritative:+ // if a key also appears in plaintext `actions` (a row not yet re-saved since encryption shipped),+ // the encrypted value takes precedence, so both shapes resolve to the right value.+ private mergeEncryptedInputs(item: HogFlow): void {+ const raw = item.encrypted_inputs as unknown++ let decrypted: Record<string, Record<string, unknown>> | undefined+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {+ // The sql lib occasionally hands back an already-parsed object+ decrypted = raw as Record<string, Record<string, unknown>>+ } else if (typeof raw === 'string' && raw) {+ try {+ const plaintext = this.encryptedFields.decrypt(raw)+ if (plaintext) {+ decrypted = parseJSON(plaintext)+ }+ } catch (error) {+ // The blob is dropped below and the flow runs without its secrets (fail-open, matching+ // HogFunctionManagerService). The counter makes the failure alertable - the most likely+ // cause is Fernet key skew between Django and the workers.+ logger.warn('[HogFlowManager]', 'Could not decrypt encrypted inputs - flow will run without them', {+ error: error instanceof Error ? error.message : 'Unknown error',+ })+ counterEncryptedInputsDecryptFailed.inc()+ captureException(error)+ }+ }++ // Drop the encrypted blob from the in-memory flow either way - downstream reads inputs off+ // `action.config.inputs`, and this keeps the ciphertext out of anything that logs the flow.+ delete item.encrypted_inputs++ if (!decrypted) {+ return+ }++ for (const action of item.actions ?? []) {+ const actionSecrets = decrypted[action.id]+ if (!actionSecrets || !('config' in action)) {+ continue+ }+ const config = action.config as { inputs?: Record<string, unknown> }+ config.inputs = { ...config.inputs, ...actionSecrets }++ // The top-level `trigger` is derived from the trigger action and is stripped of secrets+ // the same way. The source-webhook consumer builds its function from `hogFlow.trigger`+ // (not the action), so re-merge the trigger action's secrets there too or a webhook+ // trigger's secret auth header would be missing at runtime.+ if (action.type === 'trigger' && item.trigger && 'inputs' in item.trigger) {+ const trigger = item.trigger as { inputs?: Record<string, unknown> }+ trigger.inputs = { ...trigger.inputs, ...actionSecrets }+ }+ }+ }}diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 372d36b7f0b3..b050a84e33cc 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -278,6 +278,15 @@ field_with_masked_contents: dict[AuditableScope, list[str]] = {# Full content snapshot including action inputs (auth headers, API keys) — record that a# draft was staged/published/discarded, never its contents."draft",+ # Encrypted secret function inputs (Fernet ciphertext) — a diff would be noise at best and+ # leak-adjacent at worst; record that they changed, never the values.+ "encrypted_inputs",+ "draft_encrypted_inputs",+ # The action graph can carry secret function inputs (auth headers, API keys). New writes strip+ # them into encrypted_inputs, but a legacy row's first write would diff its still-plaintext+ # `before` against the stripped `after`, leaking the secret. Record that actions changed, never+ # the contents — the per-version content audit lives in the revisions feature instead.+ "actions",],"OrganizationDomain": ["_scim_bearer_token",diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 3e36dfc7f3c9..577cc1e94ddc 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -3,6 +3,7 @@ import jsonimport uuid as uuid_modimport hashlibimport dataclasses+from copy import deepcopyfrom datetime import timedeltafrom typing import Any, Optional, cast@@ -149,7 +150,179 @@ def snapshot_flow_content(flow: HogFlow) -> dict:for field in ("actions", "edges"):if not snapshot[field]:snapshot[field] = []- return snapshot+ # Defensively strip secrets: a legacy row written before encryption shipped still has plaintext+ # secret inputs in `actions`, and this snapshot feeds revision content — which must never carry+ # secrets. New rows are already stripped, so this is a no-op for them.+ return strip_content_secrets(snapshot)+++# --- 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 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 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:+ # Mask the standalone `trigger` field. Both the minimal and (crucially) the summary serializer+ # return `trigger` while the summary omits `actions`, so it can't be re-derived from masked actions+ # there - a function-shaped trigger's secret would otherwise leak on the MCP list endpoint. Mask+ # from the instance's own trigger action (or the stored trigger config as a fallback for legacy+ # rows whose actions may be empty).+ trigger_action = next(+ (a for a in (instance.actions or []) if isinstance(a, dict) and a.get("type") == "trigger"),+ None,+ )+ trigger_action = (+ deepcopy(trigger_action)+ if trigger_action is not None+ else {"type": "trigger", "config": deepcopy(instance.trigger) if instance.trigger else {}}+ )+ masked = mask_secret_action_inputs([trigger_action], secrets_by_action, template_cache)+ 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 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@@ -647,6 +820,10 @@ class HogFlowActionSerializer(serializers.Serializer):context={"function_type": template.type,"is_dwh_source": self.context.get("is_dwh_source", False),+ # The existing (decrypted) secret inputs for this action, so a resent+ # {"secret": true} marker recovers the stored value instead of wiping it.+ "encrypted_inputs": (self.context.get("existing_encrypted_inputs") or {}).get(data.get("id"))+ or {},},)@@ -1069,6 +1246,37 @@ class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Mod]read_only_fields = fields+ def to_representation(self, instance):+ # Never return secret function inputs. Replace each set secret with the {"secret": True}+ # presence marker in the live actions and, when present, the staged draft's actions. Values+ # come from the encrypted columns (or legacy plaintext); see mask_secret_action_inputs.+ live_secrets = instance.encrypted_inputs or {} if isinstance(instance, HogFlow) else {}+ draft_secrets = instance.draft_encrypted_inputs or {} if isinstance(instance, HogFlow) else {}+ data = super().to_representation(instance)++ # `actions`/`draft` come back from super() by reference (JSONField doesn't copy), so masking in+ # place would rewrite the live model instance. Deepcopy first to keep serialization side-effect+ # free. The template cache lives on the context so a list render dedupes lookups across flows.+ template_cache: TemplateCache = self.context.setdefault("_hogflow_template_cache", {})+ if isinstance(data.get("actions"), list):+ data["actions"] = mask_secret_action_inputs(deepcopy(data["actions"]), live_secrets, template_cache)+ # `trigger` is a separately-serialized field derived from the trigger action. Mask it from the+ # instance directly (not from data["actions"]) so it's covered even by the summary serializer,+ # which returns `trigger` but omits `actions` - otherwise a function-shaped trigger's secret+ # would leak on the MCP list endpoint.+ if "trigger" in data and isinstance(instance, HogFlow):+ data["trigger"] = mask_trigger_config(instance, live_secrets, template_cache)+ draft = data.get("draft")+ if isinstance(draft, dict) and isinstance(draft.get("actions"), list):+ draft = deepcopy(draft)+ draft["actions"] = mask_secret_action_inputs(+ draft["actions"], merge_secret_maps(live_secrets, draft_secrets), template_cache+ )+ _mask_derived_trigger(draft, template_cache)+ data["draft"] = draft++ return data+class HogFlowSummarySerializer(HogFlowMinimalSerializer):# Metadata-only listing view. Deliberately omits the action graph (actions/edges) and other@@ -1188,17 +1396,30 @@ class HogFlowSerializer(HogFlowMinimalSerializer):)def to_internal_value(self, data):+ # When used as a nested field (the `configuration` override on test invocations) DRF never+ # binds `self.instance`, so fall back to the flow passed in via context so recovery still works.+ instance = cast(Optional[HogFlow], self.instance) or self.context.get("instance")+status = data.get("status")- if status is None and self.instance:- status = self.instance.status+ if status is None and instance:+ status = instance.statusif status != "active":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.+ if instance is not None:+ self.context["existing_encrypted_inputs"] = merge_secret_maps(+ instance.encrypted_inputs, instance.draft_encrypted_inputs+ )+# 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.actions = data.get("actions")- if actions is None and self.instance:- actions = self.instance.actions+ if actions is None and instance:+ actions = instance.actionsself.context["is_dwh_source"] = any(isinstance(action, dict)and action.get("type") == "trigger"@@ -1252,6 +1473,18 @@ class HogFlowSerializer(HogFlowMinimalSerializer):def validate(self, data):instance = cast(Optional[HogFlow], self.instance)is_draft = self.context.get("is_draft")++ # Reject duplicate action ids on any client-submitted actions array (create/update/graph), on+ # every path - not just the surgical /graph endpoint where validate_graph enforces it. Secret+ # recovery is keyed by action id, so a forged duplicate id could otherwise pull another action's+ # secret into an attacker-controlled step. Rejecting here blocks it before anything is written.+ submitted_actions = data.get("actions")+ if isinstance(submitted_actions, list):+ submitted_ids = [a.get("id") for a in submitted_actions if isinstance(a, dict)]+ duplicate_ids = sorted({aid for aid in submitted_ids if aid is not None and submitted_ids.count(aid) > 1})+ if duplicate_ids:+ raise serializers.ValidationError({"actions": f"Duplicate action id(s): {', '.join(duplicate_ids)}"})+actions = data.get("actions", instance.actions if instance else [])# When activating a draft, re-validate actions from the instance with full (non-draft) checks@@ -1263,6 +1496,10 @@ class HogFlowSerializer(HogFlowMinimalSerializer):action_errors = cast(list[Any], action_serializer.errors)raise serializers.ValidationError({"actions": _describe_action_errors(action_errors, instance.actions)})actions = action_serializer.validated_data+ # Re-validation recovers stripped secret inputs back into these actions (mutating the+ # instance's in place). Route them through validated_data so the write re-strips them into+ # encrypted_inputs rather than persisting recovered secrets to the live actions blob.+ data["actions"] = actions# The trigger is derived from the actions. We can trust the action level validation and pull it outtrigger_actions = [action for action in actions if action.get("type") == "trigger"]@@ -1379,15 +1616,26 @@ class HogFlowSerializer(HogFlowMinimalSerializer):return data+ def _strip_secret_inputs(self, validated_data: dict) -> None:+ # Move secret function inputs out of the live `actions` (and the derived `trigger`) into the+ # encrypted_inputs column before persisting. Only runs when this write carries actions - a+ # metadata-only update must not touch stored secrets. The map is rebuilt from the incoming+ # action set, so deleted actions' secrets drop out.+ if "actions" not in validated_data:+ return+ validated_data["encrypted_inputs"] = strip_secrets_from_content(validated_data, template_cache={})+def create(self, validated_data: dict, *args, **kwargs) -> HogFlow:request = self.context["request"]team_id = self.context["team_id"]validated_data["created_by"] = request.uservalidated_data["team_id"] = team_id+ self._strip_secret_inputs(validated_data)return super().create(validated_data=validated_data)def update(self, instance, validated_data):+ self._strip_secret_inputs(validated_data)return super().update(instance, validated_data)@@ -2111,11 +2359,17 @@ class HogFlowViewSet(# network and must not run under the select_for_update lock.if not enabled:return False- old_content = snapshot_flow_content(before)- new_content = {- **old_content,+ raw_old = snapshot_flow_content(before)+ raw_new = {+ **raw_old,**{field: validated_data[field] for field in DRAFT_CONTENT_FIELDS if field in validated_data},}+ # Compare secret-free on both sides. `raw_new` still carries the plaintext secrets validation+ # recovered into `actions` (stripping happens later in save()), while `before` is the persisted+ # stripped snapshot; without this a secret-bearing flow would bump on every actions-carrying save.+ template_cache: TemplateCache = {}+ old_content = strip_content_secrets(raw_old, template_cache)+ new_content = strip_content_secrets(raw_new, template_cache)if new_content == old_content:return Falseinstance.version = (before.version or 0) + 1@@ -2148,9 +2402,18 @@ class HogFlowViewSet(for field in DRAFT_CONTENT_FIELDS:if field in validated_data:draft[field] = validated_data[field]++ # Keep secrets out of the draft snapshot too. When this edit carried the full action set (its+ # secrets recovered in-place), split them into the draft's own encrypted column and strip the+ # snapshot; otherwise the draft's secrets are unchanged. Publish/restore re-attach from here.+ draft_encrypted_inputs = locked.draft_encrypted_inputs+ if "actions" in validated_data:+ draft_encrypted_inputs = strip_secrets_from_content(draft, template_cache={})+instance.draft = draftinstance.draft_updated_at = timezone.now()- instance.save(update_fields=["draft", "draft_updated_at"])+ instance.draft_encrypted_inputs = draft_encrypted_inputs+ instance.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])@extend_schema(request=HogFlowGraphUpdateSerializer, responses={200: HogFlowSerializer})@action(detail=True, methods=["PATCH"])@@ -2430,12 +2693,16 @@ class HogFlowViewSet(locked, before_update, serializer.validated_data.get("actions"), enabled=True)bump = self._stage_revision_bump(locked, before_update, serializer.validated_data, enabled=True)+ # save() runs update(), which recovers the draft's secrets (from the merged live+draft+ # encrypted maps) and re-splits them into the live encrypted_inputs column. The draft's own+ # secret column is then cleared alongside the draft.serializer.save()if bump:self._append_revisions(locked, before_update)locked.draft = Nonelocked.draft_updated_at = None- locked.save(update_fields=["draft", "draft_updated_at"])+ locked.draft_encrypted_inputs = None+ locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])self._maybe_reschedule_timing_edits(before_update, locked)log_activity_from_viewset(self, locked, activity="published", name=locked.name, previous=before_update)@@ -2468,7 +2735,8 @@ class HogFlowViewSet(before_update = HogFlow.objects.get(pk=instance.pk)locked.draft = Nonelocked.draft_updated_at = None- locked.save(update_fields=["draft", "draft_updated_at"])+ locked.draft_encrypted_inputs = None+ locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])log_activity_from_viewset(self, locked, activity="draft_discarded", name=locked.name, previous=before_update)self._emit_resource_edited(locked)@@ -2536,7 +2804,11 @@ class HogFlowViewSet(before_update = HogFlow.objects.get(pk=instance.pk)locked.draft = dict(revision.content)locked.draft_updated_at = timezone.now()- locked.save(update_fields=["draft", "draft_updated_at"])+ # Revision snapshots carry no secrets (they're stripped before snapshotting), so the+ # restored draft re-attaches from the live encrypted_inputs on the follow-up publish.+ # Clear any stale draft secrets from a prior draft so they can't bleed into this one.+ locked.draft_encrypted_inputs = None+ locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])log_activity_from_viewset(self, locked, activity="revision_restored", name=locked.name, previous=before_update)self._emit_resource_edited(locked)@@ -2579,7 +2851,13 @@ class HogFlowViewSet()})- payload["configuration"] = hog_flow.draft+ # The draft's actions are stripped of secrets, and this inline path bypasses the worker's+ # manager (which normally decrypts), so fold the draft's secrets back in before dispatch.+ draft = dict(hog_flow.draft)+ draft_secrets = merge_secret_maps(hog_flow.encrypted_inputs, hog_flow.draft_encrypted_inputs)+ if isinstance(draft.get("actions"), list):+ draft["actions"] = rehydrate_flow_secrets(draft["actions"], draft_secrets)+ payload["configuration"] = draftres = create_hog_flow_invocation_test(team_id=self.team_id,diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex e485ceed2b96..cb8a7e70ecb7 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -1,9 +1,12 @@+import json+from copy import deepcopyfrom datetime import UTC, datetime, timedeltafrom typing import Optionalfrom posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import MagicMock, PropertyMock, patch+from django.db import connectionfrom django.test import override_settingsfrom parameterized import parameterized@@ -27,6 +30,29 @@ from products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job impwebhook_template = MOCK_NODE_TEMPLATES[0]+_REVISIONS_FLAG_PATH = "products.workflows.backend.api.hog_flow.use_workflows_revisions"+_SECRET_TEMPLATE_ID = "template-secret-webhook"+++def _secret_input_template() -> dict:+ # A webhook destination with one secret input (api_key) alongside a non-secret one (url).+ template = deepcopy(webhook_template)+ template["id"] = _SECRET_TEMPLATE_ID+ template["name"] = "Secret Webhook"+ template["inputs_schema"] = [+ {"key": "url", "type": "string", "label": "URL", "secret": False, "hidden": False, "required": True},+ {"key": "api_key", "type": "string", "label": "API key", "secret": True, "hidden": False, "required": False},+ ]+ return template+++def _raw_encrypted_inputs(model_id) -> Optional[str]:+ # The stored (still-encrypted) column value, to prove secrets aren't persisted in plaintext.+ with connection.cursor() as cursor:+ cursor.execute("SELECT encrypted_inputs FROM posthog_hogflow WHERE id = %s", [str(model_id)])+ row = cursor.fetchone()+ return row[0] if row else None+class TestHogFlowAPI(APIBaseTest):def setUp(self):@@ -3659,3 +3685,376 @@ class TestHogFlowGlobalStats(ClickhouseTestMixin, APIBaseTest):)assert res.status_code == status.HTTP_200_OK, res.json()assert {r["workflow_id"] for r in res.json()} == {str(self.flow_a.id)}+++class TestHogFlowSecretInputs(APIBaseTest):+ def setUp(self):+ super().setUp()+ sync_template_to_db(_secret_input_template())++ def _flow_payload(self, api_key: str = "SUPER-SECRET") -> dict:+ return {+ "name": "Secret Flow",+ "actions": [+ {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "event",+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},+ },+ },+ {+ "id": "action_1",+ "name": "action_1",+ "type": "function",+ "config": {+ "template_id": _SECRET_TEMPLATE_ID,+ "inputs": {"url": {"value": "https://example.com"}, "api_key": {"value": api_key}},+ },+ },+ ],+ }++ def _function_inputs(self, flow_json: dict) -> dict:+ return next(a for a in flow_json["actions"] if a["type"] == "function")["config"]["inputs"]++ def _create(self, api_key: str = "SUPER-SECRET") -> str:+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", self._flow_payload(api_key))+ assert response.status_code == 201, response.json()+ return response.json()["id"]++ def test_secret_action_input_is_encrypted_at_rest_and_masked_on_read(self):+ create = self.client.post(f"/api/projects/{self.team.id}/hog_flows", self._flow_payload())+ assert create.status_code == 201, create.json()+ flow_id = create.json()["id"]++ # Masked on the create response and on retrieve; the non-secret input stays visible.+ retrieve = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}")+ for body in (create.json(), retrieve.json()):+ inputs = self._function_inputs(body)+ assert inputs["api_key"] == {"secret": True}+ assert inputs["url"]["value"] == "https://example.com"++ # Split out of the plaintext actions blob and stored encrypted.+ flow = HogFlow.objects.get(id=flow_id)+ db_inputs = next(a for a in flow.actions if a["id"] == "action_1")["config"]["inputs"]+ assert "api_key" not in db_inputs+ assert db_inputs["url"]["value"] == "https://example.com"+ assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == "SUPER-SECRET"+ assert "SUPER-SECRET" not in (_raw_encrypted_inputs(flow_id) or "")++ @parameterized.expand(+ [+ ("resent_mask_preserves", {"secret": True}, "SUPER-SECRET"),+ ("new_value_replaces", {"value": "ROTATED"}, "ROTATED"),+ ]+ )+ def test_secret_update(self, _name, api_key_input, expected_stored):+ flow_id = self._create()++ payload = self._flow_payload()+ self._function_inputs(payload)["api_key"] = api_key_input+ patch_res = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", payload)+ assert patch_res.status_code == 200, patch_res.json()++ flow = HogFlow.objects.get(id=flow_id)+ assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == expected_stored++ def test_metadata_only_update_leaves_secret_intact(self):+ # A PATCH that carries no actions must not clear the stored secret.+ flow_id = self._create()+ patch_res = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"name": "Renamed"})+ assert patch_res.status_code == 200, patch_res.json()+ flow = HogFlow.objects.get(id=flow_id)+ assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == "SUPER-SECRET"++ @patch(_REVISIONS_FLAG_PATH, return_value=True)+ def test_publish_promotes_draft_secret_to_live_without_wiping(self, _flag):+ flow_id = self._create()+ assert (+ self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "active"}).status_code+ == 200+ )++ # Stage a draft (via MCP) that rotates the secret; live must stay untouched until publish.+ draft_payload = self._flow_payload(api_key="ROTATED-IN-DRAFT")+ stage = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"actions": draft_payload["actions"]},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert stage.status_code == 200, stage.json()++ flow = HogFlow.objects.get(id=flow_id)+ assert flow.draft_encrypted_inputs["action_1"]["api_key"]["value"] == "ROTATED-IN-DRAFT"+ assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == "SUPER-SECRET"+ assert "ROTATED-IN-DRAFT" not in json.dumps(flow.draft)++ with patch(+ "products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count", side_effect=Exception("down")+ ):+ confirm_token = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish", {}).json()[+ "confirm_token"+ ]+ publish = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",+ {"confirm": True, "confirm_token": confirm_token},+ )+ assert publish.status_code == 200, publish.json()++ flow.refresh_from_db()+ assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == "ROTATED-IN-DRAFT"+ assert flow.draft is None+ assert flow.draft_encrypted_inputs is None++ def test_activity_log_masks_secret_changes(self):+ flow_id = self._create()+ payload = self._flow_payload(api_key="ROTATED")+ assert self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", payload).status_code == 200++ activity = self.client.get(+ f"/api/projects/{self.team.pk}/activity_log",+ data={"scope": "HogFlow", "item_id": flow_id, "page": "1", "limit": "20"},+ )+ assert activity.status_code == status.HTTP_200_OK+ results = activity.json()["results"]++ # No secret value, old or new, ever appears in the audit trail.+ assert "SUPER-SECRET" not in json.dumps(results)+ assert "ROTATED" not in json.dumps(results)+ # When the encrypted column is diffed, it's masked rather than shown as ciphertext.+ for entry in results:+ for change in entry["detail"].get("changes") or []:+ if change["field"] in ("encrypted_inputs", "draft_encrypted_inputs"):+ assert change["before"] in (None, "masked")+ assert change["after"] in (None, "masked")++ def _publish_confirmed(self, flow_id: str):+ with patch(+ "products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count", side_effect=Exception("down")+ ):+ token = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish", {}).json()[+ "confirm_token"+ ]+ res = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",+ {"confirm": True, "confirm_token": token},+ )+ assert res.status_code == 200, res.json()+ return res++ @patch(_REVISIONS_FLAG_PATH, return_value=True)+ def test_activation_keeps_secret_stripped_from_live_actions(self, _flag):+ # Activating a draft re-validates its actions (recovering secrets); the live actions blob must+ # stay stripped, with the secret only in encrypted_inputs.+ flow_id = self._create()+ assert (+ self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "active"}).status_code+ == 200+ )+ flow = HogFlow.objects.get(id=flow_id)+ db_inputs = next(a for a in flow.actions if a["id"] == "action_1")["config"]["inputs"]+ assert "api_key" not in db_inputs+ assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == "SUPER-SECRET"++ @patch(_REVISIONS_FLAG_PATH, return_value=True)+ def test_restore_reattaches_live_secret_not_historical(self, _flag):+ flow_id = self._create()+ assert (+ self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "active"}).status_code+ == 200+ )++ # Rotate the secret through a published draft so live becomes ROTATED and revision v1 (the+ # pre-rotation content, secrets stripped) is snapshotted.+ rotated = self._flow_payload(api_key="ROTATED")+ assert (+ self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"actions": rotated["actions"]},+ HTTP_X_POSTHOG_CLIENT="mcp",+ ).status_code+ == 200+ )+ self._publish_confirmed(flow_id)+ flow = HogFlow.objects.get(id=flow_id)+ assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == "ROTATED"++ # Restore the pre-rotation revision into the draft, then publish it.+ restore = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions/1/restore", {})+ assert restore.status_code == 200, restore.json()+ flow.refresh_from_db()+ assert flow.draft_encrypted_inputs is None # restore clears stale draft secrets++ # The restored revision snapshot never carried the secret in plaintext.+ revision = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions/1").json()+ rev_inputs = next(a for a in revision["content"]["actions"] if a["type"] == "function")["config"]["inputs"]+ assert "api_key" not in rev_inputs++ self._publish_confirmed(flow_id)++ # The restored graph re-attaches the CURRENT live secret, not the historical one - a rotated+ # credential is never resurrected from a snapshot.+ flow.refresh_from_db()+ assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == "ROTATED"+ assert flow.draft is None++ def test_duplicate_action_id_is_rejected(self):+ # Secret recovery is keyed by action id, so a forged duplicate id must never reach the recovery+ # path - reject it outright on the normal write path (not just the /graph endpoint).+ payload = self._flow_payload()+ payload["actions"].append({**payload["actions"][1], "name": "dupe"}) # second action reuses action_1's id+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", payload)+ assert response.status_code == 400, response.json()+ assert "Duplicate action id" in str(response.json())++ @patch(_REVISIONS_FLAG_PATH, return_value=True)+ def test_noop_resave_of_secret_flow_does_not_bump_revision(self, _flag):+ # Resending the masked graph a GET returned (api_key as {"secret": true}) must be a true no-op:+ # validation recovers the secret back into actions before the strip, so the version-bump compare+ # has to normalize both sides secret-free or every such save spuriously bumps the version.+ flow_id = self._create()+ assert (+ self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "active"}).status_code+ == 200+ )+ # GET returns the stored shape with the secret masked - exactly what a client resubmits.+ masked_actions = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}").json()["actions"]+ assert next(a for a in masked_actions if a["type"] == "function")["config"]["inputs"]["api_key"] == {+ "secret": True+ }++ # First resave settles any create-vs-update shape defaults; the second identical one is the no-op.+ assert (+ self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"actions": masked_actions}+ ).status_code+ == 200+ )+ version_after_first = HogFlow.objects.get(id=flow_id).version++ assert (+ self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"actions": masked_actions}+ ).status_code+ == 200+ )+ flow = HogFlow.objects.get(id=flow_id)+ assert flow.version == version_after_first+ # And the resent mask never wiped the stored secret.+ assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == "SUPER-SECRET"++ def test_test_invocation_rehydrates_resent_secret_in_configuration(self):+ # A test run submits an explicit `configuration` (the masked graph a GET returned). The nested+ # HogFlowSerializer never gets self.instance, so recovery must come via context - otherwise the+ # required secret input 400s or is silently dropped.+ flow_id = self._create()+ config = self._flow_payload()+ self._function_inputs(config)["api_key"] = {"secret": True}++ with patch("products.workflows.backend.api.hog_flow.create_hog_flow_invocation_test") as mock_invoke:+ mock_invoke.return_value = MagicMock(status_code=200, json=lambda: {"status": "success"})+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/invocations/",+ data={+ "globals": {"event": {"event": "$pageview", "distinct_id": "d"}},+ "mock_async_functions": True,+ "configuration": config,+ },+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ sent_actions = mock_invoke.call_args.kwargs["payload"]["configuration"]["actions"]+ sent_inputs = next(a for a in sent_actions if a["type"] == "function")["config"]["inputs"]+ assert sent_inputs["api_key"]["value"] == "SUPER-SECRET"++ def test_function_shaped_trigger_secret_is_masked_on_read(self):+ # A legacy row (pre-encryption) with a webhook trigger carrying a plaintext secret in both the+ # trigger action and the derived `trigger` field. Read-back must mask it on the trigger field,+ # not only inside actions - they're serialized separately.+ trigger_config = {+ "type": "webhook",+ "template_id": _SECRET_TEMPLATE_ID,+ "inputs": {"url": {"value": "https://example.com"}, "api_key": {"value": "TRIGGER-SECRET"}},+ }+ flow = HogFlow.objects.create(+ team=self.team,+ name="Legacy webhook trigger",+ status=HogFlow.State.DRAFT,+ actions=[+ {"id": "trigger_node", "name": "trigger", "type": "trigger", "config": trigger_config},+ {"id": "exit_node", "name": "exit", "type": "exit", "config": {}},+ ],+ trigger=trigger_config,+ edges=[{"from": "trigger_node", "to": "exit_node", "type": "continue"}],+ )++ # Retrieve (full serializer, includes actions).+ body = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow.id}").json()+ assert body["trigger"]["inputs"]["api_key"] == {"secret": True}+ assert "TRIGGER-SECRET" not in json.dumps(body)++ # MCP list (summary serializer) omits actions but still returns trigger, so it can't re-derive+ # the mask from actions - the trigger must be masked independently or the secret leaks here.+ listing = self.client.get(f"/api/projects/{self.team.id}/hog_flows", HTTP_X_POSTHOG_CLIENT="mcp").json()+ row = next(r for r in listing["results"] if r["id"] == str(flow.id))+ assert "actions" not in row+ assert row["trigger"]["inputs"]["api_key"] == {"secret": True}+ assert "TRIGGER-SECRET" not in json.dumps(listing)++ @patch(_REVISIONS_FLAG_PATH, return_value=True)+ def test_legacy_plaintext_secret_stripped_from_revision_snapshot(self, _flag):+ # A row written before encryption shipped still has a plaintext secret in `actions`. The first+ # tracked live edit bootstraps a revision of that prior state, which must be stripped - not carry+ # the plaintext forward into history.+ trigger = {+ "id": "trigger_node",+ "name": "trigger",+ "type": "trigger",+ "config": {+ "type": "event",+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},+ },+ }+ legacy_action = {+ "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"}},+ },+ }+ flow = HogFlow.objects.create(+ team=self.team,+ name="Legacy flow",+ status=HogFlow.State.ACTIVE,+ version=1,+ actions=[trigger, legacy_action],+ trigger=trigger["config"],+ edges=[{"from": "trigger_node", "to": "action_1", "type": "continue"}],+ )++ # A web live edit (flag on) bumps the version and bootstraps a revision of the pre-edit state.+ changed_action = {+ "id": "action_1",+ "name": "action_1",+ "type": "function",+ "config": {+ "template_id": _SECRET_TEMPLATE_ID,+ "inputs": {"url": {"value": "https://changed.example.com"}, "api_key": {"value": "LEGACY-SECRET"}},+ },+ }+ resp = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow.id}",+ {"actions": [trigger, changed_action]},+ )+ assert resp.status_code == 200, resp.json()++ # The bootstrap revision (v1) snapshots the prior legacy state - it must not carry the plaintext.+ revision = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow.id}/revisions/1").json()+ rev_inputs = next(a for a in revision["content"]["actions"] if a["type"] == "function")["config"]["inputs"]+ assert "api_key" not in rev_inputs+ assert "LEGACY-SECRET" not in json.dumps(revision)