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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(cli): renew the key once per lite auth print-token run
mateo-berri36e9e813a733
diff --git a/litellm/proxy/client/cli/commands/auth.py b/litellm/proxy/client/cli/commands/auth.pyindex d776a2c9418..4eb23a547b6 100644--- a/litellm/proxy/client/cli/commands/auth.py+++ b/litellm/proxy/client/cli/commands/auth.py@@ -61,6 +61,8 @@ class CliTeam(TypedDict, total=False):class CliContextObj(TypedDict):base_url: strbase_url_explicit: NotRequired[bool]+ api_key: ReadOnly[NotRequired[str | None]]+ api_key_from_token_file: ReadOnly[NotRequired[bool]]class CliPollData(TypedDict, total=False):@@ -831,18 +833,21 @@ def print_token(ctx: click.Context):# actually issued this token for -- that's the whole point of not# needing a wrapper command.ctx_obj: Final[CliContextObj] = ctx.obj- if ctx_obj.get("base_url_explicit"):- base_url: Final = ctx_obj["base_url"]- if token_data.get("base_url") != base_url.rstrip("/"):- click.echo("Not authenticated for this server. Run 'lite login'.", err=True)- sys.exit(1)+ issued_for_this_server: Final = token_data.get("base_url") == ctx_obj.get("base_url", "").rstrip("/")+ if ctx_obj.get("base_url_explicit") and not issued_for_this_server:+ click.echo("Not authenticated for this server. Run 'lite login'.", err=True)+ sys.exit(1)renews: Final = "refresh_token" in token_dataif not is_cli_token_fresh(token_data) and not renews:click.echo("Token expired. Run 'lite login' again.", err=True)sys.exit(1)- api_key: Final = fresh_api_key(token_data, save_token, requests.Session(), reload=load_token, warn=_warn)+ api_key: Final = (+ ctx_obj.get("api_key")+ if issued_for_this_server and ctx_obj.get("api_key_from_token_file")+ else fresh_api_key(token_data, save_token, requests.Session(), reload=load_token, warn=_warn)+ )if not api_key:click.echo(f"Key expired. Run '{_login_command(renews)}' again.", err=True)sys.exit(1)diff --git a/litellm/proxy/client/cli/main.py b/litellm/proxy/client/cli/main.pyindex 3a289736c66..6dba1399acb 100644--- a/litellm/proxy/client/cli/main.py+++ b/litellm/proxy/client/cli/main.py@@ -93,11 +93,12 @@ def cli(ctx: click.Context, show_version: bool, base_url: str | None, api_key: s# If no API key provided via flag or environment variable, try to load from saved token.# Pass base_url so we only use the stored key when it was issued for this server.- if api_key is None:- api_key = get_stored_api_key(expected_base_url=base_url)+ api_key_from_token_file: Final = api_key is None+ resolved_api_key: Final = get_stored_api_key(expected_base_url=base_url) if api_key_from_token_file else api_keyctx.obj["base_url"] = base_url- ctx.obj["api_key"] = api_key+ ctx.obj["api_key"] = resolved_api_key+ ctx.obj["api_key_from_token_file"] = api_key_from_token_file# `--base-url` defaults to localhost:4000 for local dev convenience, but# apiKeyHelper is invoked bare (no flags) -- commands that must work# unattended (print-token) need to tell "user didn't say" apart from@@ -107,7 +108,7 @@ def cli(ctx: click.Context, show_version: bool, base_url: str | None, api_key: sctx.obj["base_url_explicit"] = base_url_provided or bool(stored_base_url)if show_version:- print_version(base_url, api_key)+ print_version(base_url, resolved_api_key)ctx.exit()# If no subcommand was invoked, start interactive modediff --git a/tests/test_litellm/proxy/client/cli/test_auth_commands.py b/tests/test_litellm/proxy/client/cli/test_auth_commands.pyindex f618bf8ea61..9b7dbbd1fdd 100644--- a/tests/test_litellm/proxy/client/cli/test_auth_commands.py+++ b/tests/test_litellm/proxy/client/cli/test_auth_commands.py@@ -1525,6 +1525,58 @@ class TestPkcePrintToken:assert "Run 'lite login' again" not in result.outputsave.assert_not_called()+ def test_print_token_through_the_cli_group_renews_once_and_reports_a_refusal_once(self, monkeypatch):+ monkeypatch.delenv("LITELLM_PROXY_API_KEY", raising=False)+ monkeypatch.delenv("LITELLM_PROXY_URL", raising=False)++ class _RefusingSession(_FakeSession):+ def __init__(self):+ super().__init__()+ self.response = _FakeHttpResponse(+ 400, {"error": "invalid_grant", "error_description": "the refresh token was already used"}+ )++ with (+ patch(+ "litellm.proxy.client.cli.commands.auth.load_token",+ return_value=_pkce_record(expires_at=time.time() - 1),+ ),+ patch("litellm.proxy.client.cli.commands.auth.save_token") as save,+ patch("litellm.proxy.client.cli.commands.auth.requests.Session", _RefusingSession),+ ):+ result = self.runner.invoke(cli, ["--base-url", PKCE_BASE_URL, "auth", "print-token"])++ assert result.exit_code == 1+ assert result.stdout == ""+ assert sum(len(session.posts) for session in _FakeSession.instances) == 1+ assert result.output.count("Could not renew the key") == 1+ assert "Could not renew the key: token request failed with 400: the refresh token was already used" in result.output+ assert "Key expired. Run 'lite login --pkce' again." in result.output+ save.assert_not_called()++ 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))+ 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, ["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_for_an_expired_classic_token_makes_no_request(self):with (patch(