: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): reject hog fetches that loop events back to the same project (#58283)
posthog[bot]1cfb0c07d2b5
diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex cfb857ff0dc4..dec267a13a18 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -18,7 +18,12 @@ import { promisifyCallback } from '../../utils/utils'import { compileHog } from '../templates/compiler'import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'import { createExampleInvocation, createHogExecutionGlobals, createHogFunction } from '../_tests/fixtures'-import { EXTEND_OBJECT_KEY, isConnectionLevelError } from './hog-executor.service'+import {+ EXTEND_OBJECT_KEY,+ extractEmittedEventNames,+ isConnectionLevelError,+ isPostHogIngestHost,+} from './hog-executor.service'// Mock before importing fetchjest.mock('~/utils/request', () => {@@ -1406,6 +1411,299 @@ describe('Hog Executor', () => {`)})+ describe('rejects fetches that would loop events back into the same project', () => {+ const TEAM_API_TOKEN = 'phc_teamtoken123'+ const TEAM_SECRET_API_TOKEN = 'phsk_secrettoken456'++ beforeEach(() => {+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({+ id: 1,+ api_token: TEAM_API_TOKEN,+ secret_api_token: TEAM_SECRET_API_TOKEN,+ } as any)+ // Tests in this block check whether the underlying fetch was invoked, so start+ // each case with a clean call history.+ jest.mocked(fetch).mockClear()+ })++ const expectedRejectionMessage =+ "Refusing to fetch a posthog.com endpoint using this project's own API token"++ it.each([+ ['us.posthog.com host with api_token in body', 'https://us.posthog.com/i/v0/e/', TEAM_API_TOKEN],+ [+ 'eu.posthog.com host with secret_api_token in body',+ 'https://eu.posthog.com/i/v0/e/',+ TEAM_SECRET_API_TOKEN,+ ],+ ['bare posthog.com host with api_token in body', 'https://posthog.com/capture/', TEAM_API_TOKEN],+ ['app.posthog.com host with api_token in body', 'https://app.posthog.com/capture/', TEAM_API_TOKEN],+ ])('rejects %s', async (_name, url, token) => {+ const invocation = await createFetchInvocation({+ url,+ method: 'POST',+ body: JSON.stringify({ api_token: token, event: '$pageview' }),+ })++ const result = await executor.executeFetch(invocation)++ expect(jest.mocked(fetch)).not.toHaveBeenCalled()+ expect(result.finished).toBe(true)+ expect(String(result.error)).toContain(expectedRejectionMessage)+ expect(result.metrics).toEqual([+ expect.objectContaining({+ metric_kind: 'failure',+ metric_name: 'failed',+ }),+ ])+ })++ it('rejects when the team token appears in the URL query string', async () => {+ const invocation = await createFetchInvocation({+ url: `https://us.posthog.com/decide/?token=${TEAM_API_TOKEN}`,+ method: 'GET',+ })++ const result = await executor.executeFetch(invocation)++ expect(jest.mocked(fetch)).not.toHaveBeenCalled()+ expect(result.finished).toBe(true)+ expect(String(result.error)).toContain(expectedRejectionMessage)+ })++ it('rejects when the team token appears in a request header', async () => {+ const invocation = await createFetchInvocation({+ url: 'https://us.posthog.com/i/v0/e/',+ method: 'POST',+ headers: { Authorization: `Bearer ${TEAM_API_TOKEN}` },+ body: JSON.stringify({ event: '$pageview' }),+ })++ const result = await executor.executeFetch(invocation)++ expect(jest.mocked(fetch)).not.toHaveBeenCalled()+ expect(result.finished).toBe(true)+ expect(String(result.error)).toContain(expectedRejectionMessage)+ })++ it('allows posthog.com fetches that use a different token', async () => {+ jest.mocked(fetch).mockResolvedValue({+ status: 200,+ body: 'ok',+ headers: {},+ json: () => Promise.resolve({}),+ text: () => Promise.resolve('ok'),+ dump: () => Promise.resolve(),+ } as any)++ const invocation = await createFetchInvocation({+ url: 'https://us.posthog.com/capture/',+ method: 'POST',+ body: JSON.stringify({ api_token: 'phc_some_other_project', event: '$pageview' }),+ })++ const result = await executor.executeFetch(invocation)++ expect(jest.mocked(fetch)).toHaveBeenCalled()+ expect(result.error).toBeUndefined()+ })++ it('allows fetches to non-posthog domains even when they contain the team token', async () => {+ jest.mocked(fetch).mockResolvedValue({+ status: 200,+ body: 'ok',+ headers: {},+ json: () => Promise.resolve({}),+ text: () => Promise.resolve('ok'),+ dump: () => Promise.resolve(),+ } as any)++ const invocation = await createFetchInvocation({+ url: 'https://example.com/webhook',+ method: 'POST',+ body: JSON.stringify({ api_token: TEAM_API_TOKEN }),+ })++ const result = await executor.executeFetch(invocation)++ expect(jest.mocked(fetch)).toHaveBeenCalled()+ expect(result.error).toBeUndefined()+ })++ it('allows fetches when the team has no api token', async () => {+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({+ id: 1,+ api_token: '',+ secret_api_token: null,+ } as any)+ jest.mocked(fetch).mockResolvedValue({+ status: 200,+ body: 'ok',+ headers: {},+ json: () => Promise.resolve({}),+ text: () => Promise.resolve('ok'),+ dump: () => Promise.resolve(),+ } as any)++ const invocation = await createFetchInvocation({+ url: 'https://us.posthog.com/capture/',+ method: 'POST',+ body: JSON.stringify({ api_token: 'phc_anything' }),+ })++ const result = await executor.executeFetch(invocation)++ expect(jest.mocked(fetch)).toHaveBeenCalled()+ expect(result.error).toBeUndefined()+ })++ describe('when the function has specific trigger events', () => {+ const okFetchResponse = {+ status: 200,+ body: 'ok',+ headers: {},+ json: () => Promise.resolve({}),+ text: () => Promise.resolve('ok'),+ dump: () => Promise.resolve(),+ } as any++ const setHogFunctionFilters = (+ invocation: CyclotronJobInvocationHogFunction,+ eventIds: (string | null)[]+ ) => {+ invocation.hogFunction = {+ ...invocation.hogFunction,+ filters: {+ ...(invocation.hogFunction.filters ?? {}),+ events: eventIds.map((id, order) => ({+ id,+ name: id ?? 'All events',+ type: 'events',+ order,+ })),+ },+ } as any+ }++ it('rejects when the emitted event matches one of the trigger events', async () => {+ const invocation = await createFetchInvocation({+ url: 'https://us.posthog.com/i/v0/e/',+ method: 'POST',+ body: JSON.stringify({ api_token: TEAM_API_TOKEN, event: '$pageview' }),+ })+ setHogFunctionFilters(invocation, ['$pageview'])++ const result = await executor.executeFetch(invocation)++ expect(jest.mocked(fetch)).not.toHaveBeenCalled()+ expect(result.finished).toBe(true)+ expect(String(result.error)).toContain(expectedRejectionMessage)+ })++ it('allows when the emitted event does not match any trigger event', async () => {+ jest.mocked(fetch).mockResolvedValue(okFetchResponse)+ const invocation = await createFetchInvocation({+ url: 'https://us.posthog.com/i/v0/e/',+ method: 'POST',+ body: JSON.stringify({ api_token: TEAM_API_TOKEN, event: '$set' }),+ })+ setHogFunctionFilters(invocation, ['$pageview', '$autocapture'])++ const result = await executor.executeFetch(invocation)++ expect(jest.mocked(fetch)).toHaveBeenCalled()+ expect(result.error).toBeUndefined()+ })++ it('rejects when batch body contains a matching event as the first entry', async () => {+ const invocation = await createFetchInvocation({+ url: 'https://us.posthog.com/batch/',+ method: 'POST',+ body: JSON.stringify({+ api_token: TEAM_API_TOKEN,+ batch: [{ event: '$pageview' }, { event: '$set' }],+ }),+ })+ setHogFunctionFilters(invocation, ['$pageview'])++ const result = await executor.executeFetch(invocation)++ expect(jest.mocked(fetch)).not.toHaveBeenCalled()+ expect(result.finished).toBe(true)+ expect(String(result.error)).toContain(expectedRejectionMessage)+ })++ it('rejects when batch body contains a matching event as a non-first entry', async () => {+ // Regression: earlier implementation only checked batch[0]. A batch where the+ // first entry doesn't match but a later entry does would form a loop after+ // the matching event re-triggers the function.+ const invocation = await createFetchInvocation({+ url: 'https://us.posthog.com/batch/',+ method: 'POST',+ body: JSON.stringify({+ api_token: TEAM_API_TOKEN,+ batch: [{ event: '$set' }, { event: '$pageview' }],+ }),+ })+ setHogFunctionFilters(invocation, ['$pageview'])++ const result = await executor.executeFetch(invocation)++ expect(jest.mocked(fetch)).not.toHaveBeenCalled()+ expect(result.finished).toBe(true)+ expect(String(result.error)).toContain(expectedRejectionMessage)+ })++ it('allows when no event in a batch body matches any trigger event', async () => {+ jest.mocked(fetch).mockResolvedValue(okFetchResponse)+ const invocation = await createFetchInvocation({+ url: 'https://us.posthog.com/batch/',+ method: 'POST',+ body: JSON.stringify({+ api_token: TEAM_API_TOKEN,+ batch: [{ event: '$set' }, { event: '$groupidentify' }],+ }),+ })+ setHogFunctionFilters(invocation, ['$pageview', '$autocapture'])++ const result = await executor.executeFetch(invocation)++ expect(jest.mocked(fetch)).toHaveBeenCalled()+ expect(result.error).toBeUndefined()+ })++ it('allows when the body is unparseable (no extractable event name, cannot form a loop)', async () => {+ jest.mocked(fetch).mockResolvedValue(okFetchResponse)+ const invocation = await createFetchInvocation({+ url: 'https://us.posthog.com/capture/',+ method: 'POST',+ body: `not-json-${TEAM_API_TOKEN}-garbage`,+ })+ setHogFunctionFilters(invocation, ['$pageview'])++ const result = await executor.executeFetch(invocation)++ expect(jest.mocked(fetch)).toHaveBeenCalled()+ expect(result.error).toBeUndefined()+ })++ it('rejects when filter is null id (all-events)', async () => {+ const invocation = await createFetchInvocation({+ url: 'https://us.posthog.com/i/v0/e/',+ method: 'POST',+ body: JSON.stringify({ api_token: TEAM_API_TOKEN, event: '$set' }),+ })+ setHogFunctionFilters(invocation, [null])++ const result = await executor.executeFetch(invocation)++ expect(jest.mocked(fetch)).not.toHaveBeenCalled()+ expect(result.finished).toBe(true)+ expect(String(result.error)).toContain(expectedRejectionMessage)+ })+ })+ })+it('replaces access token placeholders in body, headers, and url', async () => {const mockIntegrationInputs = {oauth: {@@ -1452,6 +1750,61 @@ describe('Hog Executor', () => {})})+ describe('isPostHogIngestHost', () => {+ it.each([+ [true, 'https://posthog.com'],+ [true, 'https://us.posthog.com/capture/'],+ [true, 'https://eu.posthog.com/i/v0/e/'],+ [true, 'https://app.posthog.com/decide/'],+ [true, 'http://posthog.com/anything'],+ [false, 'https://notposthog.com/capture/'],+ [false, 'https://posthog.com.evil.example/capture/'],+ [false, 'https://example.com/posthog.com/'],+ [false, 'not a url'],+ [false, ''],+ ])('returns %s for %s', (expected, url) => {+ expect(isPostHogIngestHost(url)).toBe(expected)+ })+ })++ describe('extractEmittedEventNames', () => {+ it.each<[string, string | undefined, string[] | null]>([+ [+ 'returns a single-element array for a standard capture body',+ JSON.stringify({ event: '$pageview' }),+ ['$pageview'],+ ],+ [+ 'returns the event when other fields are present',+ JSON.stringify({ api_token: 'phc_x', event: '$set', properties: {} }),+ ['$set'],+ ],+ [+ 'returns every event in a batch body',+ JSON.stringify({ batch: [{ event: 'first' }, { event: 'second' }, { event: 'third' }] }),+ ['first', 'second', 'third'],+ ],+ [+ 'skips non-string event entries in a batch',+ JSON.stringify({ batch: [{ event: 'ok' }, { event: 123 }, { properties: {} }, { event: 'also-ok' }] }),+ ['ok', 'also-ok'],+ ],+ ['returns null for an empty body', '', null],+ ['returns null for undefined', undefined, null],+ ['returns null for a non-JSON body', 'not-json-at-all', null],+ ['returns null when body has no event field', JSON.stringify({ api_token: 'phc_x' }), null],+ ['returns null when event field is non-string', JSON.stringify({ event: 123 }), null],+ ['returns null when batch is empty', JSON.stringify({ batch: [] }), null],+ [+ 'returns null when no batch entries have a string event',+ JSON.stringify({ batch: [{ properties: {} }, { event: 123 }] }),+ null,+ ],+ ])('%s', (_name, body, expected) => {+ expect(extractEmittedEventNames(body as any)).toEqual(expected)+ })+ })+describe('isConnectionLevelError', () => {it.each([[{ code: 'UND_ERR_SOCKET', message: 'other side closed' }, true],diff --git a/nodejs/src/cdp/services/hog-executor.service.ts b/nodejs/src/cdp/services/hog-executor.service.tsindex 0c338847a036..0a31e4dc3da7 100644--- a/nodejs/src/cdp/services/hog-executor.service.ts+++ b/nodejs/src/cdp/services/hog-executor.service.ts@@ -155,6 +155,42 @@ export const MAX_ASYNC_STEPS = 5export const MAX_HOG_LOGS = 25export const EXTEND_OBJECT_KEY = '$$_extend_object'+// Hosts that we consider to be PostHog's own ingest endpoints. Hog function `fetch()` calls+// targeting these hosts with the same project's API token would create an event-forwarding loop,+// so we block them and surface guidance to use `postHogCapture` or a transformation instead.+export const isPostHogIngestHost = (urlString: string): boolean => {+ try {+ const hostname = new URL(urlString).hostname.toLowerCase()+ return hostname === 'posthog.com' || hostname.endsWith('.posthog.com')+ } catch {+ return false+ }+}++export const extractEmittedEventNames = (body: string | null | undefined): string[] | null => {+ if (!body) {+ return null+ }+ try {+ const parsed = parseJSON(body)+ if (parsed && typeof parsed === 'object') {+ if (typeof (parsed as any).event === 'string') {+ return [(parsed as any).event]+ }+ const batch = (parsed as any).batch+ if (Array.isArray(batch) && batch.length > 0) {+ const names = batch.map((e: any) => e?.event).filter((n: any): n is string => typeof n === 'string')+ if (names.length > 0) {+ return names+ }+ }+ }+ } catch {+ // unparseable+ }+ return null+}+const hogExecutionDuration = new Histogram({name: 'cdp_hog_function_execution_duration_ms',help: 'Processing time and success status of internal functions',@@ -662,6 +698,43 @@ export class HogExecutorService {}}+ if (isPostHogIngestHost(params.url)) {+ const team = await this.asyncContext.teamManager.getTeam(invocation.teamId)+ const teamTokens = [team?.api_token, team?.secret_api_token].filter(+ (token): token is string => typeof token === 'string' && token.length > 0+ )+ if (teamTokens.length > 0) {+ const haystack = `${params.url}\n${params.body ?? ''}\n${Object.values(headers).join('\n')}`+ const matchedToken = teamTokens.find((token) => haystack.includes(token))+ if (matchedToken) {+ const emittedEvents = extractEmittedEventNames(params.body)+ const triggerEventIds = (invocation.hogFunction.filters?.events ?? []).map((event) => event.id)+ const matchesAllEvents = triggerEventIds.length === 0 || triggerEventIds.some((id) => id === null)+ const wouldLoop =+ matchesAllEvents ||+ (emittedEvents !== null && emittedEvents.some((e) => triggerEventIds.includes(e)))++ if (wouldLoop) {+ const message =+ "Refusing to fetch a posthog.com endpoint using this project's own API token — this would create an event-forwarding loop. " ++ 'If you want to capture an event back into this project, use the `postHogCapture` helper. ' ++ 'If you want to enrich or modify incoming events, use a transformation instead.'+ addLog('error', message)+ result.metrics.push({+ team_id: invocation.teamId,+ app_source_id: invocation.parentRunId ?? invocation.functionId,+ metric_kind: 'failure',+ metric_name: 'failed',+ count: 1,+ })+ result.error = new Error(message)+ result.finished = true+ return result+ }+ }+ }+ }+const fetchParams: FetchOptions = { method, headers }if (!['GET', 'HEAD'].includes(method) && params.body) {