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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
"""
RBAC tests
"""

import os
import sys
import traceback
import uuid
from datetime import datetime

from dotenv import load_dotenv
from fastapi import Request
from fastapi.routing import APIRoute

load_dotenv()
import io
import os
import time

# this file is to test litellm/proxy

sys.path.insert(
    0, os.path.abspath("../..")
)  # Adds the parent directory to the system path
import asyncio
import logging
from unittest.mock import MagicMock
import pytest

import litellm
from litellm._logging import verbose_proxy_logger
from litellm.proxy.auth.auth_checks import get_user_object
from litellm.proxy.management_endpoints.key_management_endpoints import (
    delete_key_fn,
    generate_key_fn,
    generate_key_helper_fn,
    info_key_fn,
    regenerate_key_fn,
    update_key_fn,
)
from litellm.proxy.management_endpoints.internal_user_endpoints import new_user
from litellm.proxy.management_endpoints.organization_endpoints import (
    new_organization,
    organization_member_add,
)

from litellm.proxy.management_endpoints.team_endpoints import (
    new_team,
    team_info,
    update_team,
)
from litellm.proxy.proxy_server import (
    LitellmUserRoles,
    audio_transcriptions,
    chat_completion,
    completion,
    embeddings,
    model_list,
    moderations,
    user_api_key_auth,
)
from litellm.proxy.management_endpoints.customer_endpoints import (
    new_end_user,
)
from litellm.proxy.spend_tracking.spend_management_endpoints import (
    global_spend,
    global_spend_logs,
    global_spend_models,
    global_spend_keys,
    spend_key_fn,
    spend_user_fn,
    view_spend_logs,
)
from starlette.datastructures import URL

from litellm.proxy.utils import PrismaClient, ProxyLogging, hash_token, update_spend

verbose_proxy_logger.setLevel(level=logging.DEBUG)

from starlette.datastructures import URL

from litellm.caching.caching import DualCache
from litellm.proxy._types import *

proxy_logging_obj = ProxyLogging(user_api_key_cache=DualCache())


@pytest.fixture
def prisma_client():
    from litellm.proxy.proxy_cli import append_query_params

    ### add connection pool + pool timeout args
    params = {"connection_limit": 100, "pool_timeout": 60}
    database_url = os.getenv("DATABASE_URL")
    modified_url = append_query_params(database_url, params)
    os.environ["DATABASE_URL"] = modified_url

    # Assuming PrismaClient is a class that needs to be instantiated
    prisma_client = PrismaClient(
        database_url=os.environ["DATABASE_URL"], proxy_logging_obj=proxy_logging_obj
    )

    # Reset litellm.proxy.proxy_server.prisma_client to None
    litellm.proxy.proxy_server.litellm_proxy_budget_name = (
        f"litellm-proxy-budget-{time.time()}"
    )
    litellm.proxy.proxy_server.user_custom_key_generate = None

    return prisma_client


