:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cdp): refuse an input template that reads a global the runtime does not have (#104519)
Meikel Ratz3367166dccdc
diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.tsindex 1a18330da176..5985a30f8633 100644--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts@@ -731,7 +731,7 @@ describe('SourceWebhooksConsumer', () => {})await waitForBackgroundTasks()expect(getLogs()).toEqual([- '[Action:trigger] Error triggering flow: Could not execute bytecode for input field: distinct_id',+ '[Action:trigger] Error triggering flow: Could not execute bytecode for input field: distinct_id: Global variable not found: i.do.not.exist',])expect(getMetrics()).toEqual([expect.objectContaining({ metric_kind: 'failure', metric_name: 'trigger_failed', count: 1 }),diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex 624f785334ad..e9d79bf4c9d3 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -296,6 +296,33 @@ describe('Hog Executor', () => {`)})+ it('redacts secret values from the log when the inputs fail to build', async () => {+ const fn = createHogFunction({+ ...HOG_EXAMPLES.input_printer,+ ...HOG_INPUTS_EXAMPLES.secret_inputs,+ })+ const invocation = createExampleInvocation(fn)+ delete (invocation.state.globals as any).inputs+ jest.spyOn((executor as any).hogExecutor.hogInputsService, 'buildInputsWithGlobals').mockRejectedValueOnce(+ new Error('Unsupported unit for dateDiff: super secret')+ )++ const result = await executor.execute(invocation)++ const messages = result.logs.map((x) => x.message)+ expect(messages.join('\n')).not.toContain('super secret')+ // result.error is persisted and shown in the Invocations tab, so it must be masked too.+ expect(result.error).toContain('***REDACTED***')+ expect(result.error).not.toContain('super secret')+ expect(messages).toEqual(+ expect.arrayContaining([+ expect.stringContaining(+ 'Error building inputs: Error: Unsupported unit for dateDiff: ***REDACTED***'+ ),+ ])+ )+ })+it('queues up an async function call', async () => {const invocation = createExampleInvocation(hogFunction)invocation.state.globals.event.timestamp = '2024-06-07T12:00:00.000Z'diff --git a/nodejs/src/cdp/services/hog-executor.service.ts b/nodejs/src/cdp/services/hog-executor.service.tsindex 7e95f2cc3a02..8e2b4c7553e4 100644--- a/nodejs/src/cdp/services/hog-executor.service.ts+++ b/nodejs/src/cdp/services/hog-executor.service.ts@@ -13,7 +13,13 @@ import type {HogFunctionInvocationGlobalsWithInputs,HogFunctionType,} from '../types'-import { createAddLogFunction, getSensitiveValues, redactSensitiveValues, sanitizeLogMessage } from '../utils'+import {+ createAddLogFunction,+ getConfiguredSensitiveValues,+ getSensitiveValues,+ redactSensitiveValues,+ sanitizeLogMessage,+} from '../utils'import { execHog } from '../utils/hog-exec'import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from '../utils/hog-function-filtering'import { createInvocationResult } from '../utils/invocation-utils'@@ -158,7 +164,9 @@ export class HogExecutorService {// Declared out here so the terminal catch can mask secrets out of `result.error`, which is// persisted to `hog_invocation_results.error_message` and rendered in the Invocations tab.- let sensitiveValues: string[] = []+ // Starts from the values the function config holds, so an error raised while the inputs are+ // still resolving is masked too; the resolved values are added once the build succeeds.+ let sensitiveValues: string[] = getConfiguredSensitiveValues(invocation.hogFunction)try {let globals: HogFunctionInvocationGlobalsWithInputs@@ -188,12 +196,13 @@ export class HogExecutorService {)}} catch (e) {- addLog('error', `Error building inputs: ${e}`)+ // A template can hand an earlier secret input to a function that quotes its argument.+ addLog('error', sanitizeLogMessage([`Error building inputs: ${e}`], sensitiveValues))throw e}- sensitiveValues = this.getSensitiveValues(invocation.hogFunction, globals.inputs)+ sensitiveValues = [...sensitiveValues, ...this.getSensitiveValues(invocation.hogFunction, globals.inputs)]const invocationInput = invocation.state.vmState ?? invocation.hogFunction.bytecodeconst eventId = invocation?.state.globals?.event?.uuid || 'Unknown event'diff --git a/nodejs/src/cdp/services/hog-inputs.service.test.ts b/nodejs/src/cdp/services/hog-inputs.service.test.tsindex 740c0b206fbb..eb70b1974f1d 100644--- a/nodejs/src/cdp/services/hog-inputs.service.test.ts+++ b/nodejs/src/cdp/services/hog-inputs.service.test.ts@@ -122,6 +122,20 @@ describe('Hog Inputs', () => {expect(result.body.value.event).toBe('{event}')})+ it('names a missing global in the error and keeps every other VM message out', async () => {+ const globals = createHogExecutionGlobals({ inputs: {} } as any) as any+ // {distinct_id}: GET_GLOBAL on a name the globals do not have.+ const missingGlobal = ['_H', 1, 32, 'distinct_id', 1, 1]+ await expect(formatHogInput(missingGlobal, globals, 'field')).rejects.toThrow(+ 'Could not execute bytecode for input field: field: Global variable not found: distinct_id'+ )+ // dateDiff('bogus', 1, 1): the VM quotes its argument, which can be a secret input.+ const quotesArgument = ['_H', 1, 32, 'bogus', 33, 1, 33, 1, 2, 'dateDiff', 3]+ await expect(formatHogInput(quotesArgument, globals, 'field')).rejects.toThrow(+ /^Could not execute bytecode for input field: field$/+ )+ })+it('can handle deep null and undefined values', async () => {const globals = {...createHogExecutionGlobals({diff --git a/nodejs/src/cdp/services/hog-inputs.service.ts b/nodejs/src/cdp/services/hog-inputs.service.tsindex a9bc21dad377..7abeb44e3b82 100644--- a/nodejs/src/cdp/services/hog-inputs.service.ts+++ b/nodejs/src/cdp/services/hog-inputs.service.ts@@ -260,8 +260,11 @@ export const formatHogInput = async (throw error ?? result?.error}if (!result?.finished) {- // NOT ALLOWED- throw new Error(`Could not execute bytecode for input field: ${key}`)+ // An uncaught hog exception comes back as an unfinished run with the error attached.+ // Other VM messages can echo an argument, and an argument can be a secret input.+ const message: string = result?.error?.message ?? ''+ const cause = message.startsWith('Global variable not found') ? `: ${message}` : ''+ throw new Error(`Could not execute bytecode for input field: ${key}${cause}`)}return convertHogToJS(result.result)}diff --git a/nodejs/src/cdp/utils.ts b/nodejs/src/cdp/utils.tsindex 5bc9c0585757..c71429b01c02 100644--- a/nodejs/src/cdp/utils.ts+++ b/nodejs/src/cdp/utils.ts@@ -402,6 +402,20 @@ export const getSensitiveValues = (hogFunction: HogFunctionType, inputs: Record<return values.filter((v) => v.trim())}+/**+ * Sensitive values from the function config alone, before any template resolves. Covers an error+ * raised while the inputs are still being built, when the resolved values do not exist yet.+ */+export const getConfiguredSensitiveValues = (hogFunction: HogFunctionType): string[] => {+ const configured = Object.fromEntries(+ Object.entries({ ...hogFunction.inputs, ...hogFunction.encrypted_inputs }).map(([key, input]) => [+ key,+ input?.value,+ ])+ )+ return getSensitiveValues(hogFunction, configured)+}+export const redactSensitiveValues = (message: string, sensitiveValues?: string[]): string => {// Callers pass `err.message` straight from a catch, where `err` is `any` and need not be an// Error at all, so a non-string reaches this despite the signature. Hand it back untoucheddiff --git a/nodejs/src/cdp/utils/filter-runtime.test.ts b/nodejs/src/cdp/utils/filter-runtime.test.tsindex 70880925e87f..16fa6fe7cc21 100644--- a/nodejs/src/cdp/utils/filter-runtime.test.ts+++ b/nodejs/src/cdp/utils/filter-runtime.test.ts@@ -27,7 +27,7 @@ describe('filter-runtime', () => {})it('describes what a hog function is actually evaluated with', () => {- const { roots, callables, functions } = describeFilterRuntime()+ const { roots, callables, functions, template_roots } = describeFilterRuntime()expect(roots).toEqual(expect.arrayContaining(['event', 'person', 'properties', 'group_0', '$group_4']))// In the type, but built only by the hogflow conditional-branch path, which does not compile// through compile_filters_bytecode. Listing it would let a destination save a filter that throws.@@ -42,6 +42,9 @@ describe('filter-runtime', () => {expect(functions).not.toHaveProperty('sleep')expect(callables).not.toContain('print')expect(functions).not.toHaveProperty('print')+ expect(template_roots).toEqual(expect.arrayContaining(['event', 'person', 'inputs', 'variables', 'request']))+ expect(template_roots).not.toContain('distinct_id')+ expect(template_roots).not.toContain('properties')})it('agrees with what the VM does when asked', async () => {diff --git a/nodejs/src/cdp/utils/filter-runtime.ts b/nodejs/src/cdp/utils/filter-runtime.tsindex 7c522794e039..0365554a87d7 100644--- a/nodejs/src/cdp/utils/filter-runtime.ts+++ b/nodejs/src/cdp/utils/filter-runtime.ts@@ -1,7 +1,7 @@import { ASYNC_STL, BYTECODE_STL, STL } from '@posthog/hogvm'import { ClickHouseTimestamp, ProjectId, RawClickHouseEvent } from '../../types'-import { HogFunctionInvocationGlobals } from '../types'+import { HogFunctionInvocationGlobals, HogFunctionInvocationGlobalsWithInputs } from '../types'import { convertClickhouseRawEventToFilterGlobals, convertToHogFunctionFilterGlobal } from './hog-function-filtering'/** Where Django reads the result. Relative to the repository root. */@@ -18,6 +18,23 @@ export type FilterRuntime = {* the argument count the VM enforces as [min, max]. A null max means unbounded.*/functions: Record<string, [number, number | null]>+ /** Root names an input template can read: the union of what every invocation path puts in globals. */+ template_roots: string[]+}++// A key added to HogFunctionInvocationGlobals has to be added here or the build fails.+const templateRoots: Record<keyof HogFunctionInvocationGlobalsWithInputs, true> = {+ project: true,+ source: true,+ event: true,+ person: true,+ groups: true,+ request: true,+ unsubscribe_url: true,+ unsubscribe_url_one_click: true,+ actions: true,+ variables: true,+ inputs: true,}// These stand for the callers of compile_filters_bytecode: hog function filters, evaluated by the two@@ -102,7 +119,7 @@ export function describeFilterRuntime(): FilterRuntime {`Suspiciously small runtime description: ${fromInvocation.length} roots, ${callables.length} callables`)}- return { roots: fromInvocation, callables, functions }+ return { roots: fromInvocation, callables, functions, template_roots: Object.keys(templateRoots).sort() }}export function renderFilterGlobalsFile(runtime: FilterRuntime): string {@@ -114,11 +131,13 @@ export function renderFilterGlobalsFile(runtime: FilterRuntime): string {'roots are the data globals the CDP filter runtime builds for a hog function. callables are ' +'the standard-library names the VM hands back as values and can then invoke, so they are the ' +'ones a filter can pass as a callback. functions are every standard-library name a filter can ' +- 'call directly, with the argument count the VM enforces as [min, max]. Django reads this to ' +- 'refuse a filter the runtime could not evaluate.',+ 'call directly, with the argument count the VM enforces as [min, max]. template_roots are the ' ++ 'names an input template can read. Django reads this to refuse a filter or an input the ' ++ 'runtime could not evaluate.',roots: runtime.roots,callables: runtime.callables,functions: runtime.functions,+ template_roots: runtime.template_roots,},null,// Matches what the pre-commit hook (bin/hogli format:yaml) writes, so a regenerate is a no-op.diff --git a/nodejs/src/cdp/utils/invocation-utils.test.ts b/nodejs/src/cdp/utils/invocation-utils.test.tsindex c9242ddd3cbc..ccb7596594d2 100644--- a/nodejs/src/cdp/utils/invocation-utils.test.ts+++ b/nodejs/src/cdp/utils/invocation-utils.test.ts@@ -3,6 +3,7 @@ import { DateTime } from 'luxon'import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'import { createHogExecutionGlobals, createHogFunction } from '../_tests/fixtures'import { HogInputsService } from '../services/hog-inputs.service'+import { MAX_LOG_LENGTH } from '../utils'import { buildHogFunctionInvocations, cloneInvocation, createInvocation } from './invocation-utils'describe('Invocation utils', () => {@@ -254,6 +255,40 @@ describe('Invocation utils', () => {},])})++ it('masks a secret input quoted by the failure', async () => {+ const fn = createHogFunction({+ ...HOG_EXAMPLES.input_printer,+ ...HOG_INPUTS_EXAMPLES.secret_inputs,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ })+ jest.spyOn(hogInputsService, 'buildInputsWithGlobals').mockRejectedValue(+ new Error('Unsupported unit for dateDiff: super secret')+ )++ const { logs } = await buildHogFunctionInvocations(hogInputsService, [fn], pageviewGlobals())++ expect(logs[0].message).toContain('Unsupported unit for dateDiff: ***REDACTED***')+ expect(logs[0].message).not.toContain('super secret')+ jest.restoreAllMocks()+ })++ it('truncates the failure log, which carries the VM message for every matching event', async () => {+ const fn = createHogFunction({+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ })+ jest.spyOn(hogInputsService, 'buildInputsWithGlobals').mockRejectedValue(+ new Error(`Global variable not found: missing.${'x'.repeat(MAX_LOG_LENGTH)}`)+ )++ const { logs } = await buildHogFunctionInvocations(hogInputsService, [fn], pageviewGlobals())++ expect(logs[0].message.length).toBeLessThan(MAX_LOG_LENGTH + 100)+ expect(logs[0].message).toContain('(truncated)')+ jest.restoreAllMocks()+ })})describe('cloneInvocation', () => {diff --git a/nodejs/src/cdp/utils/invocation-utils.ts b/nodejs/src/cdp/utils/invocation-utils.tsindex 643e966242db..c7676c58f8eb 100644--- a/nodejs/src/cdp/utils/invocation-utils.ts+++ b/nodejs/src/cdp/utils/invocation-utils.ts@@ -1,5 +1,4 @@// NOTE: PostIngestionEvent is our context event - it should never be sent directly to an output, but rather transformed into a lightweight schema-import { DateTime } from 'luxon'import { Counter } from 'prom-client'import { UUIDT } from '~/common/utils/utils'@@ -16,6 +15,7 @@ import {MinimalAppMetric,} from '../types'import { HogFunctionType } from '../types'+import { getConfiguredSensitiveValues, logEntry, sanitizeLogMessage } from '../utils'import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from './hog-function-filtering'/** The inputs step of the dead-letter pipeline. Read next to cdp_hog_function_filter_error. */@@ -109,9 +109,15 @@ export async function buildHogFunctionInvocations(log_source: 'hog_function',log_source_id: hogFunction.id,instance_id: new UUIDT().toString(), // random UUID, like it would be for an invocation- timestamp: DateTime.now(),- level: 'error',- message: `Error building inputs for event ${triggerGlobals.event.uuid}: ${error.message}`,+ // logEntry truncates: the message carries the VM's text, which can quote a value.+ // The VM can quote an argument, and an argument can be a secret input.+ ...logEntry(+ 'error',+ sanitizeLogMessage(+ [`Error building inputs for event ${triggerGlobals.event.uuid}: ${error.message}`],+ getConfiguredSensitiveValues(hogFunction)+ )+ ),})hogFunctionInputsErrors.inc({ type: hogFunction.type })diff --git a/posthog/cdp/filter_globals.json b/posthog/cdp/filter_globals.jsonindex 034f5147aca8..ef8511fd0af0 100644--- a/posthog/cdp/filter_globals.json+++ b/posthog/cdp/filter_globals.json@@ -1,5 +1,5 @@{- "$comment": "Generated. Do not edit: run `pnpm --filter=@posthog/nodejs run build:filter-globals`. roots are the data globals the CDP filter runtime builds for a hog function. callables are the standard-library names the VM hands back as values and can then invoke, so they are the ones a filter can pass as a callback. functions are every standard-library name a filter can call directly, with the argument count the VM enforces as [min, max]. Django reads this to refuse a filter the runtime could not evaluate.",+ "$comment": "Generated. Do not edit: run `pnpm --filter=@posthog/nodejs run build:filter-globals`. roots are the data globals the CDP filter runtime builds for a hog function. callables are the standard-library names the VM hands back as values and can then invoke, so they are the ones a filter can pass as a callback. functions are every standard-library name a filter can call directly, with the argument count the VM enforces as [min, max]. template_roots are the names an input template can read. Django reads this to refuse a filter or an input the runtime could not evaluate.","roots": ["$group_0","$group_1",@@ -153,138 +153,550 @@"values"],"functions": {- "Error": [0, 2],- "HogError": [1, 3],- "JSONExtract": [2, null],- "JSONExtractArrayRaw": [1, null],- "JSONExtractBool": [1, null],- "JSONExtractFloat": [1, null],- "JSONExtractInt": [1, null],- "JSONExtractString": [1, null],- "JSONHas": [1, null],- "JSONLength": [1, null],- "NotImplementedError": [0, 2],- "RetryError": [0, 2],- "addDays": [2, 2],- "and": [1, null],- "arrayPopBack": [1, 1],- "arrayPopFront": [1, 1],- "arrayPushBack": [2, 2],- "arrayPushFront": [2, 2],- "arrayReverse": [1, 1],- "arrayReverseSort": [1, null],- "arraySort": [1, null],- "arrayStringConcat": [1, 2],- "assumeNotNull": [1, 1],- "base64Decode": [1, 1],- "base64Encode": [1, 1],- "coalesce": [1, null],- "concat": [1, null],- "dateAdd": [3, 3],- "dateDiff": [3, 3],- "dateTrunc": [2, 3],- "decodeURLComponent": [1, 1],- "empty": [1, 1],- "encodeURLComponent": [1, 1],- "equals": [2, 2],- "extract": [2, 2],- "extractRegex": [2, 2],- "floor": [1, 2],- "formatDateTime": [2, 3],- "fromUnixTimestamp": [1, 1],- "fromUnixTimestampMilli": [1, 1],- "generateUUIDv4": [0, 0],- "greater": [2, 2],- "greaterOrEquals": [2, 2],- "has": [2, 2],- "if": [3, 3],- "ifNull": [2, 2],- "ilike": [2, 2],- "in": [2, 2],- "indexOf": [2, 2],- "isIPAddressInRange": [2, 2],- "isNotNull": [1, 1],- "isNull": [1, 1],- "isValidJSON": [1, 1],- "jsonParse": [1, 1],- "jsonStringify": [1, 2],- "keys": [1, 1],- "length": [1, 1],- "less": [2, 2],- "lessOrEquals": [2, 2],- "like": [2, 2],- "lower": [1, 1],- "match": [2, 2],- "md5": [1, 2],- "md5Hex": [1, 1],- "min2": [2, 2],- "minus": [2, 2],- "multiIf": [3, null],- "multiSearchAnyCaseInsensitive": [2, 2],- "not": [1, 1],- "notEmpty": [1, 1],- "notEquals": [2, 2],- "notILike": [2, 2],- "notLike": [2, 2],- "now": [0, 1],- "or": [1, null],- "plus": [2, 2],- "position": [2, 3],- "positionCaseInsensitive": [2, 3],- "randomFloat": [0, 0],- "range": [1, 2],- "replaceAll": [3, 3],- "replaceOne": [3, 3],- "reverse": [1, 1],- "round": [1, 2],- "sha1": [1, 2],- "sha1Hex": [1, 1],- "sha1HmacChain": [1, 2],- "sha1HmacChainHex": [1, 1],- "sha256": [1, 2],- "sha256Hex": [1, 1],- "sha256HmacChain": [1, 2],- "sha256HmacChainHex": [1, 1],- "splitByString": [2, 3],- "startsWith": [2, 2],- "substring": [2, 3],- "toDate": [1, 1],- "toDateTime": [1, 2],- "toFloat": [1, 1],- "toInt": [1, 1],- "toIntervalDay": [1, 1],- "toIntervalHour": [1, 1],- "toIntervalMinute": [1, 1],- "toIntervalMonth": [1, 1],- "toMonth": [1, 1],- "toStartOfDay": [1, 2],- "toStartOfHour": [1, 1],- "toStartOfMonth": [1, 1],- "toStartOfWeek": [1, 2],- "toString": [1, 2],- "toTimeZone": [2, 2],- "toUUID": [1, 1],- "toUnixTimestamp": [1, 2],- "toUnixTimestampMilli": [1, 2],- "toYYYYMM": [1, 1],- "toYear": [1, 1],- "today": [0, 0],- "trim": [1, 2],- "trimLeft": [1, 2],- "trimRight": [1, 2],- "tryBase64Decode": [1, 1],- "tryDecodeURLComponent": [1, 1],- "tuple": [0, null],- "typeof": [1, 1],- "upper": [1, 1],- "values": [1, 1],- "arrayCount": [2, 2],- "arrayExists": [2, 2],- "arrayFilter": [2, 2],- "arrayMap": [2, 2],- "arrayReduce": [3, 3],- "inCohort": [2, 2],- "notInCohort": [2, 2],- "sortableSemver": [1, 1]- }+ "Error": [+ 0,+ 2+ ],+ "HogError": [+ 1,+ 3+ ],+ "JSONExtract": [+ 2,+ null+ ],+ "JSONExtractArrayRaw": [+ 1,+ null+ ],+ "JSONExtractBool": [+ 1,+ null+ ],+ "JSONExtractFloat": [+ 1,+ null+ ],+ "JSONExtractInt": [+ 1,+ null+ ],+ "JSONExtractString": [+ 1,+ null+ ],+ "JSONHas": [+ 1,+ null+ ],+ "JSONLength": [+ 1,+ null+ ],+ "NotImplementedError": [+ 0,+ 2+ ],+ "RetryError": [+ 0,+ 2+ ],+ "addDays": [+ 2,+ 2+ ],+ "and": [+ 1,+ null+ ],+ "arrayPopBack": [+ 1,+ 1+ ],+ "arrayPopFront": [+ 1,+ 1+ ],+ "arrayPushBack": [+ 2,+ 2+ ],+ "arrayPushFront": [+ 2,+ 2+ ],+ "arrayReverse": [+ 1,+ 1+ ],+ "arrayReverseSort": [+ 1,+ null+ ],+ "arraySort": [+ 1,+ null+ ],+ "arrayStringConcat": [+ 1,+ 2+ ],+ "assumeNotNull": [+ 1,+ 1+ ],+ "base64Decode": [+ 1,+ 1+ ],+ "base64Encode": [+ 1,+ 1+ ],+ "coalesce": [+ 1,+ null+ ],+ "concat": [+ 1,+ null+ ],+ "dateAdd": [+ 3,+ 3+ ],+ "dateDiff": [+ 3,+ 3+ ],+ "dateTrunc": [+ 2,+ 3+ ],+ "decodeURLComponent": [+ 1,+ 1+ ],+ "empty": [+ 1,+ 1+ ],+ "encodeURLComponent": [+ 1,+ 1+ ],+ "equals": [+ 2,+ 2+ ],+ "extract": [+ 2,+ 2+ ],+ "extractRegex": [+ 2,+ 2+ ],+ "floor": [+ 1,+ 2+ ],+ "formatDateTime": [+ 2,+ 3+ ],+ "fromUnixTimestamp": [+ 1,+ 1+ ],+ "fromUnixTimestampMilli": [+ 1,+ 1+ ],+ "generateUUIDv4": [+ 0,+ 0+ ],+ "greater": [+ 2,+ 2+ ],+ "greaterOrEquals": [+ 2,+ 2+ ],+ "has": [+ 2,+ 2+ ],+ "if": [+ 3,+ 3+ ],+ "ifNull": [+ 2,+ 2+ ],+ "ilike": [+ 2,+ 2+ ],+ "in": [+ 2,+ 2+ ],+ "indexOf": [+ 2,+ 2+ ],+ "isIPAddressInRange": [+ 2,+ 2+ ],+ "isNotNull": [+ 1,+ 1+ ],+ "isNull": [+ 1,+ 1+ ],+ "isValidJSON": [+ 1,+ 1+ ],+ "jsonParse": [+ 1,+ 1+ ],+ "jsonStringify": [+ 1,+ 2+ ],+ "keys": [+ 1,+ 1+ ],+ "length": [+ 1,+ 1+ ],+ "less": [+ 2,+ 2+ ],+ "lessOrEquals": [+ 2,+ 2+ ],+ "like": [+ 2,+ 2+ ],+ "lower": [+ 1,+ 1+ ],+ "match": [+ 2,+ 2+ ],+ "md5": [+ 1,+ 2+ ],+ "md5Hex": [+ 1,+ 1+ ],+ "min2": [+ 2,+ 2+ ],+ "minus": [+ 2,+ 2+ ],+ "multiIf": [+ 3,+ null+ ],+ "multiSearchAnyCaseInsensitive": [+ 2,+ 2+ ],+ "not": [+ 1,+ 1+ ],+ "notEmpty": [+ 1,+ 1+ ],+ "notEquals": [+ 2,+ 2+ ],+ "notILike": [+ 2,+ 2+ ],+ "notLike": [+ 2,+ 2+ ],+ "now": [+ 0,+ 1+ ],+ "or": [+ 1,+ null+ ],+ "plus": [+ 2,+ 2+ ],+ "position": [+ 2,+ 3+ ],+ "positionCaseInsensitive": [+ 2,+ 3+ ],+ "randomFloat": [+ 0,+ 0+ ],+ "range": [+ 1,+ 2+ ],+ "replaceAll": [+ 3,+ 3+ ],+ "replaceOne": [+ 3,+ 3+ ],+ "reverse": [+ 1,+ 1+ ],+ "round": [+ 1,+ 2+ ],+ "sha1": [+ 1,+ 2+ ],+ "sha1Hex": [+ 1,+ 1+ ],+ "sha1HmacChain": [+ 1,+ 2+ ],+ "sha1HmacChainHex": [+ 1,+ 1+ ],+ "sha256": [+ 1,+ 2+ ],+ "sha256Hex": [+ 1,+ 1+ ],+ "sha256HmacChain": [+ 1,+ 2+ ],+ "sha256HmacChainHex": [+ 1,+ 1+ ],+ "splitByString": [+ 2,+ 3+ ],+ "startsWith": [+ 2,+ 2+ ],+ "substring": [+ 2,+ 3+ ],+ "toDate": [+ 1,+ 1+ ],+ "toDateTime": [+ 1,+ 2+ ],+ "toFloat": [+ 1,+ 1+ ],+ "toInt": [+ 1,+ 1+ ],+ "toIntervalDay": [+ 1,+ 1+ ],+ "toIntervalHour": [+ 1,+ 1+ ],+ "toIntervalMinute": [+ 1,+ 1+ ],+ "toIntervalMonth": [+ 1,+ 1+ ],+ "toMonth": [+ 1,+ 1+ ],+ "toStartOfDay": [+ 1,+ 2+ ],+ "toStartOfHour": [+ 1,+ 1+ ],+ "toStartOfMonth": [+ 1,+ 1+ ],+ "toStartOfWeek": [+ 1,+ 2+ ],+ "toString": [+ 1,+ 2+ ],+ "toTimeZone": [+ 2,+ 2+ ],+ "toUUID": [+ 1,+ 1+ ],+ "toUnixTimestamp": [+ 1,+ 2+ ],+ "toUnixTimestampMilli": [+ 1,+ 2+ ],+ "toYYYYMM": [+ 1,+ 1+ ],+ "toYear": [+ 1,+ 1+ ],+ "today": [+ 0,+ 0+ ],+ "trim": [+ 1,+ 2+ ],+ "trimLeft": [+ 1,+ 2+ ],+ "trimRight": [+ 1,+ 2+ ],+ "tryBase64Decode": [+ 1,+ 1+ ],+ "tryDecodeURLComponent": [+ 1,+ 1+ ],+ "tuple": [+ 0,+ null+ ],+ "typeof": [+ 1,+ 1+ ],+ "upper": [+ 1,+ 1+ ],+ "values": [+ 1,+ 1+ ],+ "arrayCount": [+ 2,+ 2+ ],+ "arrayExists": [+ 2,+ 2+ ],+ "arrayFilter": [+ 2,+ 2+ ],+ "arrayMap": [+ 2,+ 2+ ],+ "arrayReduce": [+ 3,+ 3+ ],+ "inCohort": [+ 2,+ 2+ ],+ "notInCohort": [+ 2,+ 2+ ],+ "sortableSemver": [+ 1,+ 1+ ]+ },+ "template_roots": [+ "actions",+ "event",+ "groups",+ "inputs",+ "person",+ "project",+ "request",+ "source",+ "unsubscribe_url",+ "unsubscribe_url_one_click",+ "variables"+ ]}diff --git a/posthog/cdp/filters.py b/posthog/cdp/filters.pyindex 72772e604959..b05818fabdf3 100644--- a/posthog/cdp/filters.py+++ b/posthog/cdp/filters.py@@ -372,6 +372,9 @@ FILTER_GLOBALS: set[str] = set(_RUNTIME["roots"]) | set(_RUNTIME["callables"])FILTER_FUNCTIONS: dict[str, tuple[int, Optional[int]]] = {name: (arity[0], arity[1]) for name, arity in _RUNTIME["functions"].items()}+# Input templates run against the invocation globals, a different shape from the flattened filter globals.+TEMPLATE_GLOBALS: set[str] = set(_RUNTIME["template_roots"])+TEMPLATE_CALLABLES: set[str] = set(_RUNTIME["callables"])_UNKNOWN_GLOBAL = "Unknown global variable: "diff --git a/posthog/cdp/test/test_validation.py b/posthog/cdp/test/test_validation.pyindex b26e4259b949..a5fd709e1af6 100644--- a/posthog/cdp/test/test_validation.py+++ b/posthog/cdp/test/test_validation.py@@ -1016,7 +1016,7 @@ class TestHogFunctionValidation(ClickhouseTestMixin, APIBaseTest, QueryMatchingT("valid_bracket", "{person.properties['self-serve']}", False),("hyphenated_single", "{person.properties.self-serve}", True),("hyphenated_multi", "{event.properties.multi-word-name}", True),- ("subtraction_with_spaces", "{event.properties.count - total}", False),+ ("subtraction_with_spaces", "{event.properties.count - inputs.total}", False),("subtraction_field_minus_field", "{event.properties.amount - event.properties.discount}", False),])@@ -1048,11 +1048,54 @@ class TestHogFunctionValidation(ClickhouseTestMixin, APIBaseTest, QueryMatchingTexpected = generate_template_bytecode(equivalent, set(), function_type="destination", is_dwh_source=False)assert rewritten == expected+ def test_destination_templates_accept_lambda_locals_and_node_callables(self):+ for template in (+ "{arrayMap(a -> { let b := a return b }, [1])}",+ "{arrayMap(tryBase64Decode, event.properties.ids)}",+ ):+ assert generate_template_bytecode(template, set(), function_type="destination"), template++ def test_template_globals_check_covers_every_function_type_and_input_shape(self):+ # Every non-transformation type resolves its inputs against the same invocation globals, and a+ # bad root inside a json input or a list fails the same way as a plain string.+ for function_type, template in (+ ("destination", {"headers": {"x-id": "{distinct_id}"}}),+ ("destination", ["ok", "{properties.foo}"]),+ ("source_webhook", "{distinct_id}"),+ ("internal_destination", "{timestamp}"),+ ):+ with self.assertRaises(Exception) as ctx:+ generate_template_bytecode(template, set(), function_type=function_type)+ assert "Variable not available in inputs" in str(ctx.exception), (function_type, template)++ # Roots a specific path provides stay allowed everywhere, so a template valid on one path is+ # never refused on another.+ for function_type, template in (+ ("source_webhook", "{request.body.distinct_id}"),+ ("destination", "{variables.total}"),+ ("destination", "{groups.company.properties.name}"),+ ("transformation", "{arrayMap(a -> a, [1])}"),+ ):+ assert generate_template_bytecode(template, set(), function_type=function_type), (function_type, template)++ def test_destination_templates_refuse_a_python_only_callback(self):+ # max2 is in the Python standard library and not in the Node VM, so a template that passes it+ # as a callback fails on every event.+ with self.assertRaises(Exception) as ctx:+ generate_template_bytecode("{arrayMap(max2, [1, 2])}", set(), function_type="destination")+ assert "Variable not available in inputs: max2" in str(ctx.exception)++ def test_destination_templates_skip_the_globals_check_when_the_function_stays_off(self):+ with self.assertRaises(Exception):+ generate_template_bytecode("{distinct_id}", set(), function_type="destination")+ assert generate_template_bytecode("{distinct_id}", set(), function_type="destination", validate_globals=False)+def test_record_alias_not_rewritten_without_dwh_source(self):- # Without a warehouse source, `record` is left untouched (compiles like any other global).- untouched = generate_template_bytecode("{record.name}", set(), function_type="destination", is_dwh_source=False)- rewritten = generate_template_bytecode("{record.name}", set(), function_type="destination", is_dwh_source=True)- assert untouched != rewritten+ # Without a warehouse source there is no `record` global at run time, so it is refused like any other.+ with self.assertRaises(Exception) as ctx:+ generate_template_bytecode("{record.name}", set(), function_type="destination", is_dwh_source=False)+ assert "Variable not available in inputs: record" in str(ctx.exception)+ assert generate_template_bytecode("{record.name}", set(), function_type="destination", is_dwh_source=True)def test_record_alias_rewriter_only_touches_record_fields(self):# AST-level: a `record` field is rewritten; a non-record field and a same-named stringdiff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.pyindex a7f95501c15b..0e62630e9c9c 100644--- a/posthog/cdp/validation.py+++ b/posthog/cdp/validation.py@@ -16,7 +16,7 @@ from posthog.hogql.context import HogQLContextfrom posthog.hogql.parser import parse_program, parse_string_templatefrom posthog.hogql.visitor import TraversingVisitor-from posthog.cdp.filters import compile_filters_bytecode, compile_filters_expr+from posthog.cdp.filters import TEMPLATE_CALLABLES, TEMPLATE_GLOBALS, compile_filters_bytecode, compile_filters_exprfrom posthog.models.integration import POSTHOG_CONNECT_KIND, Integrationfrom products.cdp.backend.models.hog_functions.hog_function import (@@ -274,10 +274,12 @@ class InputCollector(TraversingVisitor):self.inputs.add(str(node.chain[1]))-class TransformationGlobalsValidator(TraversingVisitor):- """Reject input templates that reference globals unavailable to the realtime- transformer (e.g. `person`, `groups`, `source`). Without this check, the bytecode- compiles fine and the failure surfaces only at ingestion time as+class TemplateGlobalsValidator(TraversingVisitor):+ """Reject input templates that reference globals the runtime will not have.++ Each function type passes the globals its runtime provides (transformations see `project`,+ `event` and `inputs`; everything else the invocation globals). Without this check the bytecode+ compiles fine and the failure surfaces only at run time as"Could not execute bytecode for input field" / "Global variable not found"."""@@ -287,9 +289,14 @@ class TransformationGlobalsValidator(TraversingVisitor):self,available_globals: Optional[set[str]] = None,runtime_functions: Optional[set[str]] = None,+ # The Python tables describe the Python VM. A template that runs in the Node VM passes its+ # own callables as runtime_functions and turns these off.+ python_stl: bool = True,):super().__init__()self.invalid_globals = set()+ self._python_stl = python_stl+ self._declared: set[str] = set()self._available_globals = (available_globals if available_globals is not None else TRANSFORMATION_AVAILABLE_GLOBALS)@@ -297,18 +304,25 @@ class TransformationGlobalsValidator(TraversingVisitor):runtime_functions if runtime_functions is not None else TRANSFORMATION_RUNTIME_FUNCTIONS)+ def check(self, node: ast.Expr) -> None:+ # Lambda parameters and anything a lambda body declares are locals, not globals.+ declared = DeclaredNamesCollector()+ declared.visit(node)+ self._declared = declared.names+ self.visit(node)+def visit_field(self, node: ast.Field):super().visit_field(node)if not node.chain:returnroot = str(node.chain[0])if (- root in self._available_globals+ root in self._declared+ or root in self._available_globalsor root in self._runtime_functionsor root in CORE_SUPPORTED_FUNCTIONSor root in PRODUCT_ASYNC_FUNCTIONS- or root in STL- or root in BYTECODE_STL+ or (self._python_stl and (root in STL or root in BYTECODE_STL))):returnself.invalid_globals.add(root)@@ -440,6 +454,7 @@ def generate_template_bytecode(input_collector: set[str],function_type: Optional[str] = None,is_dwh_source: bool = False,+ validate_globals: bool = True,) -> Any:"""Clones an object, compiling any string values to bytecode templates@@ -447,11 +462,14 @@ def generate_template_bytecode(if isinstance(obj, dict):return {- key: generate_template_bytecode(value, input_collector, function_type, is_dwh_source)+ key: generate_template_bytecode(value, input_collector, function_type, is_dwh_source, validate_globals)for key, value in obj.items()}elif isinstance(obj, list):- return [generate_template_bytecode(item, input_collector, function_type, is_dwh_source) for item in obj]+ return [+ generate_template_bytecode(item, input_collector, function_type, is_dwh_source, validate_globals)+ for item in obj+ ]elif isinstance(obj, str):node = parse_string_template(obj)if is_dwh_source:@@ -462,8 +480,8 @@ def generate_template_bytecode(if detector.errors:raise Exception(detector.errors[0])if function_type == "transformation":- transformation_validator = TransformationGlobalsValidator()- transformation_validator.visit(node)+ transformation_validator = TemplateGlobalsValidator()+ transformation_validator.check(node)if transformation_validator.invalid_globals:names = ", ".join(sorted(transformation_validator.invalid_globals))raise Exception(@@ -471,17 +489,31 @@ def generate_template_bytecode(f"Transformations only have access to project, event, and inputs.")elif function_type == "transformation_log":- log_validator = TransformationGlobalsValidator(+ log_validator = TemplateGlobalsValidator(available_globals=TRANSFORMATION_LOG_AVAILABLE_GLOBALS,runtime_functions=set(),)- log_validator.visit(node)+ log_validator.check(node)if log_validator.invalid_globals:names = ", ".join(sorted(log_validator.invalid_globals))raise Exception(f"Variable not available in log transformations: {names}. "f"Log transformations only have access to project, record, and inputs.")+ elif function_type is not None and validate_globals:+ # Every other type resolves its inputs against the invocation globals at run time. A save+ # that disables or deletes the function skips this, so a broken function can be turned off.+ template_validator = TemplateGlobalsValidator(+ available_globals=TEMPLATE_GLOBALS, runtime_functions=TEMPLATE_CALLABLES, python_stl=False+ )+ template_validator.check(node)+ if template_validator.invalid_globals:+ names = ", ".join(sorted(template_validator.invalid_globals))+ raise Exception(+ f"Variable not available in inputs: {names}. "+ f"Inputs can read event, person, groups, project, source and inputs, and in a workflow "+ f"also variables."+ )return create_bytecode(node).bytecodeelse:return obj@@ -784,7 +816,11 @@ class InputsItemSerializer(serializers.Serializer):else:input_collector: set[str] = set()attrs["bytecode"] = generate_template_bytecode(- value, input_collector, function_type=function_type, is_dwh_source=is_dwh_source+ value,+ input_collector,+ function_type=function_type,+ is_dwh_source=is_dwh_source,+ validate_globals=self.context.get("function_will_be_enabled", True),)attrs["input_deps"] = list(input_collector)if "transpiled" in attrs:@@ -1128,7 +1164,7 @@ def compile_hog(# at ingestion time. Declared locals are excluded from the check.declared = DeclaredNamesCollector()declared.visit(program)- body_validator = TransformationGlobalsValidator(+ body_validator = TemplateGlobalsValidator(available_globals=TRANSFORMATION_LOG_AVAILABLE_GLOBALS | declared.names,runtime_functions=set(),)diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.pyindex 17df0c12bc8a..47d3c4d31a56 100644--- a/products/cdp/backend/api/test/test_hog_function.py+++ b/products/cdp/backend/api/test/test_hog_function.py@@ -2683,6 +2683,58 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):),}+ def test_destination_rejects_inputs_referencing_unavailable_globals(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_functions/",+ data={+ **EXAMPLE_FULL,+ "inputs": {**EXAMPLE_FULL["inputs"], "url": {"value": "https://example.com/{distinct_id}"}},+ },+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "inputs__url"+ assert response.json()["detail"] == (+ "Invalid template: Variable not available in inputs: distinct_id. Inputs can read event, person, "+ "groups, project, source and inputs, and in a workflow also variables."+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_functions/",+ data={+ **EXAMPLE_FULL,+ "inputs": {**EXAMPLE_FULL["inputs"], "url": {"value": "https://example.com/{event.distinct_id}"}},+ },+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()++ @parameterized.expand(+ [+ # An input saved before this check must not trap the function: disabling or deleting it+ # stays possible, while any save that leaves it enabled is still rejected.+ ("disable_allowed", True, {"enabled": False}, status.HTTP_200_OK),+ ("delete_allowed", True, {"deleted": True}, status.HTTP_200_OK),+ ("edit_while_disabled_allowed", False, {"name": "renamed"}, status.HTTP_200_OK),+ ("enable_blocked", False, {"enabled": True}, status.HTTP_400_BAD_REQUEST),+ ("edit_while_enabled_blocked", True, {"name": "renamed"}, status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_unavailable_input_global_only_blocks_saves_that_leave_function_enabled(+ self, _name, initial_enabled, patch, expected+ ):+ function = HogFunction.objects.create(+ team=self.team,+ name="Saved before the check",+ type="destination",+ hog="fetch(inputs.url)",+ inputs_schema=[{"key": "url", "type": "string", "required": True}],+ inputs={"url": {"value": "https://example.com/{distinct_id}"}},+ enabled=initial_enabled,+ )+ response = self.client.patch(f"/api/projects/{self.team.id}/hog_functions/{function.id}/", data=patch)+ assert response.status_code == expected, response.json()+ if expected == status.HTTP_400_BAD_REQUEST:+ assert response.json()["attr"] == "inputs__url"+def test_limits_transformation_functions_per_team(self):"""Test that we can create unlimited disabled transformations but only 20 enabled ones"""# 1. Create several disabled transformations (more than the limit)diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex 13dccb392bb5..1a9ea2e6e66d 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -1203,6 +1203,31 @@ class TestHogFlowAPI(APIBaseTest):assert "Send webhook" in detail, response.json()assert "Invalid template" in detail, response.json()+ def test_activating_refuses_a_step_input_that_reads_an_unavailable_global(self):+ hog_flow, action = self._create_hog_flow_with_action(+ {"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com/{distinct_id}"}}}+ )+ action["name"] = "Send webhook"+ create_response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert create_response.status_code == 201, create_response.json()+ flow_id = create_response.json()["id"]++ response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "active"})+ assert response.status_code == 400, response.json()+ assert "Send webhook" in response.json()["detail"]+ assert "Variable not available in inputs: distinct_id" in response.json()["detail"]++ # A step reading the event or a workflow variable activates.+ hog_flow, _ = self._create_hog_flow_with_action(+ {+ "template_id": "template-webhook",+ "inputs": {"url": {"value": "https://example.com/{event.distinct_id}/{variables.total}"}},+ }+ )+ hog_flow["status"] = "active"+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert response.status_code == 201, response.json()+def test_hog_flow_bytecode_compilation(self):hog_flow, action = self._create_hog_flow_with_action({