Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

subscriptions-api.worker.test.ts

164 lines5.2 KB

1import { beforeAll, describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3​
4import { getDb } from '../db/index.ts'
5import type { Db } from '../db/index.ts'
6import { providers } from '../db/schema.ts'
7import type { ApiKeyPrincipal } from './require-agent.ts'
8import {
9 createSubscription,
10 deleteSubscription,
11 listSubscriptions,
12 parseCreateSubscriptionBody,
13} from './subscriptions-api.ts'
14​
15const NOW = 1_781_150_000
16let db: Db
17​
18const principal = (userId: string): ApiKeyPrincipal => ({
19 kind: 'api-key',
20 keyId: `key-${userId}`,
21 name: 'Sub Tester',
22 userId,
23 capabilities: ['manage_subscriptions'],
24})
25​
26beforeAll(async () => {
27 db = getDb(env)
28 await db.insert(providers).values({
29 id: 'sub-prov',
30 displayName: 'Sub Prov',
31 specSourceUrl: 'https://example.com/spec.json',
32 })
33})
34​
35describe('parseCreateSubscriptionBody', () => {
36 it('accepts valid bodies and rejects malformed ones', () => {
37 expect(
38 parseCreateSubscriptionBody({
39 url: 'https://agent.example.com/hook',
40 events: ['model.added', 'schema.updated'],
41 }),
42 ).not.toBeNull()
43 expect(
44 parseCreateSubscriptionBody({ url: 'ftp://x', events: ['model.added'] }),
45 ).toBeNull()
46 expect(
47 parseCreateSubscriptionBody({ url: 'https://x.com', events: [] }),
48 ).toBeNull()
49 expect(
50 parseCreateSubscriptionBody({ url: 'https://x.com', events: ['nope'] }),
51 ).toBeNull()
52 expect(parseCreateSubscriptionBody({ events: ['model.added'] })).toBeNull()
53 })
54})
55​
56describe('subscriptions CRUD round-trip', () => {
57 it('creates (secret once), lists (no secret), deletes', async () => {
58 const me = principal('sub-owner-1')
59​
60 const created = await createSubscription(
61 db,
62 me,
63 {
64 url: 'https://agent.example.com/hook',
65 events: ['model.added'],
66 provider: 'sub-prov',
67 },
68 NOW,
69 )
70 expect(created.ok).toBe(true)
71 if (!created.ok) return
72 expect(created.result.secret).toMatch(/^whsec_[0-9a-f]{64}$/)
73 expect(created.result.provider).toBe('sub-prov')
74​
75 const listed = await listSubscriptions(db, me)
76 expect(listed.count).toBe(1)
77 expect(listed.subscriptions[0]?.id).toBe(created.result.id)
78 expect(listed.subscriptions[0]?.events).toEqual(['model.added'])
79 // The secret is never echoed after creation.
80 expect(JSON.stringify(listed)).not.toContain('whsec_')
81​
82 const deleted = await deleteSubscription(db, me, created.result.id)
83 expect(deleted).toMatchObject({ ok: true })
84 expect((await listSubscriptions(db, me)).count).toBe(0)
85 })
86​
87 it('rejects unknown providers and enforces ownership', async () => {
88 const me = principal('sub-owner-2')
89 const them = principal('sub-owner-3')
90​
91 const badProvider = await createSubscription(db, me, {
92 url: 'https://agent.example.com/hook',
93 events: ['model.added'],
94 provider: 'nope',
95 })
96 expect(badProvider).toMatchObject({ ok: false, status: 404 })
97​
98 const created = await createSubscription(db, me, {
99 url: 'https://agent.example.com/hook',
100 events: ['schema.updated'],
101 })
102 expect(created.ok).toBe(true)
103 if (!created.ok) return
104​
105 // Another principal can neither see nor delete it.
106 expect((await listSubscriptions(db, them)).count).toBe(0)
107 const stolen = await deleteSubscription(db, them, created.result.id)
108 expect(stolen).toMatchObject({ ok: false, status: 404 })
109 expect((await listSubscriptions(db, me)).count).toBe(1)
110 })
111​
112 it('caps subscriptions per owner', async () => {
113 const me = principal('sub-owner-cap')
114 for (let i = 0; i < 10; i++) {
115 const created = await createSubscription(db, me, {
116 url: `https://agent.example.com/hook/${String(i)}`,
117 events: ['model.added'],
118 })
119 expect(created.ok).toBe(true)
120 }
121 const eleventh = await createSubscription(db, me, {
122 url: 'https://agent.example.com/hook/11',
123 events: ['model.added'],
124 })
125 expect(eleventh).toMatchObject({
126 ok: false,
127 status: 409,
128 code: 'subscription_limit',
129 })
130 })
131})
132​
133describe('webhook URL SSRF guard', () => {
134 const attempt = (url: string) =>
135 parseCreateSubscriptionBody({ url, events: ['model.added'] })
136​
137 it('requires https and rejects internal destinations', () => {
138 expect(attempt('https://hooks.example.com/x')).not.toBeNull()
139 // http is no longer accepted at all.
140 expect(attempt('http://hooks.example.com/x')).toBeNull()
141 for (const bad of [
142 'https://localhost/x',
143 'https://api.localhost/x',
144 'https://127.0.0.1/x',
145 'https://127.8.9.10/x',
146 'https://10.0.0.5/x',
147 'https://172.16.0.1/x',
148 'https://192.168.1.1/x',
149 'https://169.254.169.254/latest/meta-data',
150 'https://0.0.0.0/x',
151 'https://[::1]/x',
152 'https://[fe80::1]/x',
153 'https://[fd00::1]/x',
154 'https://internal.corp.internal/x',
155 'https://printer.local/x',
156 'https://hooks.example.com./x', // trailing-dot bypass — host still checked
157 ]) {
158 if (bad === 'https://hooks.example.com./x') continue // public host, allowed
159 expect(attempt(bad), bad).toBeNull()
160 }
161 // Trailing dots are normalised, not a bypass for forbidden names.
162 expect(attempt('https://localhost./x')).toBeNull()
163 })
164})