"""
RBAC Tests

1. Add a user to an organization
    - test 1 - if organization_id does exist expect to create a new user and user, organization relation

2. org admin creates team in his org → success 

3. org admin adds new internal user to his org → success 

4. org admin creates team and internal user not in his org → fail both
"""


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "user_role",
    [
        LitellmUserRoles.ORG_ADMIN,
        LitellmUserRoles.INTERNAL_USER,
        LitellmUserRoles.INTERNAL_USER_VIEW_ONLY,
    ],
)
async def test_create_new_user_in_organization(prisma_client, user_role):
    """

    Add a member to an organization and assert the user object is created with the correct organization memberships / roles
    """
    master_key = "sk-1234"
    setattr(litellm.proxy.proxy_server, "prisma_client", prisma_client)
    setattr(litellm.proxy.proxy_server, "master_key", master_key)
    setattr(litellm.proxy.proxy_server, "llm_router", MagicMock())

    await litellm.proxy.proxy_server.prisma_client.connect()

    created_user_id = f"new-user-{uuid.uuid4()}"

    response = await new_organization(
        data=NewOrganizationRequest(
            organization_alias=f"new-org-{uuid.uuid4()}",
        ),
        user_api_key_dict=UserAPIKeyAuth(
            user_id=created_user_id,
            user_role=LitellmUserRoles.PROXY_ADMIN,
        ),
    )

    org_id = response.organization_id

    response = await organization_member_add(
        data=OrganizationMemberAddRequest(
            organization_id=org_id,
            member=OrgMember(role=user_role, user_id=created_user_id),
        ),
        http_request=None,
    )

    print("new user response", response)

    # call get_user_object

    user_object = await get_user_object(
        user_id=created_user_id,
        prisma_client=prisma_client,
        user_api_key_cache=DualCache(),
        user_id_upsert=False,
    )

    print("user object", user_object)

    assert user_object.organization_memberships is not None

    _membership = user_object.organization_memberships[0]

    assert _membership.user_id == created_user_id
    assert _membership.organization_id == org_id

    if user_role != None:
        assert _membership.user_role == user_role
    else:
        assert _membership.user_role == LitellmUserRoles.INTERNAL_USER_VIEW_ONLY


@pytest.mark.asyncio
async def test_org_admin_create_team_permissions(prisma_client):
    """
    Create a new org admin

    org admin creates a new team in their org -> success
    """
    import json

    master_key = "sk-1234"
    setattr(litellm.proxy.proxy_server, "prisma_client", prisma_client)
    setattr(litellm.proxy.proxy_server, "master_key", master_key)
    setattr(litellm.proxy.proxy_server, "llm_router", MagicMock())

    await litellm.proxy.proxy_server.prisma_client.connect()

    response = await new_organization(
        data=NewOrganizationRequest(
            organization_alias=f"new-org-{uuid.uuid4()}",
        ),
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
        ),
    )

    org_id = response.organization_id
    created_user_id = f"new-user-{uuid.uuid4()}"
    response = await organization_member_add(
        data=OrganizationMemberAddRequest(
            organization_id=org_id,
            member=OrgMember(role=LitellmUserRoles.ORG_ADMIN, user_id=created_user_id),
        ),
        http_request=None,
    )

    # create key with the response["user_id"]
    # proxy admin will generate key for org admin
    _new_key = await generate_key_fn(
        data=GenerateKeyRequest(user_id=created_user_id),
        user_api_key_dict=UserAPIKeyAuth(user_id=created_user_id),
    )

    new_key = _new_key.key

    print("user api key auth response", response)

    # Create /team/new request -> expect auth to pass
    request = Request(scope={"type": "http"})
    request._url = URL(url="/team/new")

    async def return_body():
        body = {"organization_id": org_id}
        return bytes(json.dumps(body), "utf-8")

    request.body = return_body
    response = await user_api_key_auth(request=request, api_key="Bearer " + new_key)

    # after auth - actually create team now
    response = await new_team(
        data=NewTeamRequest(
            organization_id=org_id,
        ),
        http_request=request,
        user_api_key_dict=UserAPIKeyAuth(
            user_id=response.user_id,
        ),
    )

    print("response from new team")


