Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(cli): let lite up trust the key the group already renewed

mateo-berria20cfc5f0e5d
diff --git a/litellm/proxy/client/cli/commands/up.py b/litellm/proxy/client/cli/commands/up.py
index 35ca504c493..80b7a04b75a 100644
--- a/litellm/proxy/client/cli/commands/up.py
+++ b/litellm/proxy/client/cli/commands/up.py
@@ -17,7 +17,7 @@ from pydantic import JsonValue, TypeAdapter, ValidationError
from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh
from .agents import AgentRunError, resolve_api_key, verify_proxy_key
-from .auth import get_stored_api_key, load_token, login
+from .auth import CliContextObj, get_stored_api_key, load_token, login
from .claude_settings import (
BACKUP_PATH,
CLAUDE_SETTINGS_PATH,
@@ -103,21 +103,28 @@ def restore_claude_settings(settings_path: Path | None = None, backup_path: Path
return record
-def _usable_login(base_url: str) -> bool:
- if get_stored_api_key(expected_base_url=base_url) is None:
+def _usable_login(api_key: str | None) -> bool:
+ if api_key is None:
return False
token_data: Final = load_token()
return token_data is not None and is_cli_token_fresh(token_data)
+def _key_resolved_on_the_way_in(ctx_obj: CliContextObj, base_url: str) -> str | None:
+ if ctx_obj.get("api_key_from_token_file"):
+ return ctx_obj.get("api_key")
+ return get_stored_api_key(expected_base_url=base_url)
+
+
def _stored_login_is_pkce() -> bool:
token_data: Final = load_token()
return token_data is not None and "refresh_token" in token_data
def _ensure_fresh_login(ctx: click.Context) -> None:
- base_url: Final = ctx.obj["base_url"].rstrip("/")
- if _usable_login(base_url):
+ ctx_obj: Final[CliContextObj] = ctx.obj
+ base_url: Final = ctx_obj["base_url"].rstrip("/")
+ if _usable_login(_key_resolved_on_the_way_in(ctx_obj, base_url)):
return
pkce: Final = _stored_login_is_pkce()
@@ -130,7 +137,7 @@ def _ensure_fresh_login(ctx: click.Context) -> None:
click.echo("No fresh LiteLLM login found for this proxy; starting login...")
ctx.invoke(login, pkce=pkce)
- if not _usable_login(base_url):
+ if not _usable_login(get_stored_api_key(expected_base_url=base_url)):
raise UpError("Login did not produce a usable token; cannot start `lite up`.")
diff --git a/tests/test_litellm/proxy/client/cli/test_auth_commands.py b/tests/test_litellm/proxy/client/cli/test_auth_commands.py
index 9b7dbbd1fdd..f6123b5c690 100644
--- a/tests/test_litellm/proxy/client/cli/test_auth_commands.py
+++ b/tests/test_litellm/proxy/client/cli/test_auth_commands.py
@@ -1554,6 +1554,27 @@ class TestPkcePrintToken:
assert "Key expired. Run 'lite login --pkce' again." in result.output
save.assert_not_called()
+ def test_print_token_through_the_cli_group_prints_the_key_the_group_renewed(self, monkeypatch):
+ monkeypatch.delenv("LITELLM_PROXY_API_KEY", raising=False)
+ monkeypatch.delenv("LITELLM_PROXY_URL", raising=False)
+
+ class _RefreshingSession(_FakeSession):
+ def __init__(self):
+ super().__init__()
+ self.response = _FakeHttpResponse(200, PKCE_TOKEN_RESPONSE)
+
+ with (
+ patch("litellm.proxy.client.cli.commands.auth.load_token", return_value=_pkce_record()),
+ patch("litellm.proxy.client.cli.commands.auth.save_token") as save,
+ patch("litellm.proxy.client.cli.commands.auth.requests.Session", _RefreshingSession),
+ ):
+ result = self.runner.invoke(cli, ["--base-url", PKCE_BASE_URL, "auth", "print-token"])
+
+ assert result.exit_code == 0, result.output
+ assert result.stdout == "sk-cli-rotated\n"
+ assert sum(len(session.posts) for session in _FakeSession.instances) == 1
+ assert save.call_count == 1
+
def test_print_token_invoked_bare_for_another_server_renews_once(self, monkeypatch, tmp_path):
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("USERPROFILE", str(tmp_path))
diff --git a/tests/test_litellm/proxy/client/cli/test_up_commands.py b/tests/test_litellm/proxy/client/cli/test_up_commands.py
index 6344e4ba154..264de328c37 100644
--- a/tests/test_litellm/proxy/client/cli/test_up_commands.py
+++ b/tests/test_litellm/proxy/client/cli/test_up_commands.py
@@ -221,6 +221,13 @@ def _make_ctx(base_url):
return click.Context(click.Command("test"), obj={"base_url": base_url})
+def _make_group_ctx(base_url, api_key):
+ """The context the `lite` group hands down after it already read the token file once."""
+ return click.Context(
+ click.Command("test"), obj={"base_url": base_url, "api_key": api_key, "api_key_from_token_file": True}
+ )
+
+
def _pkce_record(base_url, seconds_left):
return {
"key": "sk-pkce",
@@ -339,6 +346,45 @@ class TestEnsureFreshLogin:
with pytest.raises(UpError, match="Run `lite login --pkce` first"):
_ensure_fresh_login(_make_ctx("http://proxy-a:4000"))
+ def test_trusts_the_key_the_cli_group_already_resolved_instead_of_reading_the_token_file_again(
+ self, monkeypatch
+ ):
+ """The `lite` group renews a --pkce key on the way in, so a second renewal here would hit
+ the proxy twice and, once the refresh token is burned, print the refusal twice."""
+ store = _FakeTokenStore(monkeypatch, _pkce_record("http://proxy-a:4000", seconds_left=86_400), {})
+ login_calls = _capture_login(monkeypatch)
+
+ _ensure_fresh_login(_make_group_ctx("http://proxy-a:4000", api_key="sk-pkce-renewed-by-the-group"))
+
+ assert login_calls == []
+ assert store.key_requests == []
+
+ def test_fails_non_interactively_without_a_second_renewal_when_the_group_could_not_renew(self, monkeypatch):
+ monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: False)
+ store = _FakeTokenStore(
+ monkeypatch,
+ _pkce_record("http://proxy-a:4000", seconds_left=-10),
+ {"http://proxy-a:4000": "sk-a-second-renewal-would-mint-this"},
+ )
+
+ with pytest.raises(UpError, match="Run `lite login --pkce` first"):
+ _ensure_fresh_login(_make_group_ctx("http://proxy-a:4000", api_key=None))
+
+ assert store.key_requests == []
+
+ def test_re_reads_the_token_file_only_after_the_interactive_login_it_started(self, monkeypatch):
+ monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: True)
+ store = _FakeTokenStore(monkeypatch, _pkce_record("http://proxy-a:4000", seconds_left=-10), {})
+ login_calls = _capture_login(
+ monkeypatch,
+ on_login=lambda: store.log_in(_pkce_record("http://proxy-a:4000", seconds_left=86_400), "sk-pkce-fresh"),
+ )
+
+ _ensure_fresh_login(_make_group_ctx("http://proxy-a:4000", api_key=None))
+
+ assert login_calls == [("http://proxy-a:4000", True)]
+ assert store.key_requests == ["http://proxy-a:4000"]
+
class TestUpCommand:
def setup_method(self):