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.

16.2 KB
Raw Blame
import { createMockJobQueue } from '~/tests/helpers/mocks/job-queue.mock'
import { mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'
import { mockFetch } from '~/tests/helpers/mocks/request.mock'

import crypto from 'crypto'
import { Server } from 'http'
import { DateTime, Settings } from 'luxon'
import supertest from 'supertest'
import express from 'ultimate-express'

import { insertHogFunction, insertHogFunctionTemplate } from '~/cdp/_tests/fixtures'
import { CdpApi } from '~/cdp/cdp-api'
import { HogFunctionType } from '~/cdp/types'
import { setupExpressApp } from '~/common/api/router'
import { KAFKA_WAREHOUSE_SOURCE_WEBHOOKS } from '~/common/config/kafka-topics'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { parseJSON } from '~/common/utils/json-parse'
import { createCdpConsumerDeps } from '~/tests/helpers/cdp'
import { createTestTeamFixture } from '~/tests/helpers/sql'
import { Hub, Team } from '~/types'

import { compileInputs } from '../templates/test/test-helpers'

const STRIPE_TEMPLATE_ID = 'template-warehouse-source-stripe'

const STRIPE_INPUTS_SCHEMA = [
    {
        type: 'string' as const,
        key: 'signing_secret',
        label: 'Signing secret',
        required: false,
        secret: true,
        hidden: false,
        description: 'Used to validate the webhook came from Stripe',
    },
    {
        type: 'boolean' as const,
        key: 'bypass_signature_check',
        label: 'Bypass signature check',
        description: 'If set, the stripe-signature header will not be checked. This is not recommended.',
        default: false,
        required: false,
        secret: false,
    },
    {
        type: 'json' as const,
        key: 'schema_mapping',
        label: 'Schema mapping',
        description: 'Maps Stripe object types to ExternalDataSchema IDs',
        required: true,
        secret: false,
        hidden: true,
    },
    {
        type: 'string' as const,
        key: 'source_id',
        label: 'Source ID',
        description: 'The ExternalDataSource ID this webhook is associated with',
        required: true,
        secret: false,
        hidden: true,
    },
]

const STRIPE_HOG_CODE = `
if (request.method != 'POST') {
  return {
    'httpResponse': {
      'status': 405,
      'body': 'Method not allowed'
    }
  }
}

if (not inputs.bypass_signature_check) {
  if (empty(inputs.signing_secret)) {
    return {
      'httpResponse': {
        'status': 200,
        'body': 'Signing secret not configured, delivery dropped',
      },
      'appMetric': 'missing_credential'
    }
  }

  let body := request.stringBody
  let signatureHeader := request.headers['stripe-signature']

  if (empty(signatureHeader)) {
    return {
      'httpResponse': {
        'status': 400,
        'body': 'Missing signature',
      }
    }
  }

  let headerParts := splitByString(',', signatureHeader)
  let timestamp := null
  let v1Signature := null

  for (let _, part in headerParts) {
      let trimmed := trim(part)
      if (trimmed like 't=%') {
          let tParts := splitByString('=', trimmed, 2)
          if (length(tParts) = 2) {
              timestamp := tParts[2]
          }
      }
      if (trimmed like 'v1=%') {
          let v1Parts := splitByString('=', trimmed, 2)
          if (length(v1Parts) = 2) {
              v1Signature := v1Parts[2]
          }
      }
  }

  if (empty(timestamp) or empty(v1Signature)) {
      return {
        'httpResponse': {
          'status': 400,
          'body': 'Could not parse signature',
        }
      }
  }

  let signedPayload := concat(timestamp, '.', body)
  let computedSignature := sha256HmacChainHex([inputs.signing_secret, signedPayload])

  if (computedSignature != v1Signature) {
      return {
        'httpResponse': {
          'status': 400,
          'body': 'Bad signature',
        }
      }
  }
}

let objectType := request.body.data?.object?.object

if (empty(objectType)) {
  return {
    'httpResponse': {
      'status': 200,
      'body': 'No object type found, skipping'
    }
  }
}

let schemaId := inputs.schema_mapping?.[objectType]

if (empty(schemaId)) {
  return {
    'httpResponse': {
      'status': 200,
      'body': f'No schema mapping for object type: {objectType}, skipping'
    }
  }
}

produceToWarehouseWebhooks(request.body, schemaId)
`

// Minimal template-like object for compileInputs (only needs inputs_schema)
const stripeTemplateForInputs = { inputs_schema: STRIPE_INPUTS_SCHEMA } as any

describe('DWH source webhooks', () => {
    let hub: Hub
    let team: Team

    beforeEach(async () => {
        hub = await createHub({})
        team = (await createTestTeamFixture(hub.postgres)).team
        mockFetch.mockClear()
    })

    afterEach(async () => {
        await closeHub(hub)
    })

    describe('handleWarehouseSourceWebhook', () => {
        let api: CdpApi
        let app: express.Application
        let server: Server
        let hogFunction: HogFunctionType
        let stripeTemplateId: string
        let defaultTemplateId: string

        const invoiceSchemaId = 'test-schema-id-invoice'
        const chargeSchemaId = 'test-schema-id-charge'
        const subscriptionSchemaId = 'test-schema-id-subscription'
        const schemaMapping = {
            invoice: invoiceSchemaId,
            charge: chargeSchemaId,
            subscription: subscriptionSchemaId,
        }
        const signingSecret = 'whsec_testsecret'

        beforeEach(async () => {
            api = new CdpApi(hub, createCdpConsumerDeps(hub), {
                hogQueue: createMockJobQueue(),
                hogflowQueue: createMockJobQueue(),
            })
            app = setupExpressApp()
            app.use('/', api.router())
            server = app.listen(0, () => {})

            Settings.defaultZone = 'UTC'
            const fixedTime = DateTime.fromObject({ year: 2025, month: 1, day: 1 }, { zone: 'UTC' })
            jest.spyOn(Date, 'now').mockReturnValue(fixedTime.toMillis())

            stripeTemplateId = `${STRIPE_TEMPLATE_ID}-${team.id}`
            defaultTemplateId = `template-warehouse-source-default-${team.id}`

            // Insert the warehouse source templates into the DB
            await insertHogFunctionTemplate(hub.postgres, {
                id: stripeTemplateId,
                name: 'Stripe warehouse source webhook',
                type: 'warehouse_source_webhook',
                code: STRIPE_HOG_CODE,
                inputs_schema: STRIPE_INPUTS_SCHEMA,
            })

            await insertHogFunctionTemplate(hub.postgres, {
                id: defaultTemplateId,
                name: 'Default warehouse source webhook',
                type: 'warehouse_source_webhook',
                code: 'produceToWarehouseWebhooks(request.body)',
                inputs_schema: [],
            })

            hogFunction = await insertHogFunction(hub.postgres, team.id, {
                type: 'warehouse_source_webhook',
                template_id: stripeTemplateId,
                bytecode: [],
                inputs: {
                    ...(await compileInputs(stripeTemplateForInputs, {
                        signing_secret: signingSecret,
                        bypass_signature_check: false,
                    })),
                    schema_mapping: { value: schemaMapping },
                    source_id: { value: 'test-source-id' },
                    source_type: { value: 'Stripe' },
                },
            })

            await api.start()
        })

        afterEach(async () => {
            await api.stop()
            server.close()
        })

        const createStripeWebhookRequest = (secret: string, body?: Record<string, any>) => {
            const payload = JSON.stringify(
                body ?? {
                    type: 'invoice.payment_succeeded',
                    data: { object: { id: 'inv_1', object: 'invoice' } },
                }
            )
            const timestamp = Math.floor(Date.now() / 1000)
            const signature = crypto
                .createHmac('sha256', secret)
                .update(`${timestamp}.${payload}`, 'utf8')
                .digest('hex')
            return {
                body: parseJSON(payload),
                headers: { 'stripe-signature': `t=${timestamp},v1=${signature}` },
            }
        }

        const doDwhPostRequest = async (options: {
            webhookId?: string
            headers?: Record<string, string>
            body?: Record<string, any>
        }) => {
            return supertest(app)
                .post(`/public/webhooks/dwh/${options.webhookId ?? hogFunction.id}`)
                .set('Content-Type', 'application/json')
                .set(options.headers ?? {})
                .send(options.body)
        }

        const getDwhKafkaMessages = () => {
            return mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_WAREHOUSE_SOURCE_WEBHOOKS)
        }

        const waitForBackgroundTasks = async () => {
            await api['cdpSourceWebhooksConsumer']['promiseScheduler'].waitForAllSettled()
        }

        const getMetricNames = (): string[] => {
            return mockProducerObserver
                .getProducedKafkaMessagesForTopic('clickhouse_app_metrics2_test')
                .map((message) => message.value.metric_name) as string[]
        }

        it('should return 404 for non-existent webhook ID', async () => {
            const res = await doDwhPostRequest({ webhookId: 'non-existent-id' })
            expect(res.status).toEqual(404)
            expect(res.body).toEqual({ error: 'Not found' })
        })

        it('should process a valid Stripe webhook and produce to Kafka', async () => {
            const webhookReq = createStripeWebhookRequest(signingSecret)

            const res = await doDwhPostRequest({
                headers: webhookReq.headers,
                body: webhookReq.body,
            })

            expect(res.status).toEqual(201)
            expect(res.body).toEqual({ status: 'queued' })

            await waitForBackgroundTasks()

            const kafkaMessages = getDwhKafkaMessages()
            expect(kafkaMessages).toHaveLength(1)
            expect(kafkaMessages[0].key).toEqual(`${team.id}:${invoiceSchemaId}`)
            expect(kafkaMessages[0].value).toMatchObject({
                team_id: team.id,
                schema_id: invoiceSchemaId,
                payload: JSON.stringify({
                    type: 'invoice.payment_succeeded',
                    data: { object: { id: 'inv_1', object: 'invoice' } },
                }),
            })
        })

        it('should return 400 for invalid Stripe signature', async () => {
            const webhookReq = createStripeWebhookRequest('wrong-secret')

            const res = await doDwhPostRequest({
                headers: webhookReq.headers,
                body: webhookReq.body,
            })

            expect(res.status).toEqual(400)
            expect(res.text).toEqual('Bad signature')
            expect(getDwhKafkaMessages()).toHaveLength(0)
        })

        it('should return 400 when stripe-signature header is missing', async () => {
            const res = await doDwhPostRequest({
                body: { type: 'invoice.created' },
            })

            expect(res.status).toEqual(400)
            expect(res.text).toEqual('Missing signature')
            expect(getDwhKafkaMessages()).toHaveLength(0)
        })

        it('should bypass signature check when configured', async () => {
            const bypassFunction = await insertHogFunction(hub.postgres, team.id, {
                type: 'warehouse_source_webhook',
                template_id: stripeTemplateId,
                bytecode: [],
                inputs: {
                    ...(await compileInputs(stripeTemplateForInputs, {
                        signing_secret: '',
                        bypass_signature_check: true,
                    })),
                    schema_mapping: { value: schemaMapping },
                    source_id: { value: 'test-source-id' },
                    source_type: { value: 'Stripe' },
                },
            })

            const res = await doDwhPostRequest({
                webhookId: bypassFunction.id,
                body: { type: 'charge.succeeded', data: { object: { id: 'ch_1', object: 'charge' } } },
            })

            expect(res.status).toEqual(201)
            expect(res.body).toEqual({ status: 'queued' })

            await waitForBackgroundTasks()

            const kafkaMessages = getDwhKafkaMessages()
            expect(kafkaMessages).toHaveLength(1)
            expect(kafkaMessages[0].key).toEqual(`${team.id}:${chargeSchemaId}`)
        })

        it('should drop the delivery instead of rejecting it when no signing secret is set', async () => {
            const unconfiguredFunction = await insertHogFunction(hub.postgres, team.id, {
                type: 'warehouse_source_webhook',
                template_id: stripeTemplateId,
                bytecode: [],
                inputs: {
                    ...(await compileInputs(stripeTemplateForInputs, {
                        signing_secret: '',
                        bypass_signature_check: false,
                    })),
                    schema_mapping: { value: schemaMapping },
                    source_id: { value: 'test-source-id' },
                    source_type: { value: 'Stripe' },
                },
            })

            const res = await doDwhPostRequest({
                webhookId: unconfiguredFunction.id,
                body: { type: 'charge.succeeded', data: { object: { id: 'ch_1', object: 'charge' } } },
            })

            // A 4xx here makes the provider retry for hours over a gap only the customer can close.
            expect(res.status).toEqual(200)
            expect(res.text).toEqual('Signing secret not configured, delivery dropped')
            expect(getDwhKafkaMessages()).toHaveLength(0)

            await waitForBackgroundTasks()

            expect(getMetricNames()).toContain('missing_credential')
        })

        it('should return 200 and skip when object type is not in schema_mapping', async () => {
            const webhookReq = createStripeWebhookRequest(signingSecret, {
                type: 'payment_intent.created',
                data: { object: { id: 'pi_1', object: 'payment_intent' } },
            })

            const res = await doDwhPostRequest({
                headers: webhookReq.headers,
                body: webhookReq.body,
            })

            expect(res.status).toEqual(200)
            expect(res.text).toContain('No schema mapping for object type')
            expect(getDwhKafkaMessages()).toHaveLength(0)
        })

        it('should return 200 and skip when event has no object type', async () => {
            const webhookReq = createStripeWebhookRequest(signingSecret, {
                type: 'some.event',
                data: { object: { id: 'obj_1' } },
            })

            const res = await doDwhPostRequest({
                headers: webhookReq.headers,
                body: webhookReq.body,
            })

            expect(res.status).toEqual(200)
            expect(res.text).toContain('No object type found')
            expect(getDwhKafkaMessages()).toHaveLength(0)
        })

        it('should include the full webhook body in the Kafka payload', async () => {
            const eventBody = {
                type: 'customer.subscription.created',
                data: {
                    object: {
                        id: 'sub_123',
                        object: 'subscription',
                        customer: 'cus_456',
                        status: 'active',
                        items: { data: [{ price: { id: 'price_789' } }] },
                    },
                },
            }
            const webhookReq = createStripeWebhookRequest(signingSecret, eventBody)

            const res = await doDwhPostRequest({
                headers: webhookReq.headers,
                body: webhookReq.body,
            })

            expect(res.status).toEqual(201)
            await waitForBackgroundTasks()

            const kafkaMessages = getDwhKafkaMessages()
            expect(kafkaMessages).toHaveLength(1)
            expect(kafkaMessages[0].value).toMatchObject({
                team_id: team.id,
                schema_id: subscriptionSchemaId,
                payload: JSON.stringify(eventBody),
            })
        })
    })
})