mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-02 01:28:38 +00:00
* refactor(litellm): migrate private usage in llms Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(litellm): preserve Bedrock batch signature marker Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(litellm): migrate llms private usage symbols Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(litellm): preserve UUID Watsonx project IDs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(litellm): retarget llms mocks to public names Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(litellm): limit llms changes to renames and forwarders Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(litellm): keep GCS mock client patching private Vertex auth methods Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(litellm): assert forwarder arguments and type forwarder signatures Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: mateo <mateo@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
163 lines
6.5 KiB
Python
163 lines
6.5 KiB
Python
import base64
|
|
import json
|
|
import time
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from unittest.mock import MagicMock, mock_open, patch
|
|
|
|
import pytest
|
|
|
|
import litellm
|
|
from litellm.constants import DEFAULT_REQUEST_TIMEOUT_SECONDS, HTTP_HANDLER_CONNECT_TIMEOUT_SECONDS
|
|
from litellm.llms.chatgpt.authenticator import (
|
|
TOKEN_REFRESH_TIMEOUT_SECONDS,
|
|
Authenticator,
|
|
)
|
|
from litellm.llms.chatgpt.common_utils import GetAccessTokenError
|
|
|
|
|
|
def _make_jwt(payload: dict) -> str:
|
|
header = {"alg": "none", "typ": "JWT"}
|
|
|
|
def _b64(obj: dict) -> str:
|
|
raw = json.dumps(obj, separators=(",", ":")).encode("utf-8")
|
|
return base64.urlsafe_b64encode(raw).decode("utf-8").rstrip("=")
|
|
|
|
return f"{_b64(header)}.{_b64(payload)}."
|
|
|
|
|
|
class TestChatGPTAuthenticator:
|
|
@pytest.fixture
|
|
def authenticator(self, tmp_path, monkeypatch):
|
|
monkeypatch.setenv("CHATGPT_TOKEN_DIR", str(tmp_path))
|
|
return Authenticator()
|
|
|
|
def test_get_access_token_from_file(self, authenticator):
|
|
future_time = time.time() + 3600
|
|
auth_data = json.dumps({"access_token": "token-123", "expires_at": future_time})
|
|
|
|
with patch("builtins.open", mock_open(read_data=auth_data)):
|
|
token = authenticator.get_access_token()
|
|
assert token == "token-123"
|
|
|
|
def test_get_access_token_refresh(self, authenticator):
|
|
past_time = time.time() - 10
|
|
auth_data = json.dumps(
|
|
{
|
|
"access_token": "token-old",
|
|
"refresh_token": "refresh-123",
|
|
"expires_at": past_time,
|
|
}
|
|
)
|
|
refreshed = {
|
|
"access_token": "token-new",
|
|
"refresh_token": "refresh-123",
|
|
"id_token": "id-123",
|
|
}
|
|
|
|
with (
|
|
patch("builtins.open", mock_open(read_data=auth_data)),
|
|
patch.object(authenticator, "_refresh_tokens", return_value=refreshed),
|
|
):
|
|
token = authenticator.get_access_token()
|
|
assert token == "token-new"
|
|
|
|
@pytest.mark.parametrize(
|
|
("request_timeout", "expected_read"),
|
|
[
|
|
(DEFAULT_REQUEST_TIMEOUT_SECONDS, TOKEN_REFRESH_TIMEOUT_SECONDS),
|
|
(TOKEN_REFRESH_TIMEOUT_SECONDS * 4.0, TOKEN_REFRESH_TIMEOUT_SECONDS),
|
|
(TOKEN_REFRESH_TIMEOUT_SECONDS / 3.0, TOKEN_REFRESH_TIMEOUT_SECONDS / 3.0),
|
|
],
|
|
)
|
|
def test_refresh_tokens_uses_bounded_timeout(self, authenticator, monkeypatch, request_timeout, expected_read):
|
|
monkeypatch.setattr(litellm, "request_timeout", request_timeout)
|
|
monkeypatch.setattr(litellm, "request_timeout_explicitly_set", False)
|
|
client = MagicMock()
|
|
response = MagicMock()
|
|
response.json.return_value = {
|
|
"access_token": "token-new",
|
|
"id_token": "id-123",
|
|
}
|
|
client.post.return_value = response
|
|
|
|
with patch( # test-quality-ok: requested seam for asserting timeout propagation
|
|
"litellm.llms.chatgpt.authenticator.get_httpx_client", return_value=client
|
|
):
|
|
refreshed = authenticator._refresh_tokens("refresh-123")
|
|
|
|
assert refreshed["access_token"] == "token-new"
|
|
timeout = client.post.call_args.kwargs["timeout"]
|
|
assert timeout.read == expected_read
|
|
assert timeout.connect == HTTP_HANDLER_CONNECT_TIMEOUT_SECONDS
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_access_token_refuses_device_code_login_in_event_loop(self, authenticator):
|
|
with (
|
|
patch("builtins.open", side_effect=FileNotFoundError),
|
|
patch.object(authenticator, "_login_device_code") as mock_login,
|
|
patch.object(authenticator, "_wait_for_access_token") as mock_wait,
|
|
):
|
|
with pytest.raises(GetAccessTokenError) as exc:
|
|
authenticator.get_access_token()
|
|
|
|
assert exc.value.status_code == 401
|
|
assert "event loop" in str(exc.value)
|
|
assert authenticator.auth_file not in str(exc.value)
|
|
mock_login.assert_not_called()
|
|
mock_wait.assert_not_called()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_access_token_refuses_cooldown_wait_in_event_loop(self, authenticator):
|
|
auth_data = json.dumps({"device_code_requested_at": time.time()})
|
|
|
|
with (
|
|
patch("builtins.open", mock_open(read_data=auth_data)),
|
|
patch.object(authenticator, "_login_device_code") as mock_login,
|
|
patch.object(authenticator, "_wait_for_access_token") as mock_wait,
|
|
):
|
|
with pytest.raises(GetAccessTokenError) as exc:
|
|
authenticator.get_access_token()
|
|
|
|
assert exc.value.status_code == 401
|
|
assert "event loop" in str(exc.value)
|
|
assert authenticator.auth_file not in str(exc.value)
|
|
mock_login.assert_not_called()
|
|
mock_wait.assert_not_called()
|
|
|
|
def test_get_access_token_refuses_device_code_login_in_worker_thread(self, authenticator):
|
|
with (
|
|
patch("builtins.open", side_effect=FileNotFoundError),
|
|
patch.object(authenticator, "_login_device_code") as mock_login,
|
|
patch.object(authenticator, "_wait_for_access_token") as mock_wait,
|
|
):
|
|
with ThreadPoolExecutor(max_workers=1) as pool:
|
|
with pytest.raises(GetAccessTokenError) as exc:
|
|
pool.submit(authenticator.get_access_token).result()
|
|
|
|
assert exc.value.status_code == 401
|
|
assert "worker thread" in str(exc.value)
|
|
assert authenticator.auth_file not in str(exc.value)
|
|
mock_login.assert_not_called()
|
|
mock_wait.assert_not_called()
|
|
|
|
def test_get_access_token_device_code_login_without_event_loop(self, authenticator):
|
|
with (
|
|
patch("builtins.open", side_effect=FileNotFoundError),
|
|
patch.object(authenticator, "_login_device_code", return_value={"access_token": "tok"}),
|
|
):
|
|
token = authenticator.get_access_token()
|
|
|
|
assert token == "tok"
|
|
|
|
def test_get_account_id_from_id_token(self, authenticator):
|
|
id_token = _make_jwt({"https://api.openai.com/auth": {"chatgpt_account_id": "acct-123"}})
|
|
auth_data = json.dumps({"id_token": id_token})
|
|
|
|
with (
|
|
patch("builtins.open", mock_open(read_data=auth_data)),
|
|
patch.object(authenticator, "_write_auth_file") as mock_write,
|
|
):
|
|
account_id = authenticator.get_account_id()
|
|
assert account_id == "acct-123"
|
|
mock_write.assert_called_once()
|
|
assert mock_write.call_args[0][0]["account_id"] == "acct-123"
|