Skip to content

: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.

fix(cdp): bound liquid template rendering with parse, time, and memory limits (#94119)

Harley Alexander7e5aaa1a709a
diff --git a/nodejs/package.json b/nodejs/package.json
index fb01253a72e0..49ecde4ee272 100644
--- a/nodejs/package.json
+++ b/nodejs/package.json
@@ -122,7 +122,7 @@
"js-big-decimal": "^2.2.0",
"jsonwebtoken": "^9.0.2",
"libsodium-wrappers": "^0.7.15",
- "liquidjs": "^10.27.0",
+ "liquidjs": "^10.27.2",
"lodash": "^4.18.1",
"lru-cache": "^11.0.0",
"luxon": "^3.4.4",
diff --git a/nodejs/src/cdp/services/hog-inputs.service.test.ts b/nodejs/src/cdp/services/hog-inputs.service.test.ts
index 003879b9556b..c197c6478c2c 100644
--- a/nodejs/src/cdp/services/hog-inputs.service.test.ts
+++ b/nodejs/src/cdp/services/hog-inputs.service.test.ts
@@ -198,6 +198,20 @@ describe('Hog Inputs', () => {
expect(inputs.liquid_templated).toMatchInlineSnapshot(`"event: "test""`)
})
+ it('rejects liquid inputs whose leaves together exceed the invocation budget', async () => {
+ const leaf = `{% for i in (1..600) %}${'a'.repeat(10_000)}{% endfor %}`
+ hogFunction = createHogFunction({
+ ...hogFunction,
+ inputs: {
+ ...hogFunction.inputs,
+ liquid_object: { value: { first: leaf, second: leaf }, templating: 'liquid' },
+ },
+ })
+ await expect(hogInputsService.buildInputs(hogFunction, globals)).rejects.toThrow(
+ 'liquid output limit exceeded'
+ )
+ })
+
it('should load integration inputs and replace access tokens with placeholders', async () => {
hogFunction = createHogFunction({
...hogFunction,
diff --git a/nodejs/src/cdp/services/hog-inputs.service.ts b/nodejs/src/cdp/services/hog-inputs.service.ts
index 597467489957..a3eb711a2f49 100644
--- a/nodejs/src/cdp/services/hog-inputs.service.ts
+++ b/nodejs/src/cdp/services/hog-inputs.service.ts
@@ -7,7 +7,7 @@ import { logger } from '~/common/utils/logger'
import { HogFunctionInvocationGlobals, HogFunctionInvocationGlobalsWithInputs, HogFunctionType } from '../types'
import { EncryptedFields } from '../utils/encryption-utils'
import { execHog } from '../utils/hog-exec'
-import { LiquidRenderer } from '../utils/liquid'
+import { LiquidRenderBudget, LiquidRenderer } from '../utils/liquid'
import { getDevicePushSubscriptionToken } from '../utils/push-subscription-utils'
import { IntegrationManagerService } from './managers/integration-manager.service'
import { RecipientTokensService } from './messaging/recipient-tokens.service'
@@ -41,11 +41,14 @@ export class HogInputsService {
...(await this.loadIntegrationInputs(hogFunction, newGlobals)),
}
+ // One budget for the whole invocation, so many small liquid leaves cannot add up to a stall.
+ const liquidBudget = new LiquidRenderBudget()
+
const _formatInput = async (input: CyclotronInputType, key: string): Promise<any> => {
const templating = input.templating ?? 'hog'
if (templating === 'liquid') {
- return formatLiquidInput(input.value, newGlobals, key)
+ return formatLiquidInput(input.value, newGlobals, key, liquidBudget)
}
if (templating === 'hog' && input?.bytecode) {
return await formatHogInput(input.bytecode, newGlobals, key)
@@ -289,25 +292,26 @@ export const formatHogInput = async (
export const formatLiquidInput = (
value: unknown,
globals: HogFunctionInvocationGlobalsWithInputs,
- key?: string
+ key?: string,
+ budget: LiquidRenderBudget = new LiquidRenderBudget()
): any => {
if (value === null || value === undefined) {
return value
}
if (typeof value === 'string') {
- return LiquidRenderer.renderWithHogFunctionGlobals(value, globals)
+ return LiquidRenderer.renderWithHogFunctionGlobals(value, globals, budget)
}
if (Array.isArray(value)) {
- return value.map((item) => formatLiquidInput(item, globals, key))
+ return value.map((item) => formatLiquidInput(item, globals, key, budget))
}
if (typeof value === 'object' && value !== null) {
return Object.fromEntries(
Object.entries(value).map(([key2, value]) => [
key2,
- formatLiquidInput(value, globals, key ? `${key}.${key2}` : key2),
+ formatLiquidInput(value, globals, key ? `${key}.${key2}` : key2, budget),
])
)
}
diff --git a/nodejs/src/cdp/utils/liquid.test.ts b/nodejs/src/cdp/utils/liquid.test.ts
index 5826cd4351aa..ba756eb5efd7 100644
--- a/nodejs/src/cdp/utils/liquid.test.ts
+++ b/nodejs/src/cdp/utils/liquid.test.ts
@@ -2,7 +2,7 @@ import * as fs from 'fs'
import * as path from 'path'
import { HogFunctionInvocationGlobalsWithInputs } from '../types'
-import { LiquidRenderer } from './liquid'
+import { LiquidRenderBudget, LiquidRenderer } from './liquid'
describe('LiquidRenderer', () => {
let globals: HogFunctionInvocationGlobalsWithInputs
@@ -250,6 +250,73 @@ describe('LiquidRenderer', () => {
})
})
+ describe('resource limits', () => {
+ it.each([
+ [
+ 'exponential string growth',
+ "{% assign s = 'aaaaaaaa' %}{% for i in (1..40) %}{% assign s = s | append: s %}{% endfor %}{{ s | size }}",
+ 'memory alloc limit exceeded',
+ ],
+ [
+ 'CPU-bound nested loop',
+ '{% assign a = (1..100) %}{% for i in a %}{% for j in a %}{% for k in a %}{% for l in a %}{% endfor %}{% endfor %}{% endfor %}{% endfor %}',
+ 'template render limit exceeded',
+ ],
+ ['oversized template source', '{{ person.name }}'.padEnd(6_000_000, ' '), 'parse length limit exceeded'],
+ [
+ 'literal output amplification',
+ `{% for i in (1..1100) %}${'a'.repeat(10_000)}{% endfor %}`,
+ 'liquid output limit exceeded',
+ ],
+ ])('rejects a template with %s instead of blocking the process', (_name, template, expectedError) => {
+ expect(() => LiquidRenderer.renderWithHogFunctionGlobals(template, globals)).toThrow(expectedError)
+ })
+
+ it('renders an email body whose size comes from an inlined image, not from tags', () => {
+ // Real bodies reach megabytes because a logo is inlined as a base64 data URI. They carry a
+ // handful of tags, so tightening the length caps toward the typical template breaks them.
+ const inlinedImage = `<img src="data:image/png;base64,${'A'.repeat(1_500_000)}" />`
+ const template = `<html>${inlinedImage}<p>Hello {{ person.name }}</p></html>`
+
+ const result = LiquidRenderer.renderWithHogFunctionGlobals(template, globals)
+
+ expect(result).toContain('Hello test_person')
+ expect(result.length).toBeGreaterThan(1_500_000)
+ })
+
+ it('rejects expression filters, which the render deadline cannot interrupt', () => {
+ const template = '{{ (1..3) | where_exp: "x", "x > 1" | size }}'
+ expect(() => LiquidRenderer.renderWithHogFunctionGlobals(template, globals)).toThrow(
+ 'liquid filter where_exp is not supported'
+ )
+ })
+
+ it('decodes many unmatched openers in linear time', () => {
+ const template = '{{'.repeat(50_000)
+ const start = performance.now()
+ expect(() => LiquidRenderer.renderWithHogFunctionGlobals(template, globals)).toThrow('not closed')
+ expect(performance.now() - start).toBeLessThan(1000)
+ })
+
+ it('shares one budget across renders when given one', () => {
+ const budget = new LiquidRenderBudget()
+ const template = `{% for i in (1..600) %}${'a'.repeat(10_000)}{% endfor %}`
+ expect(LiquidRenderer.renderWithHogFunctionGlobals(template, globals, budget)).toHaveLength(6_000_000)
+ expect(() => LiquidRenderer.renderWithHogFunctionGlobals(template, globals, budget)).toThrow(
+ 'liquid output limit exceeded'
+ )
+ })
+
+ it('renders normally after a rejected template', () => {
+ expect(() =>
+ LiquidRenderer.renderWithHogFunctionGlobals('{{ person.name }}'.padEnd(6_000_000, ' '), globals)
+ ).toThrow('parse length limit exceeded')
+ expect(LiquidRenderer.renderWithHogFunctionGlobals('Hello {{ person.name }}!', globals)).toBe(
+ 'Hello test_person!'
+ )
+ })
+ })
+
describe('renderWithHogFunctionGlobals', () => {
it('renders with hog function globals', () => {
const template = 'Event: {{ event.event }}, Person: {{ person.name }}'
diff --git a/nodejs/src/cdp/utils/liquid.ts b/nodejs/src/cdp/utils/liquid.ts
index 48b799a2fdfd..426b83c418b2 100644
--- a/nodejs/src/cdp/utils/liquid.ts
+++ b/nodejs/src/cdp/utils/liquid.ts
@@ -2,7 +2,86 @@ import { Liquid } from 'liquidjs'
import { HogFunctionInvocationGlobalsWithInputs } from '../types'
-const LIQUID_REGEX = /\{\{(.*?)\}\}|{%(.*?)%}/g
+// Rendering is synchronous on shared multi-tenant workers, so an unbounded template would
+// stall or OOM the whole process. These budgets make an over-budget template fail only its own invocation.
+// Length is a weak proxy for render cost: real email bodies reach megabytes because a logo is inlined
+// as a base64 data URI, while carrying only a handful of tags. Time and memory are what bound the work,
+// so the length caps sit above the largest legitimate template rather than near the typical one.
+const LIQUID_PARSE_LIMIT_CHARS = 5_000_000
+// Charged only for values the template constructs (ranges, joins, padding, string filters), so literal
+// passthrough of a large body is free and this still catches expansion.
+const LIQUID_MEMORY_LIMIT_UNITS = 1_000_000
+// Time and output are budgeted per invocation, not per template, because one invocation renders
+// every string leaf of every liquid input and those leaves would otherwise each get a full budget.
+const LIQUID_RENDER_LIMIT_MS = 500
+const LIQUID_OUTPUT_LIMIT_CHARS = 10_000_000
+
+const LIQUID_TAG_CLOSERS: Record<string, string> = { '{': '}}', '%': '%}' }
+
+// These filters evaluate a tenant-written expression once per array item and LiquidJS only checks
+// the render deadline between template nodes, so one filter call can run unbounded. They are replaced
+// with a throwing filter rather than unregistered, because an unknown filter silently acts as identity.
+const LIQUID_UNBOUNDED_FILTERS = ['where_exp', 'find_exp', 'find_index_exp', 'reject_exp', 'group_by_exp']
+
+export class LiquidRenderBudget {
+ private usedMs = 0
+ private outputChars = 0
+
+ remainingMs(): number {
+ return Math.max(0, LIQUID_RENDER_LIMIT_MS - this.usedMs)
+ }
+
+ useTime(ms: number): void {
+ this.usedMs += ms
+ }
+
+ useOutput(chars: number): void {
+ this.outputChars += chars
+ if (this.outputChars > LIQUID_OUTPUT_LIMIT_CHARS) {
+ throw new Error(`liquid output limit exceeded (${LIQUID_OUTPUT_LIMIT_CHARS} characters per invocation)`)
+ }
+ }
+}
+
+const decodeEntities = (tag: string): string => {
+ return tag
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&quot;/g, '"')
+ .replace(/&#x27;/g, "'")
+ .replace(/&amp;/g, '&') // NOTE: This should always be last
+}
+
+// TRICKY: Unlayer replaces all liquid's elements like > for example with &gt;
+// We need to decode these but _only_ for the liquid elements i.e. content within {{ }} or {% %}
+// This is a single forward pass: a regex with a lazy `.*?` rescans to the end of the line for every
+// unmatched opener, which is quadratic on tenant-controlled input.
+const decodeLiquidTags = (template: string): string => {
+ let out = ''
+ let cursor = 0
+ const exhausted = new Set<string>()
+
+ while (cursor < template.length) {
+ const open = template.indexOf('{', cursor)
+ if (open === -1) {
+ break
+ }
+ const closer = LIQUID_TAG_CLOSERS[template[open + 1]]
+ const close = closer && !exhausted.has(closer) ? template.indexOf(closer, open + 2) : -1
+ if (close === -1) {
+ if (closer) {
+ exhausted.add(closer)
+ }
+ out += template.slice(cursor, open + 1)
+ cursor = open + 1
+ continue
+ }
+ out += template.slice(cursor, open) + decodeEntities(template.slice(open, close + 2))
+ cursor = close + 2
+ }
+
+ return out + template.slice(cursor)
+}
export class LiquidRenderer {
private static _liquid: Liquid | null = null
@@ -14,28 +93,44 @@ export class LiquidRenderer {
// Render partials from an in-memory map only: this disables LiquidJS's filesystem-backed
// partial loading, so user-controlled templates can't read local files via include/render/layout.
templates: {},
+ parseLimit: LIQUID_PARSE_LIMIT_CHARS,
+ renderLimit: LIQUID_RENDER_LIMIT_MS,
+ memoryLimit: LIQUID_MEMORY_LIMIT_UNITS,
})
+ for (const name of LIQUID_UNBOUNDED_FILTERS) {
+ this._liquid.registerFilter(name, () => {
+ throw new Error(`liquid filter ${name} is not supported`)
+ })
+ }
}
return this._liquid
}
- static renderWithHogFunctionGlobals(template: string, globals: HogFunctionInvocationGlobalsWithInputs): string {
+ static renderWithHogFunctionGlobals(
+ template: string,
+ globals: HogFunctionInvocationGlobalsWithInputs,
+ budget: LiquidRenderBudget = new LiquidRenderBudget()
+ ): string {
+ // Checked before decoding so the decoder never sees a string LiquidJS would reject anyway.
+ if (template.length > LIQUID_PARSE_LIMIT_CHARS) {
+ throw new Error(`liquid parse length limit exceeded (${LIQUID_PARSE_LIMIT_CHARS} characters)`)
+ }
+
const context = {
...globals,
now: new Date(),
}
- // TRICKY: Unlayer replaces all liquid's elements like > for example with &gt;
- // We need to decode these but _only_ for the liquid elements i.e. content within {{ }} or {% %}
- const decodedTemplate = template.replace(LIQUID_REGEX, (match) => {
- return match
- .replace(/&lt;/g, '<')
- .replace(/&gt;/g, '>')
- .replace(/&quot;/g, '"')
- .replace(/&#x27;/g, "'")
- .replace(/&amp;/g, '&') // NOTE: This should always be last
- })
-
- return this.liquid.parseAndRenderSync(decodedTemplate, context)
+ const start = performance.now()
+ try {
+ const result: string = this.liquid.parseAndRenderSync(decodeLiquidTags(template), context, {
+ renderLimit: budget.remainingMs(),
+ })
+ // String length is O(1) on a V8 rope, so this rejects a huge result before anything flattens it.
+ budget.useOutput(result.length)
+ return result
+ } finally {
+ budget.useTime(performance.now() - start)
+ }
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e5b5865f45af..61d26490fd2e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1664,8 +1664,8 @@ importers:
specifier: ^0.7.15
version: 0.7.16
liquidjs:
- specifier: ^10.27.0
- version: 10.27.0
+ specifier: ^10.27.2
+ version: 10.29.0
lodash:
specifier: ^4.18.1
version: 4.18.1
@@ -18222,6 +18222,11 @@ packages:
engines: {node: '>=16'}
hasBin: true
+ resolution: {integrity: sha512-pCVOhs6FLAR8su3ItJ07diN26t6W5dHQRnmTMy8HPyTFuv1+oSCVJIGp5pGjfQyOZfh50KswvKtMTp6p4JEIdw==}
+ engines: {node: '>=16'}
+ hasBin: true
+
resolution: {integrity: sha512-iyAZCeyD+c1gPyE9qpFu8af0Y+MRtmKOncdGoA2S5EY8iFq99dmmvkNnHiWo+pj0s7yH7l3KPIgee77tKpXPWQ==}
engines: {node: '>=18.0.0'}
@@ -30870,7 +30875,7 @@ snapshots:
escape-goat: 3.0.0
google-libphonenumber: 3.2.40
kafkajs: 2.2.4
- liquidjs: 10.27.0
+ liquidjs: 10.29.0
lodash: 4.18.1
lru-cache: 10.4.3
ssh2-sftp-client: 10.0.3
@@ -30907,7 +30912,7 @@ snapshots:
cheerio: 1.0.0
dayjs: 1.11.11(patch_hash=2e3e09d22bbc20d8961e0392c318f12ffada0babb6422f03b5538af8b2707852)
escape-goat: 3.0.0
- liquidjs: 10.27.0
+ liquidjs: 10.29.0
lodash: 4.18.1
transitivePeerDependencies:
- encoding
@@ -39910,6 +39915,10 @@ snapshots:
dependencies:
commander: 10.0.1
+ dependencies:
+ commander: 10.0.1
+
dependencies:
cli-truncate: 4.0.0