Skip to content
Source
Sign inSign up
samwillis/neon-durable-streams
Open History to see the last commit

webhook.test.ts

95 lines6.4 KB

1import { randomUUID, createPublicKey, verify } from 'node:crypto'
2import type { JsonWebKey } from 'node:crypto'
3import pg from 'pg'
4import { afterAll, expect, test } from 'vitest'
5​
6const env = process.env
7if (!env.TEST_FUNCTION_URL || !env.TEST_FUNCTION_API_KEY || !env.TEST_FUNCTION_MAINTENANCE_KEY || !env.TEST_FUNCTION_SCHEMA
8 || !env.TEST_WEBHOOK_RECEIVER_URL || !env.TEST_WEBHOOK_RECEIVER_KEY || !env.TEST_DATABASE_URL) throw new Error('Deployed Neon source and public HTTPS receiver required')
9if (!/^ds_test_[a-f0-9]{32}$/.test(env.TEST_FUNCTION_SCHEMA) || !new URL(env.TEST_WEBHOOK_RECEIVER_URL).hostname.includes('.compute.')) throw new Error('Webhook qualification requires recorded Neon Functions')
10const pool = new pg.Pool({ connectionString: env.TEST_DATABASE_URL, max: 2 })
11pool.on('error', () => {})
12afterAll(() => pool.end())
13const request = (path: string, method = 'GET', body?: object | string, headers?: Record<string, string>) => fetch(new URL(path, env.TEST_FUNCTION_URL), {
14 method, headers: { Authorization: `Bearer ${env.TEST_FUNCTION_API_KEY}`, 'Content-Type': typeof body === 'object' ? 'application/json' : 'text/plain', ...headers },
15 ...(body !== undefined ? { body: typeof body === 'string' ? body : JSON.stringify(body) } : {}), signal: AbortSignal.timeout(20_000),
16})
17interface Delivery {
18 wake_id: string; raw_body: string; signature: string; attempts: number
19 payload: { subscription_id: string; tenant_id: string; wake_id: string; generation: number; callback_url: string; callback_token: string;
20 streams: { path: string; tail_offset: string }[] }
22async function received(name: string): Promise<Delivery[]> {
23 const url = new URL('deliveries', env.TEST_WEBHOOK_RECEIVER_URL); url.searchParams.set('subscription_id', name)
24 const response = await fetch(url, { headers: { Authorization: env.TEST_WEBHOOK_RECEIVER_KEY! }, signal: AbortSignal.timeout(10_000) })
25 expect(response.status).toBe(200)
26 const deliveries = await response.json() as Delivery[]
27 if (env.GITHUB_ACTIONS === 'true') for (const delivery of deliveries) console.log(`::add-mask::${delivery.payload.callback_token}`)
28 return deliveries
30const maintain = () => request('_maintenance', 'POST', undefined, { 'x-ds-maintenance-key': env.TEST_FUNCTION_MAINTENANCE_KEY! })
31async function setup(mode: string) {
32 const name = `https-${mode}-${randomUUID()}`, path = `webhook/${name}`
33 expect((await request(`v1/stream/${path}`, 'PUT', 'before')).status).toBe(201)
34 const registration = await request(`v1/stream/__ds/subscriptions/${name}`, 'PUT', { type: 'webhook', streams: [path],
35 webhook: { url: new URL(mode, env.TEST_WEBHOOK_RECEIVER_URL).href }, lease_ttl_ms: 30_000 })
36 expect(registration.status).toBe(201)
37 const appended = await request(`v1/stream/${path}`, 'POST', ' new HTTPS data')
38 expect(appended.status).toBe(204)
39 return { name, path, tail: appended.headers.get('Stream-Next-Offset')! }
41async function acknowledged(name: string, tail: string) {
42 const result = await pool.query(`SELECT m.acked_offset FROM "${env.TEST_FUNCTION_SCHEMA}".subscription_members m JOIN "${env.TEST_FUNCTION_SCHEMA}".subscriptions s ON s.id = m.subscription_id WHERE s.tenant_id = 'function-a' AND s.name = $1`, [name])
43 return result.rows[0]?.acked_offset === tail
45​
46test('deployed Function signs real public HTTPS wakes and synchronous done acknowledges their snapshot', async () => {
47 expect((await fetch(new URL('sync', env.TEST_WEBHOOK_RECEIVER_URL), { method: 'POST', body: '{}', signal: AbortSignal.timeout(10_000) })).status).toBe(401)
48 const { name, path, tail } = await setup('sync')
49 try {
50 expect((await maintain()).status).toBe(200)
51 await expect.poll(async () => (await received(name)).length, { timeout: 15_000, interval: 250 }).toBe(1)
52 const [delivery] = await received(name)
53 expect(delivery!.payload.subscription_id).toBe(name)
54 expect(delivery!.payload.tenant_id).toBe('function-a')
55 expect(delivery!.payload.streams[0]!.path).toBe(path)
56 expect(delivery!.payload.streams[0]!.tail_offset).toBe(tail)
57 const fields = Object.fromEntries(delivery!.signature.split(',').map((field) => field.split('=')))
58 const jwks = await (await request('v1/stream/__ds/jwks.json')).json() as { keys: (JsonWebKey & { kid: string })[] }
59 const key = jwks.keys.find((key) => key.kid === fields.kid)!
60 expect(verify(null, Buffer.concat([Buffer.from(`${fields.t}.`), Buffer.from(delivery!.raw_body, 'base64')]), createPublicKey({ key, format: 'jwk' }), Buffer.from(fields.ed25519!, 'base64url'))).toBe(true)
61 await expect.poll(() => acknowledged(name, tail), { timeout: 5000, interval: 100 }).toBe(true)
62 } finally { await request(`v1/stream/__ds/subscriptions/${name}`, 'DELETE') }
63})
64​
65test('public HTTPS asynchronous callback uses its scoped token and fences duplicate completion', async () => {
66 const { name, path, tail } = await setup('async')
67 try {
68 expect((await maintain()).status).toBe(200)
69 await expect.poll(async () => (await received(name)).length, { timeout: 15_000, interval: 250 }).toBe(1)
70 const { payload } = (await received(name))[0]!
71 expect(payload.callback_url).toBe(new URL(`v1/stream/__ds/subscriptions/${name}/callback`, env.TEST_FUNCTION_URL).href)
72 expect((await request(`v1/stream/${path}`, 'GET', undefined, { Authorization: `Bearer ${payload.callback_token}` })).status).toBe(401)
73 expect(await acknowledged(name, tail)).toBe(false)
74 const callback = () => request(`v1/stream/__ds/subscriptions/${name}/callback`, 'POST', {
75 wake_id: payload.wake_id, generation: payload.generation, done: true, acks: [{ stream: path, offset: tail }],
76 }, { Authorization: `Bearer ${payload.callback_token}` })
77 expect((await callback()).status).toBe(200)
78 expect(await acknowledged(name, tail)).toBe(true)
79 expect((await callback()).status).toBe(409)
80 } finally { await request(`v1/stream/__ds/subscriptions/${name}`, 'DELETE') }
81})
82​
83test('public HTTPS 500 responses persist retry state and retry the same wake', async () => {
84 const { name, tail } = await setup('retry')
85 try {
86 await maintain()
87 await expect.poll(async () => {
88 await maintain()
89 return (await received(name))[0]?.attempts ?? 0
90 }, { timeout: 40_000, interval: 1000 }).toBeGreaterThanOrEqual(2)
91 const deliveries = await received(name)
92 expect(deliveries).toHaveLength(1)
93 await expect.poll(() => acknowledged(name, tail), { timeout: 5000, interval: 100 }).toBe(true)
94 } finally { await request(`v1/stream/__ds/subscriptions/${name}`, 'DELETE') }
95}, 55_000)