-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_users.py
456 lines (388 loc) · 14.1 KB
/
test_users.py
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# What this tests ?
## Tests /user endpoints.
import pytest
import asyncio
import aiohttp
import time
from openai import AsyncOpenAI
from test_team import list_teams
from typing import Optional
from test_keys import generate_key
from fastapi import HTTPException
async def new_user(
session, i, user_id=None, budget=None, budget_duration=None, models=None
):
url = "http://0.0.0.0:4000/user/new"
headers = {"Authorization": "Bearer sk-1234", "Content-Type": "application/json"}
data = {
"models": models or ["azure-models"],
"aliases": {"mistral-7b": "gpt-3.5-turbo"},
"duration": None,
"max_budget": budget,
"budget_duration": budget_duration,
}
if user_id is not None:
data["user_id"] = user_id
async with session.post(url, headers=headers, json=data) as response:
status = response.status
response_text = await response.text()
print(f"Response {i} (Status code: {status}):")
print(response_text)
print()
if status != 200:
raise Exception(f"Request {i} did not return a 200 status code: {status}")
return await response.json()
async def generate_key(
session,
i,
budget=None,
budget_duration=None,
models=["azure-models", "gpt-4", "dall-e-3"],
max_parallel_requests: Optional[int] = None,
user_id: Optional[str] = None,
team_id: Optional[str] = None,
metadata: Optional[dict] = None,
calling_key="sk-1234",
):
url = "http://0.0.0.0:4000/key/generate"
headers = {
"Authorization": f"Bearer {calling_key}",
"Content-Type": "application/json",
}
data = {
"models": models,
"aliases": {"mistral-7b": "gpt-3.5-turbo"},
"duration": None,
"max_budget": budget,
"budget_duration": budget_duration,
"max_parallel_requests": max_parallel_requests,
"user_id": user_id,
"team_id": team_id,
"metadata": metadata,
}
print(f"data: {data}")
async with session.post(url, headers=headers, json=data) as response:
status = response.status
response_text = await response.text()
print(f"Response {i} (Status code: {status}):")
print(response_text)
print()
if status != 200:
raise Exception(f"Request {i} did not return a 200 status code: {status}")
return await response.json()
@pytest.mark.asyncio
async def test_user_new():
"""
Make 20 parallel calls to /user/new. Assert all worked.
"""
async with aiohttp.ClientSession() as session:
tasks = [new_user(session, i) for i in range(1, 11)]
await asyncio.gather(*tasks)
async def get_user_info(session, get_user, call_user, view_all: Optional[bool] = None):
"""
Make sure only models user has access to are returned
"""
if view_all is True:
url = "http://0.0.0.0:4000/user/info"
else:
url = f"http://0.0.0.0:4000/user/info?user_id={get_user}"
headers = {
"Authorization": f"Bearer {call_user}",
"Content-Type": "application/json",
}
async with session.get(url, headers=headers) as response:
status = response.status
response_text = await response.text()
print(response_text)
print()
if status != 200:
if call_user != get_user:
return status
else:
print(f"call_user: {call_user}; get_user: {get_user}")
raise Exception(f"Request did not return a 200 status code: {status}")
return await response.json()
@pytest.mark.asyncio
async def test_user_info():
"""
Get user info
- as admin
- as user themself
- as random
"""
get_user = f"krrish_{time.time()}@berri.ai"
async with aiohttp.ClientSession() as session:
key_gen = await new_user(session, 0, user_id=get_user)
key = key_gen["key"]
## as admin ##
resp = await get_user_info(
session=session, get_user=get_user, call_user="sk-1234"
)
assert isinstance(resp["user_info"], dict)
assert len(resp["user_info"]) > 0
## as user themself ##
resp = await get_user_info(session=session, get_user=get_user, call_user=key)
assert isinstance(resp["user_info"], dict)
assert len(resp["user_info"]) > 0
# as random user #
key_gen = await new_user(session=session, i=0)
random_key = key_gen["key"]
status = await get_user_info(
session=session, get_user=get_user, call_user=random_key
)
assert status == 403
@pytest.mark.asyncio
async def test_user_update():
"""
Create user
Update user access to new model
Make chat completion call
"""
pass
@pytest.mark.skip(reason="Frequent check on ci/cd leads to read timeout issue.")
@pytest.mark.asyncio
async def test_users_budgets_reset():
"""
- Create key with budget and 5s duration
- Get 'reset_at' value
- wait 5s
- Check if value updated
"""
get_user = f"krrish_{time.time()}@berri.ai"
async with aiohttp.ClientSession() as session:
key_gen = await new_user(
session, 0, user_id=get_user, budget=10, budget_duration="5s"
)
key = key_gen["key"]
user_info = await get_user_info(
session=session, get_user=get_user, call_user=key
)
reset_at_init_value = user_info["user_info"]["budget_reset_at"]
i = 0
reset_at_new_value = None
while i < 3:
await asyncio.sleep(70)
user_info = await get_user_info(
session=session, get_user=get_user, call_user=key
)
reset_at_new_value = user_info["user_info"]["budget_reset_at"]
try:
assert reset_at_init_value != reset_at_new_value
break
except Exception:
i + 1
assert reset_at_init_value != reset_at_new_value
async def chat_completion(session, key, model="gpt-4"):
client = AsyncOpenAI(api_key=key, base_url="http://0.0.0.0:4000")
messages = [
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": f"Hello! {time.time()}"},
]
data = {
"model": model,
"messages": messages,
}
response = await client.chat.completions.create(**data)
async def chat_completion_streaming(session, key, model="gpt-4"):
client = AsyncOpenAI(api_key=key, base_url="http://0.0.0.0:4000")
messages = [
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": f"Hello! {time.time()}"},
]
data = {"model": model, "messages": messages, "stream": True}
response = await client.chat.completions.create(**data)
async for chunk in response:
continue
@pytest.mark.skip(reason="Global proxy now tracked via `/global/spend/logs`")
@pytest.mark.asyncio
async def test_global_proxy_budget_update():
"""
- Get proxy current spend
- Make chat completion call (normal)
- Assert spend increased
- Make chat completion call (streaming)
- Assert spend increased
"""
get_user = f"litellm-proxy-budget"
async with aiohttp.ClientSession() as session:
user_info = await get_user_info(
session=session, get_user=get_user, call_user="sk-1234"
)
original_spend = user_info["user_info"]["spend"]
await chat_completion(session=session, key="sk-1234")
await asyncio.sleep(5) # let db update
user_info = await get_user_info(
session=session, get_user=get_user, call_user="sk-1234"
)
new_spend = user_info["user_info"]["spend"]
print(f"new_spend: {new_spend}; original_spend: {original_spend}")
assert new_spend > original_spend
await chat_completion_streaming(session=session, key="sk-1234")
await asyncio.sleep(5) # let db update
user_info = await get_user_info(
session=session, get_user=get_user, call_user="sk-1234"
)
new_new_spend = user_info["user_info"]["spend"]
print(f"new_spend: {new_spend}; original_spend: {original_spend}")
assert new_new_spend > new_spend
@pytest.mark.asyncio
async def test_user_model_access():
"""
- Create user with model access
- Create key with user
- Call model that user has access to -> should work
- Call wildcard model that user has access to -> should work
- Call model that user does not have access to -> should fail
- Call wildcard model that user does not have access to -> should fail
"""
import openai
async with aiohttp.ClientSession() as session:
get_user = f"krrish_{time.time()}@berri.ai"
await new_user(
session=session,
i=0,
user_id=get_user,
models=["good-model", "anthropic/*"],
)
result = await generate_key(
session=session,
i=0,
user_id=get_user,
models=[], # assign no models. Allow inheritance from user
)
key = result["key"]
await chat_completion(
session=session,
key=key,
model="anthropic/claude-3-5-haiku-20241022",
)
await chat_completion(
session=session,
key=key,
model="good-model",
)
with pytest.raises(openai.AuthenticationError):
await chat_completion(
session=session,
key=key,
model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0",
)
with pytest.raises(openai.AuthenticationError):
await chat_completion(
session=session,
key=key,
model="groq/claude-3-5-haiku-20241022",
)
import json
import uuid
import pytest
import aiohttp
from typing import Dict, Tuple
async def setup_test_users(session: aiohttp.ClientSession) -> Tuple[Dict, Dict]:
"""
Create two test users and an additional key for the first user.
Returns tuple of (user1_data, user2_data) where each contains user info and keys.
"""
# Create two test users
user1 = await new_user(
session=session,
i=0,
budget=100,
budget_duration="30d",
models=["anthropic.claude-3-5-sonnet-20240620-v1:0"],
)
user2 = await new_user(
session=session,
i=1,
budget=100,
budget_duration="30d",
models=["anthropic.claude-3-5-sonnet-20240620-v1:0"],
)
print("\nCreated two test users:")
print(f"User 1 ID: {user1['user_id']}")
print(f"User 2 ID: {user2['user_id']}")
# Create an additional key for user1
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {user1['key']}",
}
key_payload = {
"user_id": user1["user_id"],
"duration": "7d",
"key_alias": f"test_key_{uuid.uuid4()}",
"models": ["anthropic.claude-3-5-sonnet-20240620-v1:0"],
}
print("\nGenerating additional key for user1...")
key_response = await session.post(
f"http://0.0.0.0:4000/key/generate", headers=headers, json=key_payload
)
assert key_response.status == 200, "Failed to generate additional key for user1"
user1_additional_key = await key_response.json()
print(f"\nGenerated key details:")
print(json.dumps(user1_additional_key, indent=2))
# Return both users' data including the additional key
return {
"user_data": user1,
"additional_key": user1_additional_key,
"headers": headers,
}, {
"user_data": user2,
"headers": {
"Content-Type": "application/json",
"Authorization": f"Bearer {user2['key']}",
},
}
async def print_response_details(response: aiohttp.ClientResponse) -> None:
"""Helper function to print response details"""
print("\nResponse Details:")
print(f"Status Code: {response.status}")
print("\nResponse Content:")
try:
formatted_json = json.dumps(await response.json(), indent=2)
print(formatted_json)
except json.JSONDecodeError:
print(await response.text())
@pytest.mark.asyncio
async def test_key_update_user_isolation():
"""Test that a user cannot update a key that belongs to another user"""
async with aiohttp.ClientSession() as session:
user1_data, user2_data = await setup_test_users(session)
# Try to update the key to belong to user2
update_payload = {
"key": user1_data["additional_key"]["key"],
"user_id": user2_data["user_data"][
"user_id"
], # Attempting to change ownership
"metadata": {"purpose": "testing_user_isolation", "environment": "test"},
}
print("\nAttempting to update key ownership to user2...")
update_response = await session.post(
f"http://0.0.0.0:4000/key/update",
headers=user1_data["headers"], # Using user1's headers
json=update_payload,
)
await print_response_details(update_response)
# Verify update attempt was rejected
assert (
update_response.status == 403
), "Request should have been rejected with 403 status code"
@pytest.mark.asyncio
async def test_key_delete_user_isolation():
"""Test that a user cannot delete a key that belongs to another user"""
async with aiohttp.ClientSession() as session:
user1_data, user2_data = await setup_test_users(session)
# Try to delete user1's additional key using user2's credentials
delete_payload = {
"keys": [user1_data["additional_key"]["key"]],
}
print("\nAttempting to delete user1's key using user2's credentials...")
delete_response = await session.post(
f"http://0.0.0.0:4000/key/delete",
headers=user2_data["headers"],
json=delete_payload,
)
await print_response_details(delete_response)
# Verify delete attempt was rejected
assert (
delete_response.status == 403
), "Request should have been rejected with 403 status code"