|
| 1 | +import json |
| 2 | +import os |
| 3 | +import sys |
| 4 | +from unittest.mock import MagicMock, patch |
| 5 | + |
| 6 | +import pytest |
| 7 | + |
| 8 | +from litellm.proxy._types import UserAPIKeyAuth |
| 9 | +from litellm.proxy.litellm_pre_call_utils import ( |
| 10 | + _get_enforced_params, |
| 11 | + check_if_token_is_service_account, |
| 12 | +) |
| 13 | + |
| 14 | +sys.path.insert( |
| 15 | + 0, os.path.abspath("../../..") |
| 16 | +) # Adds the parent directory to the system path |
| 17 | + |
| 18 | + |
| 19 | +def test_check_if_token_is_service_account(): |
| 20 | + """ |
| 21 | + Test that only keys with `service_account_id` in metadata are considered service accounts |
| 22 | + """ |
| 23 | + # Test case 1: Service account token |
| 24 | + service_account_token = UserAPIKeyAuth( |
| 25 | + api_key="test-key", metadata={"service_account_id": "test-service-account"} |
| 26 | + ) |
| 27 | + assert check_if_token_is_service_account(service_account_token) == True |
| 28 | + |
| 29 | + # Test case 2: Regular user token |
| 30 | + regular_token = UserAPIKeyAuth(api_key="test-key", metadata={}) |
| 31 | + assert check_if_token_is_service_account(regular_token) == False |
| 32 | + |
| 33 | + # Test case 3: Token with other metadata |
| 34 | + other_metadata_token = UserAPIKeyAuth( |
| 35 | + api_key="test-key", metadata={"user_id": "test-user"} |
| 36 | + ) |
| 37 | + assert check_if_token_is_service_account(other_metadata_token) == False |
| 38 | + |
| 39 | + |
| 40 | +def test_get_enforced_params_for_service_account_settings(): |
| 41 | + """ |
| 42 | + Test that service account enforced params are only added to service account keys |
| 43 | + """ |
| 44 | + service_account_token = UserAPIKeyAuth( |
| 45 | + api_key="test-key", metadata={"service_account_id": "test-service-account"} |
| 46 | + ) |
| 47 | + general_settings_with_service = { |
| 48 | + "enforced_params": ["user"], |
| 49 | + "service_account_settings": {"enforced_params": ["metadata.service"]}, |
| 50 | + } |
| 51 | + result = _get_enforced_params( |
| 52 | + general_settings=general_settings_with_service, |
| 53 | + user_api_key_dict=service_account_token, |
| 54 | + ) |
| 55 | + assert result == ["user", "metadata.service"] |
| 56 | + |
| 57 | + regular_token = UserAPIKeyAuth(api_key="test-key", metadata={}) |
| 58 | + result = _get_enforced_params( |
| 59 | + general_settings=general_settings_with_service, user_api_key_dict=regular_token |
| 60 | + ) |
| 61 | + assert result == ["user"] |
0 commit comments