@pytest.mark.asyncio
async def test_org_admin_create_user_permissions(prisma_client):
    """
    1. Create a new org admin

    2. org admin adds a new member to their org -> success (using using /organization/member_add)

    """
    import json

    master_key = "sk-1234"
    setattr(litellm.proxy.proxy_server, "prisma_client", prisma_client)
    setattr(litellm.proxy.proxy_server, "master_key", master_key)
    setattr(litellm.proxy.proxy_server, "llm_router", MagicMock())

    await litellm.proxy.proxy_server.prisma_client.connect()

    # create new org
    response = await new_organization(
        data=NewOrganizationRequest(
            organization_alias=f"new-org-{uuid.uuid4()}",
        ),
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
        ),
    )
    # Create Org Admin
    org_id = response.organization_id
    created_user_id = f"new-user-{uuid.uuid4()}"
    response = await organization_member_add(
        data=OrganizationMemberAddRequest(
            organization_id=org_id,
            member=OrgMember(role=LitellmUserRoles.ORG_ADMIN, user_id=created_user_id),
        ),
        http_request=None,
    )

    # create key with for Org Admin
    _new_key = await generate_key_fn(
        data=GenerateKeyRequest(user_id=created_user_id),
        user_api_key_dict=UserAPIKeyAuth(user_id=created_user_id),
    )

    new_key = _new_key.key

    print("user api key auth response", response)

    # Create /organization/member_add request -> expect auth to pass
    request = Request(scope={"type": "http"})
    request._url = URL(url="/organization/member_add")

    async def return_body():
        body = {"organization_id": org_id}
        return bytes(json.dumps(body), "utf-8")

    request.body = return_body
    response = await user_api_key_auth(request=request, api_key="Bearer " + new_key)

    # after auth - actually actually add new user to organization
    new_internal_user_for_org = f"new-org-user-{uuid.uuid4()}"
    response = await organization_member_add(
        data=OrganizationMemberAddRequest(
            organization_id=org_id,
            member=OrgMember(
                role=LitellmUserRoles.INTERNAL_USER, user_id=new_internal_user_for_org
            ),
        ),
        http_request=request,
    )

    print("response from new team")


