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

rate-limit.worker.test.ts

246 lines6.8 KB

1import { describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3​
4import { getDb } from '../db/index.ts'
5import { createAuth } from '../lib/auth.ts'
6import { registerKeyAgent } from './agents-api.ts'
7import {
8 ANONYMOUS_LIMIT,
9 checkRateLimit,
10 enforceRateLimit,
11} from './rate-limit.ts'
12​
13const NOW = 1_781_150_000
14​
15const makeAuth = () =>
16 createAuth(getDb(env), {
17 secret: 'vitest-only-better-auth-secret-0123456789',
18 baseUrl: 'http://rl.test',
19 })
20​
21const anonRequest = (ip: string) =>
22 new Request('http://rl.test/v1/models', {
23 headers: { 'cf-connecting-ip': ip },
24 })
25​
26describe('checkRateLimit', () => {
27 it('counts within a fixed window and resets in the next one', async () => {
28 const first = await checkRateLimit(env.SCHEMA_CACHE, 'unit-a', 2, 3600, NOW)
29 expect(first).toMatchObject({ allowed: true, remaining: 1 })
30 const second = await checkRateLimit(
31 env.SCHEMA_CACHE,
32 'unit-a',
33 2,
34 3600,
35 NOW + 10,
36 )
37 expect(second).toMatchObject({ allowed: true, remaining: 0 })
38 const third = await checkRateLimit(
39 env.SCHEMA_CACHE,
40 'unit-a',
41 2,
42 3600,
43 NOW + 20,
44 )
45 expect(third.allowed).toBe(false)
46 expect(third.resetAt).toBe(Math.floor(NOW / 3600) * 3600 + 3600)
47​
48 // Next window: fresh counter.
49 const nextWindow = await checkRateLimit(
50 env.SCHEMA_CACHE,
51 'unit-a',
52 2,
53 3600,
54 NOW + 3600,
55 )
56 expect(nextWindow.allowed).toBe(true)
57 })
58})
59​
60describe('enforceRateLimit (acceptance: anonymous window exhaustion)', () => {
61 it('allows 60 anonymous requests then 429s with Retry-After', async () => {
62 const auth = makeAuth()
63 const ip = '198.51.100.7'
64 for (let i = 0; i < ANONYMOUS_LIMIT.limit; i++) {
65 const limited = await enforceRateLimit(
66 auth,
67 getDb(env),
68 env.SCHEMA_CACHE,
69 anonRequest(ip),
70 NOW + i,
71 )
72 expect(limited).toBeNull()
73 }
74​
75 const limited = await enforceRateLimit(
76 auth,
77 getDb(env),
78 env.SCHEMA_CACHE,
79 anonRequest(ip),
80 NOW + 100,
81 )
82 expect(limited).not.toBeNull()
83 expect(limited?.status).toBe(429)
84 expect(Number(limited?.headers.get('retry-after'))).toBeGreaterThan(0)
85 expect(limited?.headers.get('x-ratelimit-remaining')).toBe('0')
86 const body = (await limited?.json()) as { error: { code: string } }
87 expect(body.error.code).toBe('rate_limited')
88​
89 // A different IP is unaffected.
90 const other = await enforceRateLimit(
91 auth,
92 getDb(env),
93 env.SCHEMA_CACHE,
94 anonRequest('198.51.100.8'),
95 NOW + 100,
96 )
97 expect(other).toBeNull()
98 })
99​
100 it('gives authenticated API keys their own (larger) bucket', async () => {
101 const auth = makeAuth()
102 const ip = '198.51.100.9'
103 // Exhaust the anonymous bucket for this IP.
104 for (let i = 0; i < ANONYMOUS_LIMIT.limit; i++) {
105 await enforceRateLimit(
106 auth,
107 getDb(env),
108 env.SCHEMA_CACHE,
109 anonRequest(ip),
110 NOW + i,
111 )
112 }
113 expect(
114 await enforceRateLimit(
115 auth,
116 getDb(env),
117 env.SCHEMA_CACHE,
118 anonRequest(ip),
119 NOW + 99,
120 ),
121 ).not.toBeNull()
122​
123 // Same IP with a valid API key: separate authenticated bucket → allowed.
124 const registered = await registerKeyAgent(auth, getDb(env), {
125 name: 'RL Key Agent',
126 })
127 expect(registered.ok).toBe(true)
128 if (!registered.ok) return
129 const keyed = new Request('http://rl.test/v1/models', {
130 headers: {
131 'cf-connecting-ip': ip,
132 authorization: `Bearer ${registered.result.key}`,
133 },
134 })
135 expect(
136 await enforceRateLimit(
137 auth,
138 getDb(env),
139 env.SCHEMA_CACHE,
140 keyed,
141 NOW + 99,
142 ),
143 ).toBeNull()
144 })
145})
146​
147describe('agent JWT buckets (signature-verified, no jti consumption)', () => {
148 it('forged JWTs never upgrade past the anonymous IP bucket', async () => {
149 const auth = makeAuth()
150 const ip = '198.51.100.20'
151 const forged = (sub: string) => {
152 const b64 = (value: object) =>
153 btoa(JSON.stringify(value))
154 .replace(/\+/g, '-')
155 .replace(/\//g, '_')
156 .replace(/=+$/, '')
157 return `${b64({ alg: 'EdDSA', typ: 'agent+jwt' })}.${b64({ sub })}.AAAA`
158 }
159​
160 // Exhaust the IP window using forged JWTs with ROTATING subs — if
161 // unverified claims granted authenticated buckets, this would never 429.
162 for (let i = 0; i < ANONYMOUS_LIMIT.limit; i++) {
163 const request = new Request('http://rl.test/v1/models', {
164 headers: {
165 'cf-connecting-ip': ip,
166 authorization: `Bearer ${forged(`spoof-${String(i)}`)}`,
167 },
168 })
169 await enforceRateLimit(
170 auth,
171 getDb(env),
172 env.SCHEMA_CACHE,
173 request,
174 NOW + i,
175 )
176 }
177 const final = new Request('http://rl.test/v1/models', {
178 headers: {
179 'cf-connecting-ip': ip,
180 authorization: `Bearer ${forged('spoof-final')}`,
181 },
182 })
183 const limited = await enforceRateLimit(
184 auth,
185 getDb(env),
186 env.SCHEMA_CACHE,
187 final,
188 NOW + 99,
189 )
190 expect(limited?.status).toBe(429)
191 })
192​
193 it('a properly signed agent JWT gets the authenticated bucket', async () => {
194 const { SignJWT, exportJWK, generateKeyPair } = await import('jose')
195 const db = getDb(env)
196 const auth = makeAuth()
197​
198 const keys = await generateKeyPair('Ed25519', { extractable: true })
199 const { agent, agentHost } = await import('../db/schema.ts')
200 await db.insert(agentHost).values({
201 id: 'rl-host',
202 name: 'rl host',
203 status: 'active',
204 createdAt: new Date(NOW * 1000),
205 updatedAt: new Date(NOW * 1000),
206 })
207 await db.insert(agent).values({
208 id: 'rl-agent',
209 name: 'rl agent',
210 mode: 'autonomous',
211 status: 'active',
212 publicKey: JSON.stringify(await exportJWK(keys.publicKey)),
213 hostId: 'rl-host',
214 createdAt: new Date(NOW * 1000),
215 updatedAt: new Date(NOW * 1000),
216 })
217​
218 const jwt = await new SignJWT({ aud: 'http://rl.test/api/auth' })
219 .setProtectedHeader({ alg: 'EdDSA', typ: 'agent+jwt' })
220 .setIssuer('rl-host')
221 .setSubject('rl-agent')
222 .setIssuedAt()
223 .setJti(crypto.randomUUID())
224 .setExpirationTime('2m')
225 .sign(keys.privateKey)
226​
227 const ip = '198.51.100.21'
228 // Exhaust the IP bucket first.
229 for (let i = 0; i < ANONYMOUS_LIMIT.limit; i++) {
230 await enforceRateLimit(
231 auth,
232 db,
233 env.SCHEMA_CACHE,
234 anonRequest(ip),
235 NOW + i,
236 )
237 }
238 // The signed JWT rides its own authenticated bucket → still allowed.
239 const request = new Request('http://rl.test/v1/models', {
240 headers: { 'cf-connecting-ip': ip, authorization: `Bearer ${jwt}` },
241 })
242 expect(
243 await enforceRateLimit(auth, db, env.SCHEMA_CACHE, request),
244 ).toBeNull()
245 })
246})