: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(cdp): hide credential headers on the webhook destination (#96545)
Georges-Antoine Assia17a28e7bdd6
diff --git a/nodejs/src/cdp/async-functions/fetch-handler.ts b/nodejs/src/cdp/async-functions/fetch-handler.tsindex 13ab9a4ede00..e751c741d472 100644--- a/nodejs/src/cdp/async-functions/fetch-handler.ts+++ b/nodejs/src/cdp/async-functions/fetch-handler.ts@@ -35,6 +35,7 @@ registerAsyncFunction('fetch', {body,headers: pickBy(headers, (v) => typeof v == 'string'),...(fetchOptions?.aws_sigv4 ? { aws_sigv4: fetchOptions.aws_sigv4 } : {}),+ ...(fetchOptions?.secret_headers_input ? { secret_headers_input: fetchOptions.secret_headers_input } : {}),// Mint the webhook id here, once per fetch call, rather than in the// executor: it has to survive every retry of this call (the receiver// dedupes on it) and it must not be shared with another fetch from thediff --git a/nodejs/src/cdp/cdp-e2e.serial.test.ts b/nodejs/src/cdp/cdp-e2e.serial.test.tsindex 6e1f077fb977..ad0d206a0511 100644--- a/nodejs/src/cdp/cdp-e2e.serial.test.ts+++ b/nodejs/src/cdp/cdp-e2e.serial.test.ts@@ -599,6 +599,93 @@ describe('CDP Consumer loop', () => {}})+ // E2E coverage for the webhook template's `secret_headers` input. In production the dictionary+ // exists only in Fernet-encrypted `encrypted_inputs`, the fetch queue carries an input-key+ // reference, and the executor resolves it again on every attempt. The unit tests seed+ // `encrypted_inputs` in memory and never cross the queue, so a reference dropped during+ // serialization, or a merge moved back into the Hog code, is only visible here.+ it('should send webhook template secret headers from encrypted_inputs on the first attempt and the retry', async () => {+ const TOKEN = 'sk_e2e_secret_headers_token_0000'+ const API_KEY = 'e2e-secret-headers-api-key-0000'+ const SECRET_HEADERS_URL = 'https://secret-headers.example.com/hooks'++ let secretHeaderAttempts = 0+ mockFetch.mockImplementation((url: string) => {+ const status = url === SECRET_HEADERS_URL && ++secretHeaderAttempts === 1 ? 500 : 200+ return Promise.resolve({+ status,+ json: () => Promise.resolve({}),+ text: () => Promise.resolve('{}'),+ headers: { 'Content-Type': 'application/json' },+ dump: () => Promise.resolve(),+ })+ })++ const fn = await insertHogFunction({+ type: 'destination',+ hog: webhookTemplate.code,+ bytecode: await compileHog(webhookTemplate.code),+ inputs_schema: webhookTemplate.inputs_schema,+ inputs: {+ url: { value: SECRET_HEADERS_URL },+ method: { value: 'POST' },+ body: { value: { event: '{event.event}' } },+ // Same name as a secret header in another case, so the merge has to replace it+ // instead of sending both.+ headers: {+ value: { 'Content-Type': 'application/json', authorization: 'plaintext-authorization' },+ },+ debug: { value: true },+ },+ encrypted_inputs: hub.encryptedFields.encrypt(+ JSON.stringify({+ secret_headers: { value: { Authorization: `Bearer ${TOKEN}`, 'X-Api-Key': API_KEY } },+ })+ ),+ ...HOG_FILTERS_EXAMPLES.no_filters,+ } as any)++ // The default `fnFetchNoFilters` from beforeEach also matches this event, so select by URL.+ const secretHeaderCalls = (): any[][] =>+ mockFetch.mock.calls.filter((c: any[]) => c[0] === SECRET_HEADERS_URL)++ await eventsConsumer.processBatch([globals])++ await waitForExpect(() => {+ expect(secretHeaderCalls()).toHaveLength(2)+ }, 5000)++ for (const [, opts] of secretHeaderCalls() as [string, any][]) {+ const headers = opts.headers as Record<string, string>+ expect(headers).toMatchObject({+ Authorization: `Bearer ${TOKEN}`,+ 'X-Api-Key': API_KEY,+ 'Content-Type': 'application/json',+ })+ expect(Object.keys(headers).filter((name) => name.toLowerCase() === 'authorization')).toEqual([+ 'Authorization',+ ])+ }++ await waitForExpect(() => {+ const messages = mockProducerObserver+ .getProducedKafkaMessagesForTopic(KAFKA_LOG_ENTRIES)+ .filter((m: any) => m.value.log_source_id === fn.id)+ .map((m: any) => m.value.message as string)+ expect(messages).toContainEqual(+ expect.stringContaining('HTTP fetch failed on attempt 1 with status code 500. Retrying.')+ )+ expect(messages).toContainEqual(expect.stringContaining('Response, 200'))+ const requestLogs = messages.filter((message) => message.startsWith('Request, '))+ expect(requestLogs).toHaveLength(1)+ expect(requestLogs[0]).toContain('"secret_headers_input":"secret_headers"')+ // Log redaction masks values but not header names. The name is what appears if the+ // template merges the secret headers into `payload.headers` instead of passing the reference.+ expect(requestLogs[0]).not.toContain('X-Api-Key')+ expect(JSON.stringify(messages)).not.toContain(TOKEN)+ }, 5000)+ })+it('should handle fetch failures with retries', async () => {mockFetch.mockImplementation(() => {return Promise.resolve({diff --git a/nodejs/src/cdp/schema/cyclotron.ts b/nodejs/src/cdp/schema/cyclotron.tsindex a592478213a5..9e02f6786226 100644--- a/nodejs/src/cdp/schema/cyclotron.ts+++ b/nodejs/src/cdp/schema/cyclotron.ts@@ -141,6 +141,8 @@ export const CyclotronInvocationQueueParametersFetchSchema = z.object({headers: z.record(z.string(), z.string()).optional(),aws_sigv4: CyclotronInvocationQueueParametersFetchAwsSigV4Schema.optional(),standard_webhooks: CyclotronInvocationQueueParametersFetchStandardWebhooksSchema.optional(),+ // An input-key reference, like the `*_input` fields above, so credential header values stay out of the fetch parameters.+ secret_headers_input: z.string().optional(),})export const MAX_WORKFLOW_EMAIL_SENDERS = 10diff --git a/nodejs/src/cdp/services/hog-executor-async.service.ts b/nodejs/src/cdp/services/hog-executor-async.service.tsindex c6930cdcbc2d..89b2a8d07a9b 100644--- a/nodejs/src/cdp/services/hog-executor-async.service.ts+++ b/nodejs/src/cdp/services/hog-executor-async.service.ts@@ -22,6 +22,7 @@ import { cdpTrackedFetch, fetchErrorDetail, isFetchResponseRetriable } from '../import { createInvocationResult } from '../utils/invocation-utils'import { isNonFailureStatus } from '../utils/non-failure-status-codes'import { ScopedServiceJwt } from '../utils/scoped-service-jwt'+import { mergeSecretHeaders, resolveSecretHeaders } from '../utils/secret-headers'import { resolveStandardWebhooksKey, signStandardWebhooksRequest } from '../utils/standard-webhooks'import { HogExecutorExecuteOptions, HogExecutorPreviousResult, HogExecutorService } from './hog-executor.service'import { HogInputsService } from './hog-inputs.service'@@ -454,6 +455,17 @@ export class HogExecutorAsyncService {}let signedHeaders = headers++ // Secret headers are merged before signing so that the signatures cover them, and they are never written+ // back to queueParameters, so every attempt resolves them again from the hog function.+ if (params.secret_headers_input) {+ const resolved = resolveSecretHeaders(params.secret_headers_input, invocation.hogFunction)+ if (!resolved.ok) {+ return failSigning(resolved.error)+ }+ signedHeaders = mergeSecretHeaders(signedHeaders, resolved.headers)+ }+if (params.aws_sigv4) {const resolved = resolveAwsSigV4Credentials(params.aws_sigv4, invocation.hogFunction)if (!resolved.ok) {@@ -463,7 +475,7 @@ export class HogExecutorAsyncService {method,url: params.url,body: params.body ?? '',- headers,+ headers: signedHeaders,credentials: resolved.credentials,})}diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex bd0392f0a3a4..8fdb14ac10ef 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -1695,6 +1695,105 @@ describe('Hog Executor', () => {})})+ describe('secret_headers_input', () => {+ const seedSecretHeadersInput = (invocation: CyclotronJobInvocationHogFunction) => {+ invocation.hogFunction.encrypted_inputs = {+ ...(invocation.hogFunction.encrypted_inputs ?? {}),+ secret_headers: { value: { authorization: 'Bearer sk_test_token', 'X-Api-Key': 'key_test_token' } },+ } as any+ }++ it('merges the resolved headers into every attempt without persisting them to the queue payload', async () => {+ const receivedHeaders: Record<string, string | string[] | undefined>[] = []+ let callCount = 0+ mockRequest.mockImplementation((req: any, res: any) => {+ receivedHeaders.push(req.headers)+ callCount+++ res.writeHead(callCount === 1 ? 500 : 200, { 'Content-Type': 'text/plain' })+ res.end('ok')+ })++ const invocation = await createFetchInvocation({+ url: `${baseUrl}/`,+ method: 'POST',+ body: '{}',+ headers: { 'Content-Type': 'application/json', Authorization: 'plaintext' },+ secret_headers_input: 'secret_headers',+ })+ seedSecretHeadersInput(invocation)++ let result = await executor.executeFetch(invocation)+ expect(result.invocation.state.attempts).toBe(1)+ expect(JSON.stringify(result.invocation.queueParameters)).not.toContain('sk_test_token')++ result = await executor.executeFetch(result.invocation)++ expect(result.error).toBeUndefined()+ expect(receivedHeaders).toHaveLength(2)+ for (const headers of receivedHeaders) {+ expect(headers['authorization']).toBe('Bearer sk_test_token')+ expect(headers['x-api-key']).toBe('key_test_token')+ expect(headers['content-type']).toBe('application/json')+ }+ })++ it('keeps the resolved headers inside an AWS SigV4 signed request', async () => {+ let received: Record<string, string | string[] | undefined> = {}+ mockRequest.mockImplementation((req: any, res: any) => {+ received = req.headers+ res.writeHead(200, { 'Content-Type': 'text/plain' })+ res.end('ok')+ })++ const invocation = await createFetchInvocation({+ url: `${baseUrl}/`,+ method: 'POST',+ body: '{}',+ headers: { 'Content-Type': 'application/x-amz-json-1.1' },+ aws_sigv4: {+ service: 'kinesis',+ region: 'us-east-1',+ access_key_id_input: 'aws_access_key_id',+ secret_access_key_input: 'aws_secret_access_key',+ },+ secret_headers_input: 'secret_headers',+ })+ seedSecretHeadersInput(invocation)+ invocation.hogFunction.encrypted_inputs = {+ ...invocation.hogFunction.encrypted_inputs,+ aws_access_key_id: { value: 'AKIDEXAMPLE' },+ aws_secret_access_key: { value: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY' },+ } as any++ const result = await executor.executeFetch(invocation)++ expect(result.error).toBeUndefined()+ expect(received['x-api-key']).toBe('key_test_token')+ expect(received['authorization']).toMatch(/^AWS4-HMAC-SHA256 .*SignedHeaders=[a-z0-9;-]*x-api-key/)+ })++ it.each([+ ['the secret headers input is missing', undefined],+ ['a secret header value is not text', { value: { Authorization: 12345 } }],+ ])('errors loudly instead of sending the request when %s', async (_name, secretHeaders) => {+ const invocation = await createFetchInvocation({+ url: `${baseUrl}/`,+ method: 'POST',+ body: '{}',+ secret_headers_input: 'secret_headers',+ })+ if (secretHeaders) {+ invocation.hogFunction.encrypted_inputs = { secret_headers: secretHeaders } as any+ }++ const result = await executor.executeFetch(invocation)++ expect(mockRequest).not.toHaveBeenCalled()+ expect(result.error).toBeInstanceOf(Error)+ expect(result.error.message).toContain('secret_headers')+ })+ })+it('respects maxFetchRetries option to disable retries', async () => {mockRequest.mockImplementation((req: any, res: any) => {res.writeHead(500, { 'Content-Type': 'text/plain' })diff --git a/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.test.ts b/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.test.tsindex f53f960eb9c6..aa173e407ae7 100644--- a/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.test.ts+++ b/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.test.ts@@ -68,6 +68,22 @@ describe('webhook template', () => {expect(JSON.stringify(params)).not.toContain('MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw')})+ it('passes a secret headers reference, not the values, to the fetch queue', async () => {+ const response = await tester.invoke({+ url: 'https://example.com',+ headers: { 'Content-Type': 'application/json' },+ secret_headers: { Authorization: 'Bearer sk_test_token' },+ debug: true,+ })++ expect(response.error).toBeUndefined()+ const params = response.invocation.queueParameters as any+ expect(params.secret_headers_input).toEqual('secret_headers')+ expect(params.headers).toEqual({ 'Content-Type': 'application/json' })+ expect(JSON.stringify(params)).not.toContain('Authorization')+ expect(response.logs.map((l) => l.message).join('\n')).not.toContain('Authorization')+ })+it('should log details of given', async () => {let response = await tester.invoke({url: 'https://example.com?v={event.properties.$lib_version}',diff --git a/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.ts b/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.tsindex 13e80e94dac3..f388f556b626 100644--- a/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.ts+++ b/nodejs/src/cdp/templates/_destinations/webhook/webhook.template.ts@@ -23,6 +23,10 @@ if (not empty(inputs.signing_secret)) {}}+if (not empty(inputs.secret_headers)) {+ payload['secret_headers_input'] := 'secret_headers'+}+if (inputs.debug) {print('Request', inputs.url, payload)}@@ -93,7 +97,18 @@ if (inputs.debug) {secret: false,required: false,default: { 'Content-Type': 'application/json' },- description: 'HTTP headers to send in the request.',+ description:+ 'HTTP headers to send in the request. Put API tokens and other credentials in Secret headers instead.',+ },+ {+ key: 'secret_headers',+ type: 'dictionary',+ label: 'Secret headers',+ secret: true,+ required: false,+ templating: false,+ description:+ 'HTTP headers that hold a credential, such as an API token. These are encrypted, hidden after saving, and kept out of the logs. Values are sent exactly as entered, without templating, and replace a plaintext header of the same name.',},{key: 'signing_secret',diff --git a/nodejs/src/cdp/utils.test.ts b/nodejs/src/cdp/utils.test.tsindex 3c849a9ea442..058eb954d46f 100644--- a/nodejs/src/cdp/utils.test.ts+++ b/nodejs/src/cdp/utils.test.ts@@ -174,6 +174,13 @@ describe('Utils', () => {expect(getSensitiveValues(hogFunction, { connection: value })).toContain('nested-private-key')})+ it('masks the bare token of every secret dictionary entry, whatever the header name', () => {+ const hogFunction: any = { inputs_schema: [{ key: 'secret_headers', type: 'dictionary', secret: true }] }+ expect(+ getSensitiveValues(hogFunction, { secret_headers: { 'X-Custom-Auth': 'Bearer sk_live_abc' } })+ ).toContain('sk_live_abc')+ })+it('masks a credential-named input that the stored schema leaves non-secret', () => {const hogFunction: any = { inputs_schema: [{ key: 'apiKey', type: 'string', secret: false }] }expect(getSensitiveValues(hogFunction, { apiKey: 'stale-schema-key' })).toEqual(['stale-schema-key'])diff --git a/nodejs/src/cdp/utils.ts b/nodejs/src/cdp/utils.tsindex fb6181e1e765..78401817b4b8 100644--- a/nodejs/src/cdp/utils.ts+++ b/nodejs/src/cdp/utils.ts@@ -356,12 +356,13 @@ export const getSensitiveValues = (hogFunction: HogFunctionType, inputs: Record<// A webhook's `headers` is free-form, so it is not marked secret, but it is where a credential// most often sits — and a webhook whose credential is rejected is exactly the case that gets it// quoted back. Mask values under header names that carry one, whatever the secret flag says.- const collectCredentialHeaders = (obj: any): void => {+ // Every entry of a secret dictionary is a credential, whatever its header name.+ const collectCredentialHeaders = (obj: any, anyHeaderName: boolean): void => {if (!obj || typeof obj !== 'object') {return}Object.entries(obj).forEach(([key, val]) => {- if (typeof val !== 'string' || !CREDENTIAL_HEADER_NAMES.test(key.trim())) {+ if (typeof val !== 'string' || (!anyHeaderName && !CREDENTIAL_HEADER_NAMES.test(key.trim()))) {return}values.push(val)@@ -374,8 +375,8 @@ export const getSensitiveValues = (hogFunction: HogFunctionType, inputs: Record<}hogFunction.inputs_schema?.forEach((schema) => {- if (schema.type === 'dictionary' && !schema.secret) {- collectCredentialHeaders(inputs[schema.key])+ if (schema.type === 'dictionary') {+ collectCredentialHeaders(inputs[schema.key], !!schema.secret)}// A function keeps the schema it was saved with, so a credential input that a later template// version marks secret is still `secret: false` on older functions.diff --git a/nodejs/src/cdp/utils/secret-headers.ts b/nodejs/src/cdp/utils/secret-headers.tsnew file mode 100644index 000000000000..45913e67fe83--- /dev/null+++ b/nodejs/src/cdp/utils/secret-headers.ts@@ -0,0 +1,48 @@+import { HogFunctionType } from '../types'+import { resolveHogFunctionInputValue } from './hog-function-inputs'++export type ResolvedSecretHeaders = { ok: true; headers: Record<string, string> } | { ok: false; error: string }++export function resolveSecretHeaders(+ inputKey: string,+ hogFunction: Pick<HogFunctionType, 'inputs' | 'encrypted_inputs'>+): ResolvedSecretHeaders {+ const value = resolveHogFunctionInputValue(hogFunction, inputKey)++ if (typeof value !== 'object' || value === null || Array.isArray(value)) {+ return {+ ok: false,+ error: `Secret headers failed: input ${inputKey} not found on hog function or not a dictionary. Refusing to send the request without its credential headers.`,+ }+ }++ const headers: Record<string, string> = {}+ for (const [name, headerValue] of Object.entries(value)) {+ if (typeof headerValue !== 'string') {+ return {+ ok: false,+ error: `Secret headers failed: the value of ${name} in input ${inputKey} is not text. Refusing to send the request without its credential headers.`,+ }+ }+ headers[name] = headerValue+ }++ return { ok: true, headers }+}++// Some receivers read the first of two same-name headers, so a plaintext header a secret header also sets is dropped.+export function mergeSecretHeaders(+ headers: Record<string, string>,+ secretHeaders: Record<string, string>+): Record<string, string> {+ const secretNames = new Set(Object.keys(secretHeaders).map((name) => name.toLowerCase()))++ const merged: Record<string, string> = {}+ for (const [name, value] of Object.entries(headers)) {+ if (!secretNames.has(name.toLowerCase())) {+ merged[name] = value+ }+ }++ return { ...merged, ...secretHeaders }+}diff --git a/nodejs/src/cdp/workflows-e2e.serial.test.ts b/nodejs/src/cdp/workflows-e2e.serial.test.tsindex f49f426a9c20..4846d3d62f79 100644--- a/nodejs/src/cdp/workflows-e2e.serial.test.ts+++ b/nodejs/src/cdp/workflows-e2e.serial.test.ts@@ -24,6 +24,7 @@ import express from 'ultimate-express'import { HogFlow } from '~/cdp/schema/hogflow'import { template as createTaskTemplate } from '~/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template'+import { template as webhookTemplate } from '~/cdp/templates/_destinations/webhook/webhook.template'import { setupExpressApp } from '~/common/api/router'import {KAFKA_APP_METRICS_2,@@ -254,6 +255,22 @@ describe('Workflows E2E (postgres-v2)', () => {await backgroundTask}+ /**+ * Mirrors what the hog flow API stores on save: a secret input is stripped out of the plaintext+ * `actions` and kept Fernet-encrypted in `encrypted_inputs`, keyed by action id and then input key.+ */+ async function setWorkflowEncryptedInputs(+ workflowId: string,+ secretsByActionId: Record<string, Record<string, { value: unknown }>>+ ): Promise<void> {+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogflow SET encrypted_inputs = $2 WHERE id = $1`,+ [workflowId, hub.encryptedFields.encrypt(JSON.stringify(secretsByActionId))],+ 'setWorkflowEncryptedInputs'+ )+ }+/*** Build the row-scoped globals the DWH consumer produces for a synced warehouse row: a synthetic* event named `$warehouse_source_row` with no real person, and the source table on@@ -506,19 +523,7 @@ describe('Workflows E2E (postgres-v2)', () => {],})- // Mirrors what the hog flow API stores on save: the secret input is stripped out of the- // plaintext `actions` and kept Fernet-encrypted in `encrypted_inputs`, keyed by action id.- await hub.postgres.query(- PostgresUse.COMMON_WRITE,- `UPDATE posthog_hogflow SET encrypted_inputs = $2 WHERE id = $1`,- [- workflowId,- hub.encryptedFields.encrypt(- JSON.stringify({ send_with_secret: { api_key: { value: secretApiKey } } })- ),- ],- 'setWorkflowEncryptedInputs'- )+ await setWorkflowEncryptedInputs(workflowId, { send_with_secret: { api_key: { value: secretApiKey } } })globals = createGlobals()})@@ -550,6 +555,137 @@ describe('Workflows E2E (postgres-v2)', () => {})})+ describe('workflow with webhook secret headers: trigger → webhook → exit', () => {+ const token = 'workflows-e2e-secret-headers-token-0000'+ const apiKey = 'workflows-e2e-secret-headers-api-key-0000'+ const webhookUrl = 'https://example.com/secret-headers-webhook'+ let workflowId: string+ let releaseRetry: () => void = () => {}++ const fetchResponse = (status: number) => ({+ status,+ json: () => Promise.resolve({}),+ text: () => Promise.resolve('{}'),+ headers: { 'Content-Type': 'application/json' },+ dump: () => Promise.resolve(),+ })++ beforeEach(async () => {+ await insertHogFunctionTemplate(hub.postgres, {+ id: 'template-webhook',+ name: webhookTemplate.name,+ code: webhookTemplate.code,+ inputs_schema: webhookTemplate.inputs_schema,+ })++ workflowId = await createWorkflow({+ actions: {+ trigger: trigger(),+ send_webhook: {+ type: 'function',+ config: {+ template_id: 'template-webhook',+ inputs: {+ url: { value: webhookUrl },+ method: { value: 'POST' },+ body: { value: { event: '{event.event}' } },+ // Same name as a secret header in another case, so the merge has to+ // replace it instead of sending both.+ headers: {+ value: {+ 'Content-Type': 'application/json',+ authorization: 'plaintext-authorization',+ },+ },+ debug: { value: true },+ },+ },+ },+ exit: exitAction(),+ },+ edges: [+ { from: 'trigger', to: 'send_webhook', type: 'continue' },+ { from: 'send_webhook', to: 'exit', type: 'continue' },+ ],+ })+ await setWorkflowEncryptedInputs(workflowId, {+ send_webhook: { secret_headers: { value: { Authorization: `Bearer ${token}`, 'X-Api-Key': apiKey } } },+ })++ // The first attempt fails so the fetch parameters are written to the job row for the retry.+ // The retry is then held open until the test releases it, so the row can be read while it+ // still holds the state the worker resumed from.+ let attempts = 0+ const retryGate = new Promise<void>((resolve) => {+ releaseRetry = resolve+ })+ mockFetch.mockImplementation(async () => {+ attempts += 1+ if (attempts > 1) {+ await retryGate+ }+ return fetchResponse(attempts === 1 ? 500 : 200)+ })+ globals = createGlobals()+ })++ it('merges the decrypted secret headers on both attempts and keeps them off the fetch parameters', async () => {+ try {+ await triggerWorkflow(globals)++ await waitForExpect(() => {+ expect(mockFetch).toHaveBeenCalledTimes(2)+ }, 10000)++ // Only `queueParameters` is asserted on. `state.globals.inputs` carries every resolved input,+ // which is a property of the whole job payload and not of this template.+ const blobs = (await queryCyclotronJobs()).map((row: any) =>+ parseJSON((row.state as Buffer).toString('utf-8'))+ )+ const fetchBlob = blobs.find((blob: any) => blob.queueParameters?.type === 'fetch')+ expect(fetchBlob).toBeDefined()+ expect(fetchBlob.queueParameters).toMatchObject({+ secret_headers_input: 'secret_headers',+ headers: { 'Content-Type': 'application/json', authorization: 'plaintext-authorization' },+ })+ expect(JSON.stringify(fetchBlob.queueParameters)).not.toContain(token)+ expect(JSON.stringify(fetchBlob.queueParameters)).not.toContain(apiKey)+ } finally {+ releaseRetry()+ }++ for (const [url, options] of mockFetch.mock.calls as [string, any][]) {+ expect(url).toEqual(webhookUrl)+ expect(options.headers).toMatchObject({+ Authorization: `Bearer ${token}`,+ 'X-Api-Key': apiKey,+ 'Content-Type': 'application/json',+ })+ expect(Object.keys(options.headers).filter((name) => name.toLowerCase() === 'authorization')).toEqual([+ 'Authorization',+ ])+ }++ await waitForExpect(() => {+ const messages = mockProducerObserver+ .getProducedKafkaMessagesForTopic(KAFKA_LOG_ENTRIES)+ .filter((m: any) => m.value.log_source_id === workflowId)+ .map((m: any) => m.value.message as string)+ expect(messages).toContainEqual(+ expect.stringContaining('HTTP fetch failed on attempt 1 with status code 500. Retrying.')+ )+ expect(messages).toContainEqual(expect.stringContaining('Response, 200'))+ const requestLogs = messages.filter((message) => message.includes('Request, '))+ expect(requestLogs).toHaveLength(1)+ expect(requestLogs[0]).toContain('"secret_headers_input":"secret_headers"')+ // Log redaction masks values but not header names. The name is what appears if the+ // template merges the secret headers into `payload.headers` instead of passing the reference.+ expect(requestLogs[0]).not.toContain('X-Api-Key')+ expect(JSON.stringify(messages)).not.toContain(token)+ }, 5000)+ })+ })+describe('delay workflow: trigger → delay → function → exit', () => {beforeEach(async () => {await createWorkflow({diff --git a/nodejs/tests/fixtures/hog-bytecode/559b81a6d527960bd76052639f473bbedd23c416a2ea4d5a3990e4c0281bdd4a.json b/nodejs/tests/fixtures/hog-bytecode/559b81a6d527960bd76052639f473bbedd23c416a2ea4d5a3990e4c0281bdd4a.jsonnew file mode 100644index 000000000000..fb370efd90e2--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/559b81a6d527960bd76052639f473bbedd23c416a2ea4d5a3990e4c0281bdd4a.json@@ -0,0 +1 @@+["_H",1,32,"headers",32,"headers",32,"inputs",1,2,32,"body",32,"body",32,"inputs",1,2,32,"method",32,"method",32,"inputs",1,2,42,3,32,"signing_secret",32,"inputs",1,2,2,"empty",1,5,40,11,36,0,32,"standard_webhooks",32,"secret_input",32,"signing_secret",42,1,46,32,"secret_headers",32,"inputs",1,2,2,"empty",1,5,40,7,36,0,32,"secret_headers_input",32,"secret_headers",46,32,"debug",32,"inputs",1,2,40,14,32,"Request",32,"url",32,"inputs",1,2,36,0,2,"print",3,35,32,"url",32,"inputs",1,2,36,0,2,"fetch",2,33,400,36,1,32,"status",45,14,40,21,32,"Webhook failed with status ",36,1,32,"status",45,32,": ",36,1,32,"body",45,2,"concat",4,2,"Error",1,49,32,"debug",32,"inputs",1,2,40,16,32,"Response",36,1,32,"status",45,36,1,32,"body",45,2,"print",3,35,35,35]diff --git a/playwright/e2e/webhook-secret-headers.spec.ts b/playwright/e2e/webhook-secret-headers.spec.tsnew file mode 100644index 000000000000..b87b9a54473a--- /dev/null+++ b/playwright/e2e/webhook-secret-headers.spec.ts@@ -0,0 +1,214 @@+import { Page } from '@playwright/test'++import { PlaywrightWorkspaceSetupResult, expect, test } from '../utils/workspace-test-base'++const TEMPLATE_ID = 'template-webhook-secret-headers-e2e'+const SECRET_HEADER_VALUE = 'Bearer e2e-secret-headers-token-0000'+const MASKED_MESSAGE = 'This value is secret and is not displayed here.'+const TRIGGER_NODE_ID = 'trigger_node'+const WEBHOOK_NODE_ID = 'webhook_node'+const EXIT_NODE_ID = 'exit_node'++// The destination editor and the workflow builder render a template's inputs through the same+// component, so a `secret: true` dictionary input (the webhook template's "Secret headers") is the+// one place a person can put a credential header. Nothing below the browser proves that both+// editors let a person enter one, save it, and read it back masked instead of in plaintext, or that+// the marker the editor sends on a later save keeps the stored secret instead of wiping it.+function buildWorkflowWithWebhookStep(): Record<string, any> {+ return {+ name: `Webhook secret headers ${Date.now()}`,+ actions: [+ {+ id: TRIGGER_NODE_ID,+ type: 'trigger',+ name: 'Trigger',+ description: 'Triggered by an event',+ created_at: 0,+ updated_at: 0,+ config: {+ type: 'event',+ filters: { events: [{ id: '$pageview', type: 'events' }] },+ },+ },+ {+ id: WEBHOOK_NODE_ID,+ type: 'function',+ name: 'Webhook',+ description: '',+ created_at: 0,+ updated_at: 0,+ config: {+ template_id: TEMPLATE_ID,+ inputs: {},+ },+ },+ {+ id: EXIT_NODE_ID,+ type: 'exit',+ name: 'Exit',+ description: 'Default exit',+ created_at: 0,+ updated_at: 0,+ config: { reason: 'Default exit' },+ },+ ],+ edges: [+ { from: TRIGGER_NODE_ID, to: WEBHOOK_NODE_ID, type: 'continue' },+ { from: WEBHOOK_NODE_ID, to: EXIT_NODE_ID, type: 'continue' },+ ],+ conversion: { window_minutes: null, filters: [] },+ exit_condition: 'exit_only_at_end',+ version: 1,+ status: 'draft',+ }+}++async function createWorkflowViaApi(page: Page, teamId: string): Promise<string> {+ return await page.evaluate(+ async ({ teamId, payload }) => {+ const csrfToken =+ document.cookie+ .split(';')+ .map((c) => c.trim())+ .find((c) => c.startsWith('posthog_csrftoken='))+ ?.split('=')+ .slice(1)+ .join('=') || ''+ if (!csrfToken) {+ throw new Error('CSRF cookie missing')+ }+ const response = await fetch(`/api/environments/${teamId}/hog_flows/`, {+ method: 'POST',+ credentials: 'include',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': decodeURIComponent(csrfToken),+ },+ body: JSON.stringify(payload),+ })+ if (!response.ok) {+ throw new Error(`hog_flows POST failed: ${response.status} ${await response.text()}`)+ }+ const data = await response.json()+ return data.id as string+ },+ { teamId, payload: buildWorkflowWithWebhookStep() }+ )+}++async function addSecretHeader(page: Page): Promise<void> {+ // The label renders as a button whose accessible name includes the optional marker.+ await expect(page.getByRole('button', { name: 'Secret headers (optional)' })).toBeVisible({ timeout: 60000 })+ await page.getByRole('button', { name: 'Add entry' }).click()+ await page.getByPlaceholder('Key').fill('Authorization')+ await page.getByPlaceholder('Value').fill(SECRET_HEADER_VALUE)+}++async function expectSecretHeaderMasked(page: Page): Promise<void> {+ await expect(page.getByText(MASKED_MESSAGE)).toBeVisible({ timeout: 15000 })+ await expect(page.getByPlaceholder('Value')).toHaveCount(0)+ await expect(page.getByText(SECRET_HEADER_VALUE)).toHaveCount(0)+ const inputValues = await page+ .locator('input')+ .evaluateAll((inputs) => inputs.map((input) => (input as HTMLInputElement).value))+ expect(inputValues).not.toContain(SECRET_HEADER_VALUE)+}++test.describe('Webhook secret headers', () => {+ test.describe.configure({ mode: 'serial' })+ test.setTimeout(180 * 1000)++ let workspace: PlaywrightWorkspaceSetupResult | null = null++ test.beforeAll(async ({ playwrightSetup }) => {+ workspace = await playwrightSetup.createWorkspace({+ skip_onboarding: true,+ no_demo_data: true,+ })+ // Playwright CI doesn't run sync_hog_function_templates, so the templates table is empty.+ // A dedicated id keeps the seed from being skipped on a database that already holds the+ // real `template-webhook`, and one dictionary input keeps the field locators unambiguous.+ await playwrightSetup.seedHogFunctionTemplate({+ template_id: TEMPLATE_ID,+ name: 'Webhook with secret headers (e2e)',+ status: 'stable',+ template_type: 'destination',+ inputs_schema: [+ {+ key: 'url',+ type: 'string',+ label: 'Webhook URL',+ required: false,+ default: 'https://example.com/hooks',+ description: 'The URL to send the request to.',+ },+ {+ key: 'secret_headers',+ type: 'dictionary',+ label: 'Secret headers',+ secret: true,+ required: false,+ templating: false,+ description: 'HTTP headers that hold a credential, such as an API token.',+ },+ ],+ })+ })++ test.beforeEach(async ({ page, playwrightSetup }) => {+ await playwrightSetup.loginAndNavigateToTeam(page, workspace!)+ })++ test('a secret header entered in the destination editor is stored encrypted and read back masked', async ({+ page,+ }) => {+ await test.step('create a destination from the template with a secret header', async () => {+ await page.goto(`/functions/new/${TEMPLATE_ID}`)+ await addSecretHeader(page)+ // The button reads "Create & enable" and is rendered in the header and below the form.+ await page+ .getByRole('button', { name: /^Create/ })+ .first()+ .click()+ await page.waitForURL(/\/functions\/(?!new\/)[^/?#]+/, { timeout: 30000 })+ })++ await test.step('the saved destination shows the secret as masked', async () => {+ await page.reload()+ await expectSecretHeaderMasked(page)+ })++ await test.step('saving again without retyping the secret keeps it', async () => {+ await page.getByRole('switch', { name: 'Enable destination' }).click()+ await page.getByRole('button', { name: /^Save/ }).first().click()+ await expect(page.getByRole('button', { name: /^Save/ }).first()).toBeDisabled({ timeout: 15000 })+ await page.reload()+ await expectSecretHeaderMasked(page)+ })+ })++ test('a secret header entered in the workflow builder is stored encrypted and read back masked', async ({+ page,+ }) => {+ const workflowId = await createWorkflowViaApi(page, workspace!.team_id)++ await test.step('open the webhook step and add a secret header', async () => {+ await page.goto(`/workflows/${workflowId}/workflow`)+ await page.waitForSelector('[data-attr="workflow-editor"]', { timeout: 30000 })+ await page.locator(`[data-testid="rf__node-${WEBHOOK_NODE_ID}"]`).click()+ await addSecretHeader(page)+ })++ await test.step('save the workflow', async () => {+ await page.getByTestId('workflow-save').click()+ await expect(page.getByTestId('workflow-save')).toBeDisabled({ timeout: 15000 })+ })++ await test.step('the saved step shows the secret as masked', async () => {+ await page.reload()+ await page.waitForSelector('[data-attr="workflow-editor"]', { timeout: 30000 })+ await page.locator(`[data-testid="rf__node-${WEBHOOK_NODE_ID}"]`).click()+ await expectSecretHeaderMasked(page)+ })+ })+})diff --git a/posthog/management/commands/sync_hog_function_templates.py b/posthog/management/commands/sync_hog_function_templates.pyindex 404d68b14e23..c7106b12749f 100644--- a/posthog/management/commands/sync_hog_function_templates.py+++ b/posthog/management/commands/sync_hog_function_templates.py@@ -2,7 +2,7 @@ import timeimport dataclassesfrom django.conf import settings-from django.core.management.base import BaseCommand+from django.core.management.base import BaseCommand, CommandErrorimport structlog@@ -103,23 +103,22 @@ class Command(BaseCommand):current_template_ids.add(default_dict["id"])# Process templates from Node.js+ nodejs_error: str | None = Nonetry:response = get_hog_function_templates()- if response.status_code == 200:- nodejs_templates_json = response.json()- for template_data in nodejs_templates_json:- if not self.should_include_nodejs_template(template_data):- continue-- all_templates.append(template_data)- current_template_ids.add(template_data["id"])- else:- self.stdout.write(- self.style.WARNING(f"Failed to fetch Node.js templates. Status code: {response.status_code}")- )+ if response.status_code != 200:raise Exception(f"Failed to fetch Node.js templates. Status code: {response.status_code}")++ for template_data in response.json():+ if not self.should_include_nodejs_template(template_data):+ continue++ total_templates += 1+ all_templates.append(template_data)+ current_template_ids.add(template_data["id"])except Exception as e:- self.stdout.write(self.style.ERROR(f"Error fetching Node.js templates: {str(e)}"))+ nodejs_error = str(e)+ self.stdout.write(self.style.ERROR(f"Error fetching Node.js templates: {nodejs_error}"))for template_data in all_templates:try:@@ -135,33 +134,42 @@ class Command(BaseCommand):exc_info=True,)- try:- existing_templates = HogFunctionTemplate.objects.values_list("template_id", flat=True).distinct()+ # Every coming-soon template comes from the Node.js service, so after a failed fetch current_template_ids+ # holds none of them and the cleanup below would delete every coming-soon template in the database.+ if nodejs_error is not None:+ self.stdout.write(+ self.style.WARNING("Skipping cleanup of unused templates because the Node.js fetch failed")+ )+ else:+ try:+ existing_templates = HogFunctionTemplate.objects.values_list("template_id", flat=True).distinct()- candidates_for_deletion = {- tid for tid in existing_templates if tid.startswith("coming-soon-")- } - current_template_ids+ candidates_for_deletion = {+ tid for tid in existing_templates if tid.startswith("coming-soon-")+ } - current_template_ids- if candidates_for_deletion:- templates_to_delete = HogFunctionTemplate.objects.filter(template_id__in=candidates_for_deletion)- deleted_count += templates_to_delete.delete()[0]+ if candidates_for_deletion:+ templates_to_delete = HogFunctionTemplate.objects.filter(template_id__in=candidates_for_deletion)+ deleted_count += templates_to_delete.delete()[0]- self.stdout.write(- self.style.WARNING(- f"Deleted {deleted_count} unused templates: {', '.join(candidates_for_deletion)}"+ self.stdout.write(+ self.style.WARNING(+ f"Deleted {deleted_count} unused templates: {', '.join(candidates_for_deletion)}"+ ))- )- except Exception as e:- logger.error("Error checking for unused templates", error=str(e), exc_info=True)+ except Exception as e:+ logger.error("Error checking for unused templates", error=str(e), exc_info=True)# Output summaryduration = time.time() - start_time- self.stdout.write(- self.style.SUCCESS(- f"Hog function template sync complete in {duration:.2f}s. "- f"Templates: {total_templates}, "- f"Created or updated: {updated_count}, "- f"Deleted: {deleted_count}, "- f"Errors: {error_count}"- )+ summary = (+ f"Hog function template sync complete in {duration:.2f}s. "+ f"Templates: {total_templates}, "+ f"Created or updated: {updated_count}, "+ f"Deleted: {deleted_count}, "+ f"Errors: {error_count}")+ self.stdout.write(self.style.ERROR(summary) if nodejs_error is not None else self.style.SUCCESS(summary))++ if nodejs_error is not None:+ raise CommandError(f"Node.js templates were not synced: {nodejs_error}")diff --git a/posthog/management/commands/test/test_sync_hog_function_templates.py b/posthog/management/commands/test/test_sync_hog_function_templates.pyindex d021b8006bb7..7decfd290391 100644--- a/posthog/management/commands/test/test_sync_hog_function_templates.py+++ b/posthog/management/commands/test/test_sync_hog_function_templates.py@@ -2,6 +2,9 @@ import pytestfrom unittest.mock import MagicMock, patchfrom django.core.management import call_command+from django.core.management.base import CommandError++from parameterized import parameterizedfrom posthog.management.commands.sync_hog_function_templates import (TEST_INCLUDE_NODEJS_TEMPLATE_IDS,@@ -16,7 +19,7 @@ pytestmark = pytest.mark.django_dbclass TestSyncHogFunctionTemplates:- @patch("posthog.plugins.plugin_server_api.get_hog_function_templates")+ @patch("posthog.management.commands.sync_hog_function_templates.get_hog_function_templates")def test_sync_python_templates(self, mock_get_hog_function_templates):"""Test that Python templates are synced to the database."""# Mock the Node.js API to avoid external dependencies@@ -78,7 +81,7 @@ class TestSyncHogFunctionTemplates:assert node_template.type == "transformation"assert node_template.name == f"Test {template_id}"- @patch("posthog.plugins.plugin_server_api.get_hog_function_templates")+ @patch("posthog.management.commands.sync_hog_function_templates.get_hog_function_templates")def test_sync_handles_invalid_template(self, mock_get_hog_function_templates):"""Test that the command handles invalid templates gracefully."""# Create an invalid Node.js template (missing required fields)@@ -102,20 +105,45 @@ class TestSyncHogFunctionTemplates:assert all(tid in db_template_ids for tid in TEST_INCLUDE_PYTHON_TEMPLATE_IDS)assert "invalid_template" not in db_template_ids- @patch("posthog.plugins.plugin_server_api.get_hog_function_templates")- def test_sync_handles_api_error(self, mock_get_hog_function_templates):- """Test that the command handles API errors gracefully."""- # Mock an API error- mock_get_hog_function_templates.side_effect = Exception("API Error")+ @parameterized.expand(+ [+ ("connection_error", Exception("API Error"), None),+ ("error_without_message", Exception(), None),+ ("non_200_response", None, 503),+ ]+ )+ @patch("posthog.management.commands.sync_hog_function_templates.get_hog_function_templates")+ def test_sync_fails_loudly_when_nodejs_is_unavailable(+ self, _name, side_effect, status_code, mock_get_hog_function_templates+ ):+ if side_effect is not None:+ mock_get_hog_function_templates.side_effect = side_effect+ else:+ mock_response = MagicMock()+ mock_response.status_code = status_code+ mock_get_hog_function_templates.return_value = mock_response- # Run the command, should not raise an exception- call_command("sync_hog_function_templates")+ HogFunctionTemplate.objects.create(+ template_id="coming-soon-from-nodejs",+ name="Coming soon",+ description="Only ever served by the Node.js service",+ type="destination",+ code="return event",+ inputs_schema=[],+ status="coming_soon",+ free=True,+ category=["Custom"],+ code_language="hog",+ )++ with pytest.raises(CommandError):+ call_command("sync_hog_function_templates")- # Verify that Python test templates were still createddb_template_ids = set(HogFunctionTemplate.objects.values_list("template_id", flat=True))assert all(tid in db_template_ids for tid in TEST_INCLUDE_PYTHON_TEMPLATE_IDS)+ assert "coming-soon-from-nodejs" in db_template_ids- @patch("posthog.plugins.plugin_server_api.get_hog_function_templates")+ @patch("posthog.management.commands.sync_hog_function_templates.get_hog_function_templates")def test_sync_metrics(self, mock_get_hog_function_templates):"""Test that the command reports the correct metrics."""# Mock the Node.js API to avoid external dependencies@@ -148,7 +176,7 @@ class TestSyncHogFunctionTemplates:# Just check that the command ran successfullyassert "Hog function template sync complete" in output- @patch("posthog.plugins.plugin_server_api.get_hog_function_templates")+ @patch("posthog.management.commands.sync_hog_function_templates.get_hog_function_templates")def test_template_contents(self, mock_get_hog_function_templates):"""Test that template contents are properly stored in the database."""# Mock the Node.js API to avoid external dependencies@@ -174,7 +202,7 @@ class TestSyncHogFunctionTemplates:if db_template.type not in TYPES_WITH_JAVASCRIPT_SOURCE:assert db_template.bytecode is not None- @patch("posthog.plugins.plugin_server_api.get_hog_function_templates")+ @patch("posthog.management.commands.sync_hog_function_templates.get_hog_function_templates")def test_template_version_behavior(self, mock_get_hog_function_templates):"""Test that template versioning behaves correctly"""# Mock the Node.js API to avoid external dependencies@@ -186,7 +214,7 @@ class TestSyncHogFunctionTemplates:# Clear any existing templatesHogFunctionTemplate.objects.all().delete()- @patch("posthog.plugins.plugin_server_api.get_hog_function_templates")+ @patch("posthog.management.commands.sync_hog_function_templates.get_hog_function_templates")def test_delete_deleted_coming_soon_templates(self, mock_get_hog_function_templates):"""Test that coming-soon templates are properly deleted when they're no longer in in the codebase."""@@ -229,7 +257,7 @@ class TestSyncHogFunctionTemplates:# Verify the old template was deletedassert not HogFunctionTemplate.objects.filter(template_id="coming-soon-old-template").exists()- @patch("posthog.plugins.plugin_server_api.get_hog_function_templates")+ @patch("posthog.management.commands.sync_hog_function_templates.get_hog_function_templates")def test_does_not_delete_deleted_templates(self, mock_get_hog_function_templates):"""Test that non coming-soon templates are not deleted when they're no longer in in the codebase."""diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.pyindex a6b000558792..21ad3b193baa 100644--- a/products/cdp/backend/api/test/test_hog_function.py+++ b/products/cdp/backend/api/test/test_hog_function.py@@ -1165,25 +1165,47 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):"attr": "inputs_schema__0__type",}- def test_secret_inputs_not_returned(self, *args):- payload = {- "name": "Fetch URL",- "hog": "fetch(inputs.url);",- "inputs_schema": [+ @parameterized.expand(+ [+ (+ "string",{"key": "url", "type": "string", "label": "Webhook URL", "secret": True, "required": True},- ],- "inputs": {- "url": {+ "I AM SECRET",+ {+ "bytecode": ["_H", 1, 32, "I AM SECRET"],+ "bytecode_contract": RUNTIME_CONTRACT,"value": "I AM SECRET",+ "order": 0,},- },+ "gAAAAABlkgC8AAAAAAAAAAAAAAAAAAAAAKvzDjuLG689YjjVhmmbXAtZSRoucXuT8VtokVrCotIx3ttPcVufoVt76dyr2phbuotMldKMVv_Y6uzMDZFjX1VQVJqL13wH-WALMn9obfpLYD_WWOUdMA6VurFg1TxdopwQKcL10Y5Yg8s8Gswibi1pCMfjwSnKwod91SMtLKgNfAU4EPZ6GxA77xCHIjaTLueR3qx-hy2Pu3W0r5Rh1hWy0bq01uIdulQ_LhxkQgpj",+ ),+ (+ "dictionary_without_templating",+ {+ "key": "secret_headers",+ "type": "dictionary",+ "label": "Secret headers",+ "secret": True,+ "required": False,+ "templating": False,+ },+ {"Authorization": "Bearer I AM SECRET"},+ {"value": {"Authorization": "Bearer I AM SECRET"}, "order": 0},+ None,+ ),+ ]+ )+ def test_secret_inputs_not_returned(+ self, _name, schema, secret_value, expected_encrypted_input, expected_ciphertext, *args+ ):+ payload = {+ "name": "Fetch URL",+ "hog": "fetch(inputs.url);",+ "inputs_schema": [schema],+ "inputs": {schema["key"]: {"value": secret_value}},"type": "destination",}- expectation = {- "url": {- "secret": True,- }- }+ expectation = {schema["key"]: {"secret": True}}# Fernet encryption is deterministic, but has a temporal component and utilizes os.urandom() for the IVwith time_machine.travel("2024-01-01T00:01:00Z", tick=False):with patch("os.urandom", return_value=b"\x00" * 16):@@ -1192,30 +1214,17 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert res.json()["inputs"] == expectationres = self.client.get(f"/api/projects/{self.team.id}/hog_functions/{res.json()['id']}")assert res.json()["inputs"] == expectation+ assert "I AM SECRET" not in res.content.decode()# Finally check the DB has the real valueobj = HogFunction.objects.get(id=res.json()["id"])assert obj.inputs == {}- assert obj.encrypted_inputs == {- "url": {- "bytecode": [- "_H",- 1,- 32,- "I AM SECRET",- ],- "bytecode_contract": RUNTIME_CONTRACT,- "value": "I AM SECRET",- "order": 0,- },- }+ assert obj.encrypted_inputs == {schema["key"]: expected_encrypted_input}raw_encrypted_inputs = get_db_field_value("encrypted_inputs", obj.id)-- assert (- raw_encrypted_inputs- == "gAAAAABlkgC8AAAAAAAAAAAAAAAAAAAAAKvzDjuLG689YjjVhmmbXAtZSRoucXuT8VtokVrCotIx3ttPcVufoVt76dyr2phbuotMldKMVv_Y6uzMDZFjX1VQVJqL13wH-WALMn9obfpLYD_WWOUdMA6VurFg1TxdopwQKcL10Y5Yg8s8Gswibi1pCMfjwSnKwod91SMtLKgNfAU4EPZ6GxA77xCHIjaTLueR3qx-hy2Pu3W0r5Rh1hWy0bq01uIdulQ_LhxkQgpj"- )+ assert "I AM SECRET" not in raw_encrypted_inputs+ if expected_ciphertext is not None:+ assert raw_encrypted_inputs == expected_ciphertextdef test_masked_secrets_lists_only_functions_storing_the_mask(self, *args):secret_schema = [{"key": "api_key", "type": "string", "label": "API key", "secret": True, "required": True}]diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.pyindex 99659ee80cac..3d078763df2e 100644--- a/products/workflows/backend/tests/api/test_hog_flow.py+++ b/products/workflows/backend/tests/api/test_hog_flow.py@@ -112,6 +112,15 @@ def _secret_input_template() -> dict: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},+ {+ "key": "secret_headers",+ "type": "dictionary",+ "label": "Secret headers",+ "secret": True,+ "hidden": False,+ "required": False,+ "templating": False,+ },]return template@@ -6212,7 +6221,7 @@ class TestHogFlowSecretInputs(APIBaseTest):super().setUp()sync_template_to_db(_secret_input_template())- def _flow_payload(self, api_key: str = "SUPER-SECRET") -> dict:+ def _flow_payload(self, api_key: str = "SUPER-SECRET", extra_inputs: dict | None = None) -> dict:return {"name": "Secret Flow","actions": [@@ -6231,7 +6240,11 @@ class TestHogFlowSecretInputs(APIBaseTest):"type": "function","config": {"template_id": _SECRET_TEMPLATE_ID,- "inputs": {"url": {"value": "https://example.com"}, "api_key": {"value": api_key}},+ "inputs": {+ "url": {"value": "https://example.com"},+ "api_key": {"value": api_key},+ **(extra_inputs or {}),+ },},},],@@ -6245,8 +6258,21 @@ class TestHogFlowSecretInputs(APIBaseTest):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())+ @parameterized.expand(+ [+ ("string", {}, "api_key", "SUPER-SECRET"),+ (+ "dictionary_without_templating",+ {"secret_headers": {"value": {"Authorization": "Bearer SUPER-SECRET"}}},+ "secret_headers",+ {"Authorization": "Bearer SUPER-SECRET"},+ ),+ ]+ )+ def test_secret_action_input_is_encrypted_at_rest_and_masked_on_read(self, _name, extra_inputs, key, stored_value):+ create = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows", self._flow_payload(extra_inputs=extra_inputs)+ )assert create.status_code == 201, create.json()flow_id = create.json()["id"]@@ -6254,15 +6280,23 @@ class TestHogFlowSecretInputs(APIBaseTest):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[key] == {"secret": True}assert inputs["url"]["value"] == "https://example.com"+ # The plaintext never reaches a project member, including through the list the web app reads.+ # Compare test_mcp_list_is_metadata_only_and_hides_action_secrets: a token typed into the+ # plaintext `headers` dictionary is visible there.+ listing = self.client.get(f"/api/projects/{self.team.id}/hog_flows")+ assert listing.status_code == 200, listing.json()+ for response in (create, retrieve, listing):+ assert "SUPER-SECRET" not in response.content.decode()+# 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 key not in db_inputsassert db_inputs["url"]["value"] == "https://example.com"- assert flow.encrypted_inputs["action_1"]["api_key"]["value"] == "SUPER-SECRET"+ assert flow.encrypted_inputs["action_1"][key]["value"] == stored_valueassert "SUPER-SECRET" not in (_raw_encrypted_inputs(flow_id) or "")@parameterized.expand(diff --git a/tools/playwright_area_map.json b/tools/playwright_area_map.jsonindex 959958514c08..63e65e3c51dd 100644--- a/tools/playwright_area_map.json+++ b/tools/playwright_area_map.json@@ -64,7 +64,7 @@"bin/**"],"smoke_subset": ["playwright/e2e/auth.spec.ts"],- "scenes_smoke_only": ["groups", "hog-functions", "integrations", "max", "web-analytics"],+ "scenes_smoke_only": ["groups", "integrations", "max", "web-analytics"],"products": {"ai_observability": ["products/ai_observability/frontend/e2e/"],"billing": ["products/billing/frontend/e2e/"],@@ -73,6 +73,7 @@"surveys": ["products/surveys/frontend/e2e/"]},"scenes": {+ "hog-functions": ["playwright/e2e/webhook-secret-headers.spec.ts"],"billing": ["products/billing/frontend/e2e/"],"surveys": ["products/surveys/frontend/e2e/"],"session-recordings": ["products/replay/frontend/e2e/"],@@ -159,7 +160,8 @@"products/data_quality/frontend/**": ["playwright/e2e/data-quality-overview.spec.ts"],"products/workflows/frontend/**": ["playwright/e2e/workflows-hidden-templates-load.spec.ts",- "playwright/e2e/workflows-property-filter-category-dropdown.spec.ts"+ "playwright/e2e/workflows-property-filter-category-dropdown.spec.ts",+ "playwright/e2e/webhook-secret-headers.spec.ts"],"frontend/src/toolbar/**": ["playwright/e2e/toolbar.spec.ts"]},