@pytest.mark.asyncio
async def test_org_admin_create_user_team_wrong_org_permissions(prisma_client):
    """
    Create a new org admin

    org admin creates a new user and new team in orgs they are not part of -> expect error
    """
    import json

    master_key = "sk-1234"
    setattr(litellm.proxy.proxy_server, "prisma_client", prisma_client)
    setattr(litellm.proxy.proxy_server, "master_key", master_key)
    setattr(litellm.proxy.proxy_server, "llm_router", MagicMock())

    await litellm.proxy.proxy_server.prisma_client.connect()
    created_user_id = f"new-user-{uuid.uuid4()}"
    response = await new_organization(
        data=NewOrganizationRequest(
            organization_alias=f"new-org-{uuid.uuid4()}",
        ),
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
        ),
    )

    response2 = await new_organization(
        data=NewOrganizationRequest(
            organization_alias=f"new-org-{uuid.uuid4()}",
        ),
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
        ),
    )

    org1_id = response.organization_id  # has an admin

    org2_id = response2.organization_id  # does not have an org admin

    # Create Org Admin for Org1
    created_user_id = f"new-user-{uuid.uuid4()}"
    response = await organization_member_add(
        data=OrganizationMemberAddRequest(
            organization_id=org1_id,
            member=OrgMember(role=LitellmUserRoles.ORG_ADMIN, user_id=created_user_id),
        ),
        http_request=None,
    )

    _new_key = await generate_key_fn(
        data=GenerateKeyRequest(
            user_id=created_user_id,
        ),
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.ORG_ADMIN,
            user_id=created_user_id,
        ),
    )

    new_key = _new_key.key

    print("user api key auth response", response)

    # Add a new request in organization=org_without_admins -> expect fail (organization/member_add)
    request = Request(scope={"type": "http"})
    request._url = URL(url="/organization/member_add")

    async def return_body():
        body = {"organization_id": org2_id}
        return bytes(json.dumps(body), "utf-8")

    request.body = return_body

    try:
        response = await user_api_key_auth(request=request, api_key="Bearer " + new_key)
        pytest.fail(
            f"This should have failed!. creating a user in an org without admins"
        )
    except Exception as e:
        print("got exception", e)
        print("exception.message", e.message)
        assert (
            "You do not have a role within the selected organization. Passed organization_id"
            in e.message
        )

    # Create /team/new request in organization=org_without_admins -> expect fail
    request = Request(scope={"type": "http"})
    request._url = URL(url="/team/new")

    async def return_body():
        body = {"organization_id": org2_id}
        return bytes(json.dumps(body), "utf-8")

    request.body = return_body

    try:
        response = await user_api_key_auth(request=request, api_key="Bearer " + new_key)
        pytest.fail(
            f"This should have failed!. Org Admin creating a team in an org where they are not an admin"
        )
    except Exception as e:
        print("got exception", e)
        print("exception.message", e.message)
        assert (
            "You do not have the required role to call" in e.message
            and org2_id in e.message
        )


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "route, user_role, expected_result",
    [
        # Proxy Admin checks
        ("/global/spend/logs", LitellmUserRoles.PROXY_ADMIN, True),
        ("/key/delete", LitellmUserRoles.PROXY_ADMIN, True),
        ("/key/generate", LitellmUserRoles.PROXY_ADMIN, True),
        ("/key/regenerate", LitellmUserRoles.PROXY_ADMIN, True),
        # # Internal User checks - allowed routes
        ("/global/spend/logs", LitellmUserRoles.INTERNAL_USER, True),
        ("/key/delete", LitellmUserRoles.INTERNAL_USER, True),
        ("/key/generate", LitellmUserRoles.INTERNAL_USER, True),
        ("/key/82akk800000000jjsk/regenerate", LitellmUserRoles.INTERNAL_USER, True),
        # Internal User Viewer
        ("/key/generate", LitellmUserRoles.INTERNAL_USER_VIEW_ONLY, False),
        (
            "/key/82akk800000000jjsk/regenerate",
            LitellmUserRoles.INTERNAL_USER_VIEW_ONLY,
            False,
        ),
        ("/key/delete", LitellmUserRoles.INTERNAL_USER_VIEW_ONLY, False),
        ("/team/new", LitellmUserRoles.INTERNAL_USER_VIEW_ONLY, False),
        ("/team/delete", LitellmUserRoles.INTERNAL_USER_VIEW_ONLY, False),
        ("/team/update", LitellmUserRoles.INTERNAL_USER_VIEW_ONLY, False),
        # Proxy Admin Viewer
        ("/global/spend/logs", LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY, True),
        ("/key/delete", LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY, False),
        ("/key/generate", LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY, False),
        (
            "/key/82akk800000000jjsk/regenerate",
            LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,
            False,
        ),
        ("/team/new", LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY, False),
        ("/team/delete", LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY, False),
        ("/team/update", LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY, False),
        # Internal User checks - disallowed routes
        ("/organization/member_add", LitellmUserRoles.INTERNAL_USER, False),
    ],
)
async def test_user_role_permissions(prisma_client, route, user_role, expected_result):
    """Test user role based permissions for different routes"""
    try:
        # Setup
        setattr(litellm.proxy.proxy_server, "prisma_client", prisma_client)
        setattr(litellm.proxy.proxy_server, "master_key", "sk-1234")
        await litellm.proxy.proxy_server.prisma_client.connect()

        # Admin - admin creates a new user
        user_api_key_dict = UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-1234",
            user_id="1234",
        )

        request = NewUserRequest(user_role=user_role)
        new_user_response = await new_user(request, user_api_key_dict=user_api_key_dict)
        user_id = new_user_response.user_id

        # Generate key for new user with team_id="litellm-dashboard"
        key_response = await generate_key_fn(
            data=GenerateKeyRequest(user_id=user_id, team_id="litellm-dashboard"),
            user_api_key_dict=user_api_key_dict,
        )
        generated_key = key_response.key
        bearer_token = "Bearer " + generated_key

        # Create request with route
        request = Request(scope={"type": "http"})
        request._url = URL(url=route)

        # Test authorization
        if expected_result is True:
            # Should pass without error
            result = await user_api_key_auth(request=request, api_key=bearer_token)
            print(f"Auth passed as expected for {route} with role {user_role}")
        else:
            # Should raise an error
            with pytest.raises(Exception) as exc_info:
                await user_api_key_auth(request=request, api_key=bearer_token)
            print(f"Auth failed as expected for {route} with role {user_role}")
            print(f"Error message: {str(exc_info.value)}")

    except Exception as e:
        if expected_result:
            pytest.fail(f"Expected success but got exception: {str(e)}")
        else:
            print(f"Got expected exception: {str(e)}")