-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfix_rate_limits.py
More file actions
441 lines (393 loc) · 16 KB
/
Copy pathfix_rate_limits.py
File metadata and controls
441 lines (393 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
import re
# Fix test_routes_auth.py
with open('tests/test_routes_auth.py', 'r') as f:
c = f.read()
# Fix rate limit tests to use 100 instead of 10
c = c.replace(
''' @pytest.mark.asyncio
async def test_create_key_rate_limited(self, client: AsyncClient, auth_headers: dict):
"""Test rate limiting on create key endpoint."""
for i in range(10):
response = await client.post(
"/api/v1/auth/keys",
json={"name": f"Key {i}"},
headers=auth_headers,
)
assert response.status_code == status.HTTP_201_CREATED
response = await client.post(
"/api/v1/auth/keys",
json={"name": "Rate Limited Key"},
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS''',
''' @pytest.mark.asyncio
async def test_create_key_rate_limited(self, client: AsyncClient, auth_headers: dict):
"""Test rate limiting on create key endpoint."""
for i in range(100):
response = await client.post(
"/api/v1/auth/keys",
json={"name": f"Key {i}"},
headers=auth_headers,
)
assert response.status_code == status.HTTP_201_CREATED
response = await client.post(
"/api/v1/auth/keys",
json={"name": "Rate Limited Key"},
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS'''
)
c = c.replace(
''' @pytest.mark.asyncio
async def test_list_keys_rate_limited(self, client: AsyncClient, auth_headers: dict):
"""Test rate limiting on list keys endpoint."""
for i in range(10):
response = await client.get(
"/api/v1/auth/keys",
headers=auth_headers,
)
assert response.status_code == status.HTTP_200_OK
response = await client.get(
"/api/v1/auth/keys",
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS''',
''' @pytest.mark.asyncio
async def test_list_keys_rate_limited(self, client: AsyncClient, auth_headers: dict):
"""Test rate limiting on list keys endpoint."""
for i in range(100):
response = await client.get(
"/api/v1/auth/keys",
headers=auth_headers,
)
assert response.status_code == status.HTTP_200_OK
response = await client.get(
"/api/v1/auth/keys",
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS'''
)
c = c.replace(
''' @pytest.mark.asyncio
async def test_get_key_rate_limited(self, client: AsyncClient, auth_headers: dict, test_api_key):
"""Test rate limiting on get key endpoint."""
for i in range(10):
response = await client.get(
f"/api/v1/auth/keys/{test_api_key.id}",
headers=auth_headers,
)
assert response.status_code == status.HTTP_200_OK
response = await client.get(
f"/api/v1/auth/keys/{test_api_key.id}",
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS''',
''' @pytest.mark.asyncio
async def test_get_key_rate_limited(self, client: AsyncClient, auth_headers: dict, test_api_key):
"""Test rate limiting on get key endpoint."""
for i in range(100):
response = await client.get(
f"/api/v1/auth/keys/{test_api_key.id}",
headers=auth_headers,
)
assert response.status_code == status.HTTP_200_OK
response = await client.get(
f"/api/v1/auth/keys/{test_api_key.id}",
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS'''
)
c = c.replace(
''' @pytest.mark.asyncio
async def test_revoke_key_rate_limited(self, client: AsyncClient, auth_headers: dict, test_api_key, db_session):
"""Test rate limiting on revoke key endpoint."""
from app.models.api_key import APIKey
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
for i in range(10):
key = APIKey(
key_hash=pwd_context.hash(f"di_revoke_{i}"),
name=f"Revoke Key {i}",
rate_limit=100,
is_active=True,
)
db_session.add(key)
await db_session.commit()
# Revoke 10 keys
result = await db_session.execute(
db_session.query(APIKey).where(APIKey.name.like("Revoke Key%")).limit(10)
)
keys = result.scalars().all()
for i, key in enumerate(keys):
response = await client.delete(
f"/api/v1/auth/keys/{key.id}",
headers=auth_headers,
)
assert response.status_code == status.HTTP_204_NO_CONTENT
# Try to revoke another
response = await client.delete(
f"/api/v1/auth/keys/{keys[-1].id}",
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS''',
''' @pytest.mark.asyncio
async def test_revoke_key_rate_limited(self, client: AsyncClient, auth_headers: dict, test_api_key, db_session):
"""Test rate limiting on revoke key endpoint."""
from app.models.api_key import APIKey
from passlib.context import CryptContext
from sqlalchemy import select
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
for i in range(100):
key = APIKey(
key_hash=pwd_context.hash(f"di_revoke_{i}"),
name=f"Revoke Key {i}",
rate_limit=100,
is_active=True,
)
db_session.add(key)
await db_session.commit()
# Revoke 100 keys
result = await db_session.execute(
select(APIKey).where(APIKey.name.like("Revoke Key%")).limit(100)
)
keys = result.scalars().all()
for i, key in enumerate(keys):
response = await client.delete(
f"/api/v1/auth/keys/{key.id}",
headers=auth_headers,
)
assert response.status_code == status.HTTP_204_NO_CONTENT
# Try to revoke another
response = await client.delete(
f"/api/v1/auth/keys/{keys[-1].id}",
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS'''
)
with open('tests/test_routes_auth.py', 'w') as f:
f.write(c)
print('auth done')
# Fix test_routes_query.py
with open('tests/test_routes_query.py', 'r') as f:
c = f.read()
c = c.replace(
''' @pytest.mark.asyncio
async def test_rate_limiting_on_query(self, client: AsyncClient, auth_headers: dict, test_document, test_analysis):
"""Test rate limiting on query endpoints."""
# Make 10 requests (all should succeed with rate_limit=100)
for i in range(10):
response = await client.get(
f"/api/v1/query/documents/{test_document.id}",
headers=auth_headers,
)
assert response.status_code == status.HTTP_200_OK
# 11th request should be rate limited
response = await client.get(
f"/api/v1/query/documents/{test_document.id}",
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS''',
''' @pytest.mark.asyncio
async def test_rate_limiting_on_query(self, client: AsyncClient, auth_headers: dict, test_document, test_analysis):
"""Test rate limiting on query endpoints."""
# Make 100 requests (test_api_key has rate_limit=100)
for i in range(100):
response = await client.get(
f"/api/v1/query/documents/{test_document.id}",
headers=auth_headers,
)
assert response.status_code == status.HTTP_200_OK
# 101st request should be rate limited
response = await client.get(
f"/api/v1/query/documents/{test_document.id}",
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS'''
)
c = c.replace(
''' @pytest.mark.asyncio
async def test_rate_limiting_on_list(self, client: AsyncClient, auth_headers: dict):
"""Test rate limiting on document list endpoint."""
for i in range(10):
response = await client.get(
"/api/v1/query/documents",
headers=auth_headers,
)
assert response.status_code == status.HTTP_200_OK
response = await client.get(
"/api/v1/query/documents",
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS''',
''' @pytest.mark.asyncio
async def test_rate_limiting_on_list(self, client: AsyncClient, auth_headers: dict):
"""Test rate limiting on document list endpoint."""
for i in range(100):
response = await client.get(
"/api/v1/query/documents",
headers=auth_headers,
)
assert response.status_code == status.HTTP_200_OK
response = await client.get(
"/api/v1/query/documents",
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS'''
)
c = c.replace(
''' @pytest.mark.asyncio
async def test_rate_limiting_on_stats(self, client: AsyncClient, auth_headers: dict):
"""Test rate limiting on stats endpoint."""
for i in range(10):
response = await client.get(
"/api/v1/query/stats",
headers=auth_headers,
)
assert response.status_code == status.HTTP_200_OK
response = await client.get(
"/api/v1/query/stats",
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS''',
''' @pytest.mark.asyncio
async def test_rate_limiting_on_stats(self, client: AsyncClient, auth_headers: dict):
"""Test rate limiting on stats endpoint."""
for i in range(100):
response = await client.get(
"/api/v1/query/stats",
headers=auth_headers,
)
assert response.status_code == status.HTTP_200_OK
response = await client.get(
"/api/v1/query/stats",
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS'''
)
with open('tests/test_routes_query.py', 'w') as f:
f.write(c)
print('query done')
# Fix test_routes_process.py
with open('tests/test_routes_process.py', 'r') as f:
c = f.read()
c = c.replace(
''' @pytest.mark.asyncio
async def test_rate_limiting_on_analyze(self, client: AsyncClient, auth_headers: dict, test_api_key, db_session):
"""Test rate limiting on analyze endpoint."""
from app.models.document import Document, DocumentStatus
for i in range(10):
doc = Document(
filename=f"doc{i}.pdf",
file_path=f"/tmp/doc{i}.pdf",
mime_type="application/pdf",
file_size=1024,
status=DocumentStatus.UPLOADED,
api_key_id=test_api_key.id,
)
db_session.add(doc)
await db_session.commit()
for i in range(10):
result = await db_session.execute(
db_session.query(Document).where(Document.filename == f"doc{i}.pdf")
)
doc = result.scalar_one()
response = await client.post(
"/api/v1/process/analyze",
json={"document_id": str(doc.id)},
headers=auth_headers,
)
assert response.status_code in (status.HTTP_202_ACCEPTED, status.HTTP_422_UNPROCESSABLE_ENTITY)
response = await client.post(
"/api/v1/process/analyze",
json={"document_id": str(doc.id)},
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS''',
''' @pytest.mark.asyncio
async def test_rate_limiting_on_analyze(self, client: AsyncClient, auth_headers: dict, test_api_key, db_session):
"""Test rate limiting on analyze endpoint."""
from app.models.document import Document, DocumentStatus
from sqlalchemy import select
for i in range(100):
doc = Document(
filename=f"doc{i}.pdf",
file_path=f"/tmp/doc{i}.pdf",
mime_type="application/pdf",
file_size=1024,
status=DocumentStatus.UPLOADED,
api_key_id=test_api_key.id,
)
db_session.add(doc)
await db_session.commit()
for i in range(100):
result = await db_session.execute(
select(Document).where(Document.filename == f"doc{i}.pdf")
)
doc = result.scalar_one()
response = await client.post(
"/api/v1/process/analyze",
json={"document_id": str(doc.id)},
headers=auth_headers,
)
assert response.status_code in (status.HTTP_202_ACCEPTED, status.HTTP_422_UNPROCESSABLE_ENTITY)
response = await client.post(
"/api/v1/process/analyze",
json={"document_id": str(doc.id)},
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS'''
)
with open('tests/test_routes_process.py', 'w') as f:
f.write(c)
print('process done')
# Fix test_routes_upload.py
with open('tests/test_routes_upload.py', 'r') as f:
c = f.read()
c = c.replace(
''' @pytest.mark.asyncio
async def test_rate_limiting(self, client: AsyncClient, auth_headers: dict):
"""Test rate limiting on upload endpoint."""
for i in range(10):
file_content = b"%PDF-1.4\n%Test"
files = {"file": (f"test{i}.pdf", BytesIO(file_content), "application/pdf")}
response = await client.post(
"/api/v1/documents/upload",
files=files,
headers=auth_headers,
)
assert response.status_code == status.HTTP_201_CREATED
# 11th request should be rate limited
file_content = b"%PDF-1.4\n%Test"
files = {"file": ("test_rate_limit.pdf", BytesIO(file_content), "application/pdf")}
response = await client.post(
"/api/v1/documents/upload",
files=files,
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS''',
''' @pytest.mark.asyncio
async def test_rate_limiting(self, client: AsyncClient, auth_headers: dict):
"""Test rate limiting on upload endpoint."""
for i in range(100):
file_content = b"%PDF-1.4\n%Test"
files = {"file": (f"test{i}.pdf", BytesIO(file_content), "application/pdf")}
response = await client.post(
"/api/v1/documents/upload",
files=files,
headers=auth_headers,
)
assert response.status_code == status.HTTP_201_CREATED
# 101st request should be rate limited
file_content = b"%PDF-1.4\n%Test"
files = {"file": ("test_rate_limit.pdf", BytesIO(file_content), "application/pdf")}
response = await client.post(
"/api/v1/documents/upload",
files=files,
headers=auth_headers,
)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS'''
)
with open('tests/test_routes_upload.py', 'w') as f:
f.write(c)
print('upload done')
print('All rate limit test fixes applied!')