: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(agent-platform): deterministic payload filters for webhook triggers (#72056)
Tom Piccirello23fd905e7569
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/webhook-filters.test.ts b/products/agent_platform/services/agent-ingress/src/triggers/webhook-filters.test.tsnew file mode 100644index 000000000000..3a2358378290--- /dev/null+++ b/products/agent_platform/services/agent-ingress/src/triggers/webhook-filters.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest'++import { payloadMatchesFilters } from './webhook-filters'++describe('payloadMatchesFilters', () => {+ const REVIEW_REQUESTED = {+ action: 'review_requested',+ pull_request: { number: 7, draft: false },+ requested_team: { slug: 'team-security' },+ installation: { id: 42 },+ }+ const TEAM_REVIEW_FILTERS = [+ { path: 'action', equals: 'review_requested' },+ { path: 'requested_team.slug', equals: 'team-security' },+ ]++ it('passes when every filter matches — the GitHub team-review-requested gate', () => {+ expect(payloadMatchesFilters(REVIEW_REQUESTED, TEAM_REVIEW_FILTERS)).toBe(true)+ })++ it.each<[string, unknown]>([+ ['a different action (synchronize noise)', { ...REVIEW_REQUESTED, action: 'synchronize' }],+ // Review requested from an individual carries requested_reviewer, not+ // requested_team — the path is absent and must not match.+ [+ 'review requested from a user, not a team',+ { action: 'review_requested', requested_reviewer: { login: 'alice' } },+ ],+ ['a scalar where the path expects an object', { action: 'review_requested', requested_team: 'team-security' }],+ ['a null body', null],+ ])('rejects %s', (_label, body) => {+ expect(payloadMatchesFilters(body, TEAM_REVIEW_FILTERS)).toBe(false)+ })++ it('never matches a path routed through an array (documented objects-only limit)', () => {+ // Authors must address a scalar field, not one inside a list — a path+ // through an array resolves to no value, so the delivery is filtered.+ const body = { pull_request: { labels: [{ name: 'security' }] } }+ expect(payloadMatchesFilters(body, [{ path: 'pull_request.labels.0.name', equals: 'security' }])).toBe(false)+ })++ it('is AND semantics — one matching filter cannot carry a failing one', () => {+ const body = { action: 'review_requested', requested_team: { slug: 'team-platform' } }+ expect(payloadMatchesFilters(body, TEAM_REVIEW_FILTERS)).toBe(false)+ })++ it.each<[string, ReadonlyArray<{ path: string; equals: string | number | boolean }> | undefined]>([+ ['undefined filters', undefined],+ ['empty filters', []],+ ])('passes everything with %s — existing agents are unaffected', (_label, filters) => {+ expect(payloadMatchesFilters({ anything: true }, filters)).toBe(true)+ })++ it.each<[string, { path: string; equals: string | number | boolean }, boolean]>([+ ['number match', { path: 'installation.id', equals: 42 }, true],+ ['number mismatch', { path: 'installation.id', equals: 41 }, false],+ ['boolean match', { path: 'pull_request.draft', equals: false }, true],+ // Strict equality: the string '42' must not match the number 42.+ ['no cross-type coercion', { path: 'installation.id', equals: '42' }, false],+ ])('primitive equality: %s', (_label, filter, expected) => {+ expect(payloadMatchesFilters(REVIEW_REQUESTED, [filter])).toBe(expected)+ })++ it('resolves own properties only — prototype members are not payload data', () => {+ expect(payloadMatchesFilters({}, [{ path: 'constructor', equals: 'x' }])).toBe(false)+ expect(payloadMatchesFilters({ a: {} }, [{ path: 'a.toString', equals: 'x' }])).toBe(false)+ })+})diff --git a/products/agent_platform/services/agent-ingress/src/triggers/webhook-filters.ts b/products/agent_platform/services/agent-ingress/src/triggers/webhook-filters.tsnew file mode 100644index 000000000000..adbd3e9b7f2f--- /dev/null+++ b/products/agent_platform/services/agent-ingress/src/triggers/webhook-filters.ts@@ -0,0 +1,40 @@+/**+ * Deterministic webhook payload gate. A provider like GitHub delivers every+ * `pull_request` action to the hook — `opened`, `synchronize`, `labeled`, …+ * — while an agent typically wants exactly one shape (say+ * `action == 'review_requested'` AND `requested_team.slug == 'team-security'`).+ * Filtering in `agent.md` would spend a full model session per irrelevant+ * event; this gate answers before a session exists, from the trigger's+ * declared `config.filters`.+ */++import type { WebhookFilter } from '@posthog/agent-shared'++/**+ * Walk a dot-path through plain objects, resolving OWN properties only —+ * the body is attacker-supplied, so prototype members (`constructor`,+ * `toString`, …) are never treated as payload data. Any non-object hop or+ * missing key resolves to undefined.+ */+function resolvePath(body: unknown, path: string): unknown {+ let current: unknown = body+ for (const segment of path.split('.')) {+ if (current === null || typeof current !== 'object' || Array.isArray(current)) {+ return undefined+ }+ if (!Object.hasOwn(current, segment)) {+ return undefined+ }+ current = (current as Record<string, unknown>)[segment]+ }+ return current+}++/** True when EVERY filter's path strictly equals its expected value (AND).+ * No filters declared = every payload matches (backwards compatible). */+export function payloadMatchesFilters(body: unknown, filters: readonly WebhookFilter[] | undefined): boolean {+ if (!filters || filters.length === 0) {+ return true+ }+ return filters.every((filter) => resolvePath(body, filter.path) === filter.equals)+}diff --git a/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts b/products/agent_platform/services/agent-ingress/src/triggers/webhook.tsindex d1121af0c10b..383d3f83270a 100644--- a/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts+++ b/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts@@ -11,13 +11,16 @@ import { Request } from 'express'import { createHash } from 'node:crypto'import type { z } from 'zod'-import { type Trigger, TRIGGER_ROUTES } from '@posthog/agent-shared'+import { createLogger, type Trigger, TRIGGER_ROUTES } from '@posthog/agent-shared'import { principalDisplay } from '../enqueue/acl'import { enqueueOrResume } from '../enqueue/enqueue'import { defineRoute, type AuthedRouteCtx, type TriggerModule } from './types'+import { payloadMatchesFilters } from './webhook-filters'import { WebhookBodySchema } from './webhook.schemas'+const log = createLogger('webhook-trigger')+async function webhookHandler(ctx: AuthedRouteCtx<z.infer<typeof WebhookBodySchema>>): Promise<void> {const { req, res, deps, resolved } = ctx// A mislabeled urlencoded Content-Type still passes `WebhookBodySchema` (Express parses the raw JSON into a garbage form object), which would silently become the seed message. Reject explicitly.@@ -26,9 +29,22 @@ async function webhookHandler(ctx: AuthedRouteCtx<z.infer<typeof WebhookBodySchereturn}const body = ctx.parsed+ // Deterministic payload gate, AFTER auth (the mount guard already+ // verified the caller): a non-matching delivery is ACKed 2xx with no+ // session, so chatty providers stay healthy without spending a model+ // session per irrelevant event.+ const trigger = resolved.revision.spec.triggers.find((t) => t.type === 'webhook')+ const filters = trigger?.type === 'webhook' ? trigger.config.filters : undefined+ if (!payloadMatchesFilters(body, filters)) {+ // Log it: a filter whose path never matches (e.g. one that points+ // through an array) silently drops every delivery, and the provider+ // only sees a healthy 200 — this line is the one place that shows why.+ log.info({ slug: resolved.application.slug }, 'webhook_delivery_filtered')+ res.json({ ok: true, filtered: true })+ return+ }const externalKeyHeader = req.headers['x-external-key']const externalKey = typeof externalKeyHeader === 'string' ? externalKeyHeader : null- const trigger = resolved.revision.spec.triggers.find((t) => t.type === 'webhook')const idempotencyKey = extractIdempotencyKey(req, body, trigger)const sessionPrincipal = ctx.principalconst outcome = await enqueueOrResume(diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.ts b/products/agent_platform/services/agent-shared/src/spec/spec.tsindex eb6aeb270ff1..5290db81b33c 100644--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts@@ -121,6 +121,25 @@ export const AuthConfigSchema = z.object({modes: z.array(AuthModeSchema).default([{ type: 'posthog_internal' }]),})+/**+ * One deterministic gate on a webhook payload: the value at the dot-path in+ * the JSON body must strictly equal `equals` (own properties only, no type+ * coercion). All filters on a trigger must match (AND) for a delivery to+ * create a session; a non-matching delivery is ACKed `200 {ok, filtered}`+ * WITHOUT running the agent, so a chatty provider (GitHub sends every+ * pull_request action) doesn't spend a model session per irrelevant event and+ * still sees the 2xx it needs to keep the hook healthy.+ */+export const WebhookFilterSchema = z.object({+ /** Dot-path into the JSON body, e.g. `action` or `requested_team.slug`.+ * Traverses objects only — a path segment that lands on an array (or any+ * non-object) resolves to no value and the filter never matches, so a+ * delivery is filtered out. Address a scalar field, not one inside a list. */+ path: z.string().min(1),+ equals: z.union([z.string(), z.number(), z.boolean()]),+})+export type WebhookFilter = z.infer<typeof WebhookFilterSchema>+export const TriggerSchema = z.discriminatedUnion('type', [/*** Slack trigger. These spec flags only control what the INGRESS does with@@ -244,6 +263,9 @@ export const TriggerSchema = z.discriminatedUnion('type', [type: z.literal('webhook'),config: z.object({path: z.string(),+ /** Deterministic payload gate — see {@link WebhookFilterSchema}.+ * Omitted/empty = every authenticated delivery runs the agent. */+ filters: z.array(WebhookFilterSchema).max(16).optional(),}),auth: AuthConfigSchema,}),diff --git a/products/agent_platform/services/agent-tests/src/cases/webhook-mcp-trigger.test.ts b/products/agent_platform/services/agent-tests/src/cases/webhook-mcp-trigger.test.tsindex bb1314cf57d7..0fe18176366f 100644--- a/products/agent_platform/services/agent-tests/src/cases/webhook-mcp-trigger.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/webhook-mcp-trigger.test.ts@@ -30,6 +30,42 @@ describe('webhook trigger: real e2e', () => {await closeSharedPool()})+ it('config.filters gates deliveries deterministically — non-matching is ACKed 200 with no session', async () => {+ c.setScript([fauxText('ack')])+ await c.deployAgent({+ slug: 'wh-filtered',+ spec: {+ triggers: [+ {+ type: 'webhook',+ config: {+ path: '/webhook',+ filters: [+ { path: 'action', equals: 'review_requested' },+ { path: 'requested_team.slug', equals: 'team-security' },+ ],+ },+ auth: { modes: [{ type: 'public', acknowledge_public_exposure: true }] },+ },+ ],+ },+ })++ // The noise GitHub actually sends: same event type, wrong action.+ const miss = await request(c.ingress).post('/agents/wh-filtered/webhook').send({ action: 'synchronize' })+ expect(miss.status).toBe(200)+ expect(miss.body).toEqual({ ok: true, filtered: true })++ const hit = await request(c.ingress)+ .post('/agents/wh-filtered/webhook')+ .send({ action: 'review_requested', requested_team: { slug: 'team-security' } })+ expect(hit.status).toBe(200)+ expect(hit.body.session_id).toBeTruthy()+ await c.drain()+ const session = await c.queue.get(hit.body.session_id)+ expect(session!.state).toBe('completed')+ })+it('creates a session with the JSON body as content', async () => {c.setScript([fauxText('ack')])await c.deployAgent({ slug: 'wh', spec: {} })