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): renew a --pkce key wherever lite checks freshness and show its expiry in whoami

mateo-berri52c94327bd8f
diff --git a/litellm/litellm_core_utils/cli_token_utils.py b/litellm/litellm_core_utils/cli_token_utils.py
index 0043bc31204..50694ae615f 100644
--- a/litellm/litellm_core_utils/cli_token_utils.py
+++ b/litellm/litellm_core_utils/cli_token_utils.py
@@ -12,6 +12,8 @@ from collections.abc import Mapping
from pathlib import Path
from typing import Final
+CLI_TOKEN_FRESHNESS_BUFFER_SECONDS: Final = 360
+
def get_cli_token_file_path() -> str:
"""Get the path to the CLI token file"""
@@ -72,7 +74,9 @@ def get_litellm_gateway_api_key(
return token_data["key"]
-def is_cli_token_fresh(token_data: Mapping[str, object], buffer_hours: float = 0.1) -> bool:
+def is_cli_token_fresh(
+ token_data: Mapping[str, object], buffer_hours: float = CLI_TOKEN_FRESHNESS_BUFFER_SECONDS / 3600
+) -> bool:
"""Check whether a cached CLI token (as stored in token.json) is still
within its expiration window. Used by `lite auth print-token` to fail
fast, without a network round trip, once the cached token is past
diff --git a/litellm/proxy/client/README.md b/litellm/proxy/client/README.md
index 6b28f43ac73..997c923de4d 100644
--- a/litellm/proxy/client/README.md
+++ b/litellm/proxy/client/README.md
@@ -339,9 +339,10 @@ sequenceDiagram
The CLI provides these authentication commands:
- **`lite login`** - Start SSO authentication flow
-- **`lite logout`** - Clear stored authentication token
+- **`lite login --pkce`** - Sign in through the system browser with OAuth authorization code + PKCE; the key renews itself with a refresh token
+- **`lite logout`** - Clear stored authentication token (and revoke a `--pkce` refresh token on the proxy)
- **`lite whoami`** - Show current authentication status
-- **`lite auth print-token`** - Print the cached token (used as Claude Code's `apiKeyHelper`); fails once the token has expired
+- **`lite auth print-token`** - Print the cached token (used as Claude Code's `apiKeyHelper`); renews a `--pkce` key first and fails once a classic token has expired
### Authentication Flow Steps
@@ -377,7 +378,7 @@ Authentication tokens are stored in `~/.litellm/token.json` with restricted file
}
```
-The stored credential is a short-lived, per-session agent token, not a managed virtual key. It is scoped to the user and team you logged in as and inherits their models and budgets; spend is tracked against the shared team and user budgets rather than a separate per-session cap, so multiple logins or several concurrent agents all draw down the same allowance. It is short-lived by design (default 24h, configurable via `LITELLM_CLI_JWT_EXPIRATION_HOURS`); re-run `lite login` to refresh it and pick up your latest team and user settings. `lite auth print-token` (usable as Claude Code's `apiKeyHelper`) prints it while fresh and fails once it expires -- there is no silent renewal. It is accepted on a default deployment without `EXPERIMENTAL_UI_LOGIN`, does not appear in the Keys UI, and cannot be rotated or revoked mid-session. For a long-lived, rotatable, Keys-UI-visible credential, create a dedicated virtual key in the dashboard and pass it via `--api-key` or `LITELLM_PROXY_API_KEY`.
+The stored credential is a short-lived, per-session agent token, not a managed virtual key. It is scoped to the user and team you logged in as and inherits their models and budgets; spend is tracked against the shared team and user budgets rather than a separate per-session cap, so multiple logins or several concurrent agents all draw down the same allowance. It is short-lived by design (default 24h, configurable via `LITELLM_CLI_JWT_EXPIRATION_HOURS`); re-run `lite login` to refresh it and pick up your latest team and user settings. `lite auth print-token` (usable as Claude Code's `apiKeyHelper`) prints it while fresh and fails once it expires -- there is no silent renewal. It is accepted on a default deployment without `EXPERIMENTAL_UI_LOGIN`, does not appear in the Keys UI, and cannot be rotated or revoked mid-session. A credential from `lite login --pkce` is the exception: it carries a refresh token, so the CLI renews the key shortly before it expires and `lite logout` revokes the refresh token on the proxy (see [Browser sign-in with PKCE](https://docs.litellm.ai/docs/proxy/cli_sso#browser-sign-in-with-pkce)). For a long-lived, rotatable, Keys-UI-visible credential, create a dedicated virtual key in the dashboard and pass it via `--api-key` or `LITELLM_PROXY_API_KEY`.
### Usage
diff --git a/litellm/proxy/client/cli/README.md b/litellm/proxy/client/cli/README.md
index 9fe52b7a27d..faa015a2f77 100644
--- a/litellm/proxy/client/cli/README.md
+++ b/litellm/proxy/client/cli/README.md
@@ -501,13 +501,13 @@ To pin the model, pass the agent's own model flag (for example `lite claude --mo
The token minted by `lite login` is a short-lived, per-session agent credential, not a managed virtual key. It is scoped to the user and team you authenticated as, inherits that user's and team's models and budgets, and is enforced on the proxy exactly like a virtual key on the same team (guardrails, routing, logging, spend). Spend is tracked against the shared team and user budgets, so running several agents (or logging in more than once) does not hand each session its own separate budget; they all draw down the same team/user allowance. There is no separate per-session cap, so sustained agent use is not capped at a small chat-session limit.
-The credential is short-lived by design (default 24h, configurable via `LITELLM_CLI_JWT_EXPIRATION_HOURS`); run `lite login` again to refresh it, which also re-reads your latest team and user settings. It does not appear in the Keys UI and cannot be rotated or revoked mid-session. `lite auth print-token` (usable as Claude Code's `apiKeyHelper`) prints it while it's still fresh and fails once it expires -- there is no silent renewal, so a long-running session needs a fresh `lite login` once a day. `lite claude`, `lite codex`, and `lite opencode` work with it on a default deployment; `EXPERIMENTAL_UI_LOGIN` is not required. If you need a long-lived, rotatable key that shows up in the Keys UI, create a dedicated virtual key in the dashboard and pass it via `--api-key` or `LITELLM_PROXY_API_KEY` instead.
+The credential is short-lived by design (default 24h, configurable via `LITELLM_CLI_JWT_EXPIRATION_HOURS`); run `lite login` again to refresh it, which also re-reads your latest team and user settings. It does not appear in the Keys UI and cannot be rotated or revoked mid-session. `lite auth print-token` (usable as Claude Code's `apiKeyHelper`) prints it while it's still fresh and fails once it expires -- there is no silent renewal, so a long-running session needs a fresh `lite login` once a day. `lite claude`, `lite codex`, and `lite opencode` work with it on a default deployment; `EXPERIMENTAL_UI_LOGIN` is not required. `lite login --pkce` is the exception to the daily re-login: it signs in through your system browser with OAuth authorization code and PKCE and stores a refresh token next to the key, so every `lite` command and `lite auth print-token` renew the key on their own shortly before it expires, `lite whoami` shows when the current key expires, and `lite logout` revokes the refresh token on the proxy (it needs a proxy that serves `/.well-known/litellm-cli-auth`; see [Browser sign-in with PKCE](https://docs.litellm.ai/docs/proxy/cli_sso#browser-sign-in-with-pkce)). If you need a long-lived, rotatable key that shows up in the Keys UI, create a dedicated virtual key in the dashboard and pass it via `--api-key` or `LITELLM_PROXY_API_KEY` instead.
### Route Every Claude Code Session Through the Proxy
`lite claude` wraps a single invocation, but `lite up` goes further: it patches `~/.claude/settings.json`, Claude Code's own config file, so that every Claude Code session started afterward -- from any terminal, launched normally with just `claude`, no wrapper needed -- routes through your LiteLLM proxy. It sets `env.ANTHROPIC_BASE_URL` to the proxy URL and `apiKeyHelper` to a `lite auth print-token` invocation, drops any stray static `ANTHROPIC_API_KEY` so the helper-issued token wins, and leaves every other setting in the file untouched. It backs up the original file before patching it.
-Two things need to already be true: you've run `lite login`, since the apiKeyHelper depends on that stored token, and the proxy is already reachable, since `lite up` does not start one for you.
+Two things need to already be true: you've run `lite login` (or `lite login --pkce`, whose key the helper renews on its own), since the apiKeyHelper depends on that stored token, and the proxy is already reachable, since `lite up` does not start one for you.
```bash
lite login
diff --git a/litellm/proxy/client/cli/commands/auth.py b/litellm/proxy/client/cli/commands/auth.py
index aee715686b7..bc7247055d8 100644
--- a/litellm/proxy/client/cli/commands/auth.py
+++ b/litellm/proxy/client/cli/commands/auth.py
@@ -837,16 +837,29 @@ def whoami():
click.echo(f"User Email: {token_data.get('user_email', 'Unknown')}")
click.echo(f"User ID: {token_data.get('user_id', 'Unknown')}")
click.echo(f"User Role: {token_data.get('user_role', 'Unknown')}")
+ team_id: Final = token_data.get("team_id")
+ if team_id:
+ click.echo(f"Team ID: {team_id}")
- # Check if token is still valid (basic timestamp check)
timestamp: Final = token_data.get("timestamp", 0)
age_hours: Final = (time.time() - timestamp) / 3600
click.echo(f"Token age: {age_hours:.1f} hours")
- if age_hours > CLI_JWT_EXPIRATION_HOURS:
+ expires_at: Final = token_data.get("expires_at")
+ if isinstance(expires_at, (int, float)):
+ click.echo(_key_expiry_line(expires_at, renews="refresh_token" in token_data))
+ elif age_hours > CLI_JWT_EXPIRATION_HOURS:
click.echo(f"Warning: Token is more than {CLI_JWT_EXPIRATION_HOURS} hours old and may have expired.")
+def _key_expiry_line(expires_at: float, renews: bool) -> str:
+ remaining_hours: Final = (expires_at - time.time()) / 3600
+ status: Final = f"Key expires in: {remaining_hours:.1f} hours" if remaining_hours > 0 else "Key expired"
+ if renews:
+ return f"{status}, renewed on next use"
+ return status if remaining_hours > 0 else f"{status}. Run 'lite login' again"
+
+
@click.group(name="auth")
def auth_group():
"""Manage CLI authentication (apiKeyHelper support, etc.)"""
diff --git a/litellm/proxy/client/cli/commands/pkce_login.py b/litellm/proxy/client/cli/commands/pkce_login.py
index d00f9a86bfe..0e3b7c3271e 100644
--- a/litellm/proxy/client/cli/commands/pkce_login.py
+++ b/litellm/proxy/client/cli/commands/pkce_login.py
@@ -23,13 +23,14 @@ import requests
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError
from typing_extensions import ReadOnly, TypedDict
+from litellm.litellm_core_utils.cli_token_utils import CLI_TOKEN_FRESHNESS_BUFFER_SECONDS
+
if TYPE_CHECKING:
from .auth import CliTokenData
CLI_AUTH_DISCOVERY_PATH: Final = "/.well-known/litellm-cli-auth"
CALLBACK_PATH: Final = "/callback"
LOGIN_TIMEOUT_SECONDS: Final = 300
-REFRESH_LEEWAY_SECONDS: Final = 60
_HTTP_TIMEOUT_SECONDS: Final = 15
_CLIENT_NAME: Final = "litellm-cli"
@@ -460,7 +461,9 @@ def fresh_api_key(
now: Callable[[], float] = time.time,
) -> str | None:
"""The stored key, refreshed first when it is about to expire and a refresh token is
- on file. The rotated pair is saved before the new key is returned, so a crash after
+ on file. The refresh fires at the same moment ``is_cli_token_fresh`` stops calling the
+ key fresh, so a command that checks freshness and then asks for the key never disagrees
+ with itself. The rotated pair is saved before the new key is returned, so a crash after
this point never strands the CLI with a burned refresh token. A refresh that fails
reads the record again, because a sibling ``lite`` process may have rotated the pair
first, in which case the key it saved for this same proxy is the live one. A record without
@@ -471,7 +474,7 @@ def fresh_api_key(
expires_at: Final = token_data.get("expires_at")
if not isinstance(expires_at, (int, float)):
return key
- if now() < expires_at - REFRESH_LEEWAY_SECONDS:
+ if now() < expires_at - CLI_TOKEN_FRESHNESS_BUFFER_SECONDS:
return key
still_valid: Final = key if now() < expires_at else None
refresh_inputs: Final = _refresh_inputs(token_data)
diff --git a/litellm/proxy/client/cli/commands/up.py b/litellm/proxy/client/cli/commands/up.py
index dd266b4afa1..35ca504c493 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 load_token, login
+from .auth import get_stored_api_key, load_token, login
from .claude_settings import (
BACKUP_PATH,
CLAUDE_SETTINGS_PATH,
@@ -103,22 +103,34 @@ 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:
+ return False
+ token_data: Final = load_token()
+ return token_data is not None and is_cli_token_fresh(token_data)
+
+
+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("/")
- token_data = load_token()
- if token_data and token_data.get("base_url") == base_url and is_cli_token_fresh(token_data):
+ if _usable_login(base_url):
return
+ pkce: Final = _stored_login_is_pkce()
+ login_command: Final = "lite login --pkce" if pkce else "lite login"
if not sys.stdin.isatty():
raise UpError(
- "No fresh LiteLLM login found for this proxy. Run `lite login` first (apiKeyHelper "
+ f"No fresh LiteLLM login found for this proxy. Run `{login_command}` first (apiKeyHelper "
"reads this token on every Claude Code request)."
)
click.echo("No fresh LiteLLM login found for this proxy; starting login...")
- ctx.invoke(login)
- token_data = load_token()
- if not token_data or token_data.get("base_url") != base_url or not is_cli_token_fresh(token_data):
+ ctx.invoke(login, pkce=pkce)
+ if not _usable_login(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 dd86cba3f58..4e309bf1538 100644
--- a/tests/test_litellm/proxy/client/cli/test_auth_commands.py
+++ b/tests/test_litellm/proxy/client/cli/test_auth_commands.py
@@ -626,6 +626,39 @@ class TestWhoamiCommand:
assert "Authenticated" in result.output
assert "Unknown" in result.output # Should show "Unknown" for missing fields
+ def test_whoami_pkce_record_shows_the_team_and_when_the_key_renews(self):
+ token_data = {
+ "user_email": "unknown",
+ "user_id": "user-1",
+ "user_role": "cli",
+ "team_id": "team-alpha",
+ "timestamp": time.time() - 25 * 3600,
+ "expires_at": time.time() + 2 * 3600,
+ "refresh_token": "llm_srefresh_abc",
+ }
+
+ with patch("litellm.proxy.client.cli.commands.auth.load_token", return_value=token_data):
+ result = self.runner.invoke(whoami)
+
+ assert result.exit_code == 0
+ assert "Team ID: team-alpha" in result.output
+ assert "Key expires in: 2.0 hours, renewed on next use" in result.output
+ assert "Warning" not in result.output
+
+ def test_whoami_expired_key_without_a_refresh_token_asks_for_a_new_login(self):
+ token_data = {
+ "user_id": "user-1",
+ "timestamp": time.time() - 3600,
+ "expires_at": time.time() - 60,
+ }
+
+ with patch("litellm.proxy.client.cli.commands.auth.load_token", return_value=token_data):
+ result = self.runner.invoke(whoami)
+
+ assert result.exit_code == 0
+ assert "Team ID" not in result.output
+ assert "Key expired. Run 'lite login' again" in result.output
+
def test_whoami_no_timestamp(self):
"""Test whoami with token missing timestamp"""
token_data = {
diff --git a/tests/test_litellm/proxy/client/cli/test_pkce_login.py b/tests/test_litellm/proxy/client/cli/test_pkce_login.py
index bbdcbb6635d..db7d3c81d6c 100644
--- a/tests/test_litellm/proxy/client/cli/test_pkce_login.py
+++ b/tests/test_litellm/proxy/client/cli/test_pkce_login.py
@@ -5,6 +5,7 @@ import json
import re
import socket
import threading
+import time
import urllib.error
import urllib.request
from base64 import urlsafe_b64encode
@@ -13,6 +14,7 @@ from urllib.parse import parse_qs, urlparse
import pytest
import requests
+from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh
from litellm.proxy.client.cli.commands.pkce_login import (
CallbackCode,
CallbackDenied,
@@ -555,6 +557,23 @@ def test_fresh_api_key_refreshes_near_expiry_and_saves_before_returning():
assert http.calls[0][2]["refresh_token"] == "llm_srefresh_old"
[email protected](("seconds_left", "refreshes"), [(200, True), (600, False)])
+def test_fresh_api_key_refreshes_exactly_when_is_cli_token_fresh_stops_calling_the_key_fresh(
+ seconds_left, refreshes
+):
+ """`lite up` and `lite auth print-token` ask `is_cli_token_fresh` and then `fresh_api_key`; a key
+ the first calls stale that the second would not renew left `lite up` refusing a renewable login."""
+ record = {**STORED, "expires_at": time.time() + seconds_left}
+ http = _FakeHttp({("POST", f"{BASE}/token"): _FakeResponse(200, TOKEN_JSON)})
+ saved = []
+
+ key = _fresh(record, saved.append, http)
+
+ assert is_cli_token_fresh(record) is (not refreshes)
+ assert key == ("sk-cli-new" if refreshes else "sk-cli-old")
+ assert len(saved) == (1 if refreshes else 0)
+
+
def test_fresh_api_key_never_hands_out_a_rotated_key_it_could_not_save():
http = _FakeHttp({("POST", f"{BASE}/token"): _FakeResponse(200, TOKEN_JSON)})
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 51de0dcf11d..6344e4ba154 100644
--- a/tests/test_litellm/proxy/client/cli/test_up_commands.py
+++ b/tests/test_litellm/proxy/client/cli/test_up_commands.py
@@ -2,6 +2,7 @@ import json
import shutil
import stat
import sys
+import time
from unittest.mock import patch
import click
@@ -220,16 +221,62 @@ def _make_ctx(base_url):
return click.Context(click.Command("test"), obj={"base_url": base_url})
+def _pkce_record(base_url, seconds_left):
+ return {
+ "key": "sk-pkce",
+ "base_url": base_url,
+ "expires_at": time.time() + seconds_left,
+ "refresh_token": "llm_srefresh_old",
+ }
+
+
+class _FakeTokenStore:
+ """Stands in for the token file: `get_stored_api_key` answers per proxy and may rotate the
+ record that `load_token` returns afterwards, exactly the side effect a refresh has on disk."""
+
+ def __init__(self, monkeypatch, record, keys_by_base_url, rotated_to=None):
+ self.record = record
+ self.keys_by_base_url = keys_by_base_url
+ self.rotated_to = rotated_to
+ self.key_requests = []
+ monkeypatch.setattr(up_module, "load_token", lambda: self.record)
+ monkeypatch.setattr(up_module, "get_stored_api_key", self.get_stored_api_key)
+
+ def get_stored_api_key(self, expected_base_url=None):
+ self.key_requests.append(expected_base_url)
+ key = self.keys_by_base_url.get(expected_base_url)
+ if key is not None and self.rotated_to is not None:
+ self.record = self.rotated_to
+ return key
+
+ def log_in(self, record, key):
+ self.record = record
+ self.keys_by_base_url = {record["base_url"]: key}
+
+
+def _capture_login(monkeypatch, on_login=lambda: None):
+ login_calls = []
+
+ @click.pass_context
+ def fake_login(ctx, pkce=False):
+ login_calls.append((ctx.obj["base_url"], pkce))
+ on_login()
+
+ monkeypatch.setattr(up_module, "login", fake_login)
+ return login_calls
+
+
class TestEnsureFreshLogin:
"""A token that is fresh but was issued for a *different* proxy must not be trusted: without
this check, a user logged into proxy A who runs `up --base-url proxy-b` would silently get an
apiKeyHelper wired up around proxy A's real token, which print-token would then hand to proxy B."""
def test_reuses_a_fresh_token_issued_for_the_same_proxy(self, monkeypatch):
- monkeypatch.setattr(up_module, "load_token", lambda: {"key": "sk-a", "base_url": "http://proxy-a:4000"})
+ _FakeTokenStore(
+ monkeypatch, {"key": "sk-a", "base_url": "http://proxy-a:4000"}, {"http://proxy-a:4000": "sk-a"}
+ )
monkeypatch.setattr(up_module, "is_cli_token_fresh", lambda token_data: True)
- login_calls = []
- monkeypatch.setattr(up_module, "login", lambda ctx: login_calls.append(ctx))
+ login_calls = _capture_login(monkeypatch)
_ensure_fresh_login(_make_ctx("http://proxy-a:4000"))
@@ -237,34 +284,61 @@ class TestEnsureFreshLogin:
def test_forces_a_fresh_login_when_the_cached_token_is_for_a_different_proxy(self, monkeypatch):
monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: True)
- tokens = iter(
- [
- {"key": "sk-a", "base_url": "http://proxy-a:4000"},
- {"key": "sk-b", "base_url": "http://proxy-b:4000"},
- ]
- )
- monkeypatch.setattr(up_module, "load_token", lambda: next(tokens))
+ store = _FakeTokenStore(monkeypatch, {"key": "sk-a", "base_url": "http://proxy-a:4000"}, {})
monkeypatch.setattr(up_module, "is_cli_token_fresh", lambda token_data: True)
- login_calls = []
-
- @click.pass_context
- def fake_login(ctx):
- login_calls.append(ctx.obj["base_url"])
-
- monkeypatch.setattr(up_module, "login", fake_login)
+ login_calls = _capture_login(
+ monkeypatch, on_login=lambda: store.log_in({"key": "sk-b", "base_url": "http://proxy-b:4000"}, "sk-b")
+ )
_ensure_fresh_login(_make_ctx("http://proxy-b:4000"))
- assert login_calls == ["http://proxy-b:4000"]
+ assert login_calls == [("http://proxy-b:4000", False)]
+ assert store.key_requests == ["http://proxy-b:4000", "http://proxy-b:4000"]
def test_fails_cleanly_non_interactively_when_only_a_different_proxys_token_is_cached(self, monkeypatch):
monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: False)
- monkeypatch.setattr(up_module, "load_token", lambda: {"key": "sk-a", "base_url": "http://proxy-a:4000"})
+ _FakeTokenStore(monkeypatch, {"key": "sk-a", "base_url": "http://proxy-a:4000"}, {})
monkeypatch.setattr(up_module, "is_cli_token_fresh", lambda token_data: True)
- with pytest.raises(UpError, match="lite login"):
+ with pytest.raises(UpError, match="Run `lite login` first"):
_ensure_fresh_login(_make_ctx("http://proxy-b:4000"))
+ def test_trusts_a_pkce_credential_that_was_renewed_on_the_way_in(self, monkeypatch):
+ """A --pkce key inside its freshness buffer is renewed by `get_stored_api_key`, so `lite up`
+ must judge the rotated record rather than refuse the one it started with."""
+ monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: False)
+ store = _FakeTokenStore(
+ monkeypatch,
+ _pkce_record("http://proxy-a:4000", seconds_left=200),
+ {"http://proxy-a:4000": "sk-pkce-renewed"},
+ rotated_to=_pkce_record("http://proxy-a:4000", seconds_left=86_400),
+ )
+ login_calls = _capture_login(monkeypatch)
+
+ _ensure_fresh_login(_make_ctx("http://proxy-a:4000"))
+
+ assert login_calls == []
+ assert store.key_requests == ["http://proxy-a:4000"]
+
+ def test_logs_in_again_with_pkce_when_the_stale_credential_came_from_pkce(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_ctx("http://proxy-a:4000"))
+
+ assert login_calls == [("http://proxy-a:4000", True)]
+
+ def test_names_the_pkce_login_in_the_non_interactive_error_for_a_pkce_credential(self, monkeypatch):
+ monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: False)
+ _FakeTokenStore(monkeypatch, _pkce_record("http://proxy-a:4000", seconds_left=-10), {})
+
+ with pytest.raises(UpError, match="Run `lite login --pkce` first"):
+ _ensure_fresh_login(_make_ctx("http://proxy-a:4000"))
+
class TestUpCommand:
def setup_method(self):
@@ -277,6 +351,7 @@ class TestUpCommand:
with (
patch(f"{UP_MODULE}.load_token", return_value={"key": "sk-fresh", "base_url": "http://localhost:4000"}),
+ patch(f"{UP_MODULE}.get_stored_api_key", return_value="sk-fresh"),
patch(f"{UP_MODULE}.is_cli_token_fresh", return_value=True),
patch(f"{UP_MODULE}.resolve_api_key", return_value="sk-fresh"),
patch(f"{UP_MODULE}.verify_proxy_key"),
@@ -293,7 +368,10 @@ class TestUpCommand:
_patch_paths(monkeypatch, tmp_path)
monkeypatch.setattr(sys.stdin, "isatty", lambda: False)
- with patch(f"{UP_MODULE}.load_token", return_value=None):
+ with (
+ patch(f"{UP_MODULE}.load_token", return_value=None),
+ patch(f"{UP_MODULE}.get_stored_api_key", return_value=None),
+ ):
result = self.runner.invoke(up, obj={"base_url": "http://localhost:4000"})
assert result.exit_code != 0
@@ -304,6 +382,7 @@ class TestUpCommand:
with (
patch(f"{UP_MODULE}.load_token", return_value={"key": "sk-fresh", "base_url": "http://localhost:4000"}),
+ patch(f"{UP_MODULE}.get_stored_api_key", return_value="sk-fresh"),
patch(f"{UP_MODULE}.is_cli_token_fresh", return_value=True),
patch(f"{UP_MODULE}.resolve_api_key", return_value="sk-fresh"),
patch(
@@ -330,6 +409,7 @@ class TestUpCommand:
with (
patch(f"{UP_MODULE}.load_token", return_value={"key": "sk-fresh", "base_url": "http://localhost:4000"}),
+ patch(f"{UP_MODULE}.get_stored_api_key", return_value="sk-fresh"),
patch(f"{UP_MODULE}.is_cli_token_fresh", return_value=True),
patch(f"{UP_MODULE}.resolve_api_key", return_value="sk-fresh"),
patch(f"{UP_MODULE}.verify_proxy_key"),
@@ -416,7 +496,7 @@ class TestUpCanInvokeTheRealLoginCommand:
@click.pass_context
def driver(ctx):
ctx.obj = {"base_url": "http://127.0.0.1:9"}
- ctx.invoke(real_login)
+ ctx.invoke(real_login, pkce=False)
with patch(
f"{AUTH_MODULE}._start_cli_sso_flow",
@@ -436,7 +516,7 @@ class TestUpCanInvokeTheRealLoginCommand:
@click.pass_context
def driver(ctx):
ctx.obj = {"base_url": "http://127.0.0.1:9"}
- ctx.invoke(real_login)
+ ctx.invoke(real_login, pkce=False)
with (
patch(f"{AUTH_MODULE}.CLAUDE_SETTINGS_PATH", settings_path),