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
Merge origin/litellm_internal_staging into litellm_cli_refresh_tokens
mateo-berri5f7c0e1e49c7
diff --cc litellm/litellm_core_utils/cli_token_utils.pyindex c0e57a737e4,50694ae615f..b45513c5ea3--- a/litellm/litellm_core_utils/cli_token_utils.py+++ b/litellm/litellm_core_utils/cli_token_utils.py@@@ -12,112 -5,16 +12,118 @@@ first time it reads oneThis module has no dependencies on proxy code and can be safely imported at the SDK level."""-import json-import os+import mathimport time+ from collections.abc import Mapping+from dataclasses import dataclassfrom pathlib import Path-from typing import Final+from types import MappingProxyType+from typing import Final, TypeAlias++from pydantic import BaseModel, ConfigDict, ValidationError++from litellm.litellm_core_utils.cli_keyring import (+ SYSTEM_KEYRING,+ KeyringDisabled,+ KeyringNotInstalled,+ KeyringUnreachable,+ SecretErase,+ SecretErased,+ SecretFound,+ SecretMissing,+ SecretStored,+ SecretStranded,+ SecretVault,+ SecretWrite,+)+from litellm.litellm_core_utils.private_json import (+ commit_staged_json,+ discard_staged_json,+ ensure_private_dir,+ overwrite_private_json,+ stage_private_json,+ write_private_json,+)+++@dataclass(frozen=True, slots=True)+class CredentialNotSaved:+ """The credential was minted but no store would keep it, so this machine has none.++ Nothing was touched on the way to this, so a login that already worked still does.+ """++ detail: str+++@dataclass(frozen=True, slots=True)+class CredentialNotRecorded:+ """The keychain took the credential, but the file that names it could not be replaced.++ The keychain holds one entry, so the secret that was there is already gone and no rollback+ brings it back. Removing the new one as well would only turn a login this machine may still+ be able to use into no login at all, so it stays, and the user is told what is where.+ """+++@dataclass(frozen=True, slots=True)+class CredentialNotCleared:+ """The token file still holds the secret, because it could not be removed or rewritten.++ Logging out of the keychain is only half of it. A `~/.litellm` that refuses both the scrubbed+ rewrite and the removal leaves the credential readable on disk, which is the one thing a logout+ is for, so it is reported instead of being counted as a clean sweep.+ """++ detail: str+++SecretSave: TypeAlias = SecretWrite | CredentialNotSaved | CredentialNotRecorded++SecretClear: TypeAlias = SecretErase | CredentialNotCleared+++class CliTokenRecord(BaseModel):+ """A stored CLI credential.++ `key is None` means the metadata was found but the secret could not be+ produced: the keychain holds nothing for us, or we could not reach it.+ """++ model_config = ConfigDict(frozen=True, extra="allow")++ base_url: str = ""+ key: str | None = None+ user_id: str = ""+ user_email: str = ""+ user_role: str = ""+ auth_header_name: str = "Authorization"+ jwt_token: str = ""+ timestamp: float = 0.0++ expires_at: float | None = None++ refresh_token: str | None = None+++class CliTokenSecret(BaseModel):+ """The secret material as stored in the OS keychain.++ `base_url` is duplicated from the metadata file purely as a pairing tag: a+ secret minted for one server is never handed to another, even if the+ metadata file is edited underneath us. `timestamp` is the sign-in this+ secret came from, which is what decides it against a secret still on disk.+ """++ model_config = ConfigDict(frozen=True)++ base_url: str+ key: str+ jwt_token: str = ""+ timestamp: float = 0.0++ CLI_TOKEN_FRESHNESS_BUFFER_SECONDS: Final = 360++def get_cli_token_file_path() -> str:"""Get the path to the CLI token file"""home_dir: Final = Path.home()@@@ -325,170 -64,30 +331,182 @@@ def get_litellm_gateway_api_key>>> base_url="https://your-proxy.com/v1">>> )"""- token_data: Final = load_cli_token()- if not token_data or "key" not in token_data:+ record: Final = _read_token_file()+ if record is None:return None- if expected_base_url is not None:- stored_url: Final = token_data.get("base_url")- if stored_url != expected_base_url.rstrip("/"):- return None- return token_data["key"]+ if expected_base_url is not None and record.base_url != expected_base_url.rstrip("/"):+ return None+ resolved: Final = _resolve_secret(record, vault)+ return None if resolved is None else resolved.key- def is_cli_token_fresh(token_data: CliTokenRecord, 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++ token_data: CliTokenRecord | 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- `LITELLM_CLI_JWT_EXPIRATION_HOURS`."""+ """Check whether a cached CLI token 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 `LITELLM_CLI_JWT_EXPIRATION_HOURS`."""++ once the cached token is past `LITELLM_CLI_JWT_EXPIRATION_HOURS`. A `--pkce`++ credential carries its own `expires_at`, which is authoritative when present."""from litellm.constants import CLI_JWT_EXPIRATION_HOURS- age_hours: Final = (time.time() - token_data.timestamp) / 3600- expires_at: Final = token_data.get("expires_at")++ expires_at: Final = (++ token_data.expires_at if isinstance(token_data, CliTokenRecord) else token_data.get("expires_at")++ )+ if isinstance(expires_at, (int, float)):+ return time.time() < expires_at - buffer_hours * 3600- timestamp: Final = token_data.get("timestamp")++ timestamp: Final = token_data.timestamp if isinstance(token_data, CliTokenRecord) else token_data.get("timestamp")+ if not isinstance(timestamp, (int, float)):+ return False+ age_hours: Final = (time.time() - timestamp) / 3600return age_hours < (CLI_JWT_EXPIRATION_HOURS - buffer_hours)+++def _read_token_file() -> CliTokenRecord | None:+ try:+ raw: Final = Path(get_cli_token_file_path()).read_text()+ except (OSError, ValueError):+ return None+ try:+ return CliTokenRecord.model_validate_json(raw)+ except ValidationError:+ return None+++def _resolve_secret(record: CliTokenRecord, vault: SecretVault) -> CliTokenRecord | None:+ match vault.read():+ case SecretFound(blob=blob):+ return _apply_vault_secret(record, blob, vault)+ case SecretMissing():+ return _migrate_file_secret(record, vault)+ case KeyringNotInstalled() | KeyringDisabled() | KeyringUnreachable():+ return record+++def _apply_vault_secret(record: CliTokenRecord, blob: str, vault: SecretVault) -> CliTokenRecord | None:+ """Resolve the credential when both stores hold one.++ The sign-in each secret came from decides it, because either store can be the stale one. A+ secret is usually left on disk by a keychain that would not take it, which makes the file the+ fresher of the two. It is the older one when a login the keychain did take could not replace+ the file afterwards, and serving that one would put a superseded credential back in use. Equal+ stamps are one login sitting in both stores, left by a migration whose scrub was refused, so+ that branch retries the migration rather than trading one credential for another.++ A scrub the file refuses leaves that superseded secret where it lies, which is the state the+ login already named when it could not replace the file, and which `lite logout` reports rather+ than counting as a clean sweep. Rolling the vault back the way a migration does is not the+ answer here, because the two stores hold different credentials and the rollback would hand the+ superseded one back out.+ """+ secret: Final = _decode_secret(blob, record.base_url)+ if secret is None or (record.key is not None and secret.timestamp <= record.timestamp):+ return _migrate_file_secret(record, vault)+ _scrub_file_secret(record)+ return record.model_copy(+ update=MappingProxyType(+ {+ "key": secret.key,+ "jwt_token": secret.jwt_token,+ "timestamp": max(secret.timestamp, record.timestamp),+ }+ )+ )+++def _migrate_file_secret(record: CliTokenRecord, vault: SecretVault) -> CliTokenRecord | None:+ """Move a file-held secret into the vault, but only once the file's copy can be taken away.++ The scrubbed file is staged first so a directory that will not accept it stops the migration+ before the keychain is handed anything. Copying the credential into a second store and only+ then discovering the first one cannot be cleaned would widen exposure instead of narrowing it,+ which is the opposite of what moving it into the keychain is for.++ A staged file that will not go into place is overwritten where it lies before the keychain is+ asked to take the new entry back, so the migration finishes on a directory that would only ever+ have refused it. Rolling back is the last resort, and a rollback the keychain also refuses+ leaves the secret in both stores until the next read, which retries this same migration.+ """+ if record.key is None:+ return None+ staged: Final = _stage_scrubbed_file(record)+ if staged is None:+ return record+ if not isinstance(vault.write(_encode_secret(record, record.key)), SecretStored):+ discard_staged_json(staged)+ return record+ if not _commit_token_file(staged) and not _overwrite_file_secret(record):+ vault.erase()+ return record+++def _scrub_file_secret(record: CliTokenRecord) -> bool:+ """Leave no secret material in the token file once the vault holds it"""+ if record.key is None and not record.jwt_token:+ return True+ staged: Final = _stage_scrubbed_file(record)+ if staged is not None and _commit_token_file(staged):+ return True+ return _overwrite_file_secret(record)+++def _overwrite_file_secret(record: CliTokenRecord) -> bool:+ """Take the secret out of the token file where it lies, when no replacement can be put in place.++ The atomic rewrite wants room for a second file and a directory that will accept it. A full disk+ refuses the first and a read-only `~/.litellm` the second, and neither stands in the way of+ shortening the file that is already there. It is worth the loss of atomicity because a partial+ write reads as no login at all, which is where the refused rewrite left the next run anyway.+ """+ try:+ overwrite_private_json(get_cli_token_file_path(), _without_secret(record).model_dump(exclude_none=True))+ except OSError:+ return False+ return True+++def _stage_scrubbed_file(record: CliTokenRecord) -> str | None:+ staged: Final = _stage_token_file(_without_secret(record))+ return None if isinstance(staged, CredentialNotSaved) else staged+++def _stage_token_file(record: CliTokenRecord) -> str | CredentialNotSaved:+ path: Final = Path(get_cli_token_file_path())+ try:+ ensure_private_dir(path.parent)+ return stage_private_json(str(path), record.model_dump(exclude_none=True))+ except OSError as error:+ return CredentialNotSaved(str(error))+++def _commit_token_file(staged: str) -> bool:+ try:+ commit_staged_json(staged, get_cli_token_file_path())+ except OSError:+ return False+ return True+++def _without_secret(record: CliTokenRecord) -> CliTokenRecord:+ return record.model_copy(update=MappingProxyType({"key": None, "jwt_token": ""}))+++def _encode_secret(record: CliTokenRecord, key: str) -> str:+ return CliTokenSecret(+ base_url=record.base_url, key=key, jwt_token=record.jwt_token, timestamp=record.timestamp+ ).model_dump_json()+++def _decode_secret(blob: str, base_url: str) -> CliTokenSecret | None:+ """The keychain entry, when it is one this metadata file may be paired with"""+ try:+ secret: Final = CliTokenSecret.model_validate_json(blob)+ except ValidationError:+ return None+ return secret if secret.base_url == base_url else None+++def _write_token_file(record: CliTokenRecord) -> None:+ path: Final = Path(get_cli_token_file_path())+ ensure_private_dir(path.parent)+ write_private_json(str(path), record.model_dump(exclude_none=True))diff --cc litellm/proxy/client/README.mdindex d46c7174b4c,bfe95dfcbd7..3a39bec5ee6--- a/litellm/proxy/client/README.md+++ b/litellm/proxy/client/README.md@@@ -377,11 -378,7 +378,11 @@@ The key itself goes into the OS keychai}```+Keychain storage needs the `keyring` package, which ships with `pip install 'litellm[cli]'`. Headless boxes and CI runners usually have no keychain either. In all of those cases the key stays in the same `0600` file alongside the metadata, exactly as it did before, and `lite login` names which one applies: the package is missing, the machine has no keychain, or you set `LITELLM_CLI_DISABLE_KEYRING=1` to force the file even where a keychain exists. A `token.json` written by an older `lite` keeps working and is moved into the keychain, and scrubbed from the file, the first time a keychain-capable `lite` reads it.++`lite logout` clears both stores. If the keychain is locked at that moment it says so, and re-running it once the keychain is unlocked finishes the job.+- 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)). Only the holder can end a `--pkce` session early, with `lite logout`; an admin has no button for it, but every renewal re-reads the user on the proxy, so deactivating the user or removing them from the team makes the next renewal fail and the key runs out within `LITELLM_CLI_JWT_EXPIRATION_HOURS`. On a proxy with more than one worker or replica, configure Redis (`litellm_settings.cache` with Redis `cache_params`, or `general_settings.coordination_redis`) so a refresh token stays single-use and `lite logout` holds on every worker; without Redis each worker keeps its own record. 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`.### Usagediff --cc litellm/proxy/client/cli/commands/auth.pyindex e5d90b9b640,31583dec978..550b11311f5--- a/litellm/proxy/client/cli/commands/auth.py+++ b/litellm/proxy/client/cli/commands/auth.py@@@ -1,6 -1,9 +1,7 @@@import sysimport timeimport webbrowser-from pathlib import Path++from collections.abc import Callable, Mappingfrom typing import Any, Finalfrom urllib.parse import urlencode@@@ -8,36 -11,10 +9,35 @@@ import clicimport requestsfrom rich.console import Consolefrom rich.table import Table- from typing_extensions import NotRequired, ReadOnly, TypedDict+ from typing_extensions import NotRequired, ReadOnly, TypedDict, assert_neverfrom litellm.constants import CLI_JWT_EXPIRATION_HOURS-from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh+from litellm.litellm_core_utils.cli_keyring import (+ DISABLE_KEYRING_ENV_VAR,+ SYSTEM_KEYRING,+ KeyringDisabled,+ KeyringDiscardsWrites,+ KeyringNotInstalled,+ KeyringUnreachable,+ SecretErased,+ SecretFound,+ SecretMissing,+ SecretStored,+ SecretStranded,+ SecretVault,+)+from litellm.litellm_core_utils.cli_token_utils import (+ CliTokenRecord,+ CredentialNotCleared,+ CredentialNotRecorded,+ CredentialNotSaved,+ SecretSave,+ clear_cli_token,+ get_cli_token_file_path,- get_litellm_gateway_api_key,+ is_cli_token_fresh,+ load_cli_token,+ save_cli_token,+)from .claude_settings import (CLAUDE_SETTINGS_PATH,@@@ -45,6 -22,34 +45,33 @@@ClaudeSettingsError,write_claude_settings,)+ from .pkce_login import (+ Http,+ PkceFailure,+ RevocationUnavailable,+ fresh_api_key,+ pkce_token_record,+ revoke_stored_credential,+ run_pkce_login,+ )-from .private_json import write_private_json+++ class CliTokenData(TypedDict):+ base_url: str+ key: str+ user_id: str+ user_email: str+ user_role: str+ auth_header_name: str+ jwt_token: str+ timestamp: float+ expires_at: ReadOnly[NotRequired[float]]+ refresh_token: ReadOnly[NotRequired[str]]+ client_id: ReadOnly[NotRequired[str]]+ token_endpoint: ReadOnly[NotRequired[str]]+ revocation_endpoint: ReadOnly[NotRequired[str]]+ resource: ReadOnly[NotRequired[str]]+ team_id: ReadOnly[NotRequired[str | None]]class CliTeam(TypedDict, total=False):@@@ -57,7 -62,8 +84,9 @@@class CliContextObj(TypedDict):base_url: strbase_url_explicit: NotRequired[bool]+ secret_vault: NotRequired[ReadOnly[SecretVault]]+ api_key: ReadOnly[NotRequired[str | None]]+ api_key_from_token_file: ReadOnly[NotRequired[bool]]class CliPollData(TypedDict, total=False):@@@ -88,97 -94,59 +117,156 @@@ class CliAuthResult(TypedDict)team_id: str | None-# Token storage utilities-def get_token_file_path() -> str:- """Get the path to store the authentication token"""- return str(Path.home() / ".litellm" / "token.json")+KEYRING_INSTALL_HINT: Final = "pip install 'litellm[cli]'"+KEYRING_ENABLE_HINT: Final = "keyring --enable (or unset PYTHON_KEYRING_BACKEND)"-def save_token(token_data: CliTokenData) -> None:- """Save token data to file"""- write_private_json(get_token_file_path(), token_data)+STRANDED_CREDENTIAL_MESSAGE: Final = (+ "Logged out locally, but your credential is still in the OS keychain and could not be removed."+)+UNCHECKED_KEYCHAIN_MESSAGE: Final = (+ "Logged out locally, but your OS keychain could not be checked, so a credential stored there by "+ "an earlier login may still be usable."+)-def load_token() -> CliTokenData | None:- """Load token data from file"""- token_file: Final = get_token_file_path()- if not os.path.exists(token_file):- return None- try:- with open(token_file, "r") as f:- return json.load(f)- except (OSError, json.JSONDecodeError):- return None+def storage_notice(outcome: SecretSave) -> str:+ """Tell the user where the credential ended up, and how to get keychain storage if it did not."""+ path: Final = get_cli_token_file_path()+ match outcome:+ case SecretStored():+ return "Credential stored in your OS keychain."+ case KeyringNotInstalled():+ return (+ f"Credential stored in {path} (owner-only). "+ f"For OS keychain storage, install the keyring package with: {KEYRING_INSTALL_HINT}"+ )+ case KeyringDisabled():+ return f"Keychain storage is off ({DISABLE_KEYRING_ENV_VAR}). Credential stored in {path} (owner-only)."+ case KeyringUnreachable():+ return f"No OS keychain available. Credential stored in {path} (owner-only)."+ case KeyringDiscardsWrites():+ return (+ f"Your keyring backend keeps nothing it is given, so the credential was stored in {path} "+ f"(owner-only) instead. For OS keychain storage, run: {KEYRING_ENABLE_HINT}"+ )+ case CredentialNotSaved(detail=detail):+ return (+ f"Signed in, but the credential could not be saved to {path}: {detail}. "+ "Any login you already had is untouched. Run 'lite login' again once that path is "+ "writable, or 'lite logout' to clear whatever is stored now."+ )+ case CredentialNotRecorded():+ return (+ f"Signed in, and the credential is in your OS keychain, but {path} could not be "+ "replaced, so it still describes your previous login and may still hold its "+ "credential. Run 'lite login' again once that path is writable, or 'lite logout' "+ "to clear both."+ )+++def keychain_unreadable_notice(vault: SecretVault) -> str:+ """Explain why the secret half of a stored login cannot be produced, and what fixes it"""+ match vault.read():+ case KeyringNotInstalled():+ return (+ "Your credential is in your OS keychain, which this install cannot read without the "+ f"keyring package. Install it with: {KEYRING_INSTALL_HINT}, or run 'lite login' to start over."+ )+ case KeyringDisabled():+ return (+ f"Your credential is in your OS keychain, which {DISABLE_KEYRING_ENV_VAR} is blocking. "+ "Unset it, or run 'lite login' to start over."+ )+ case KeyringUnreachable():+ return (+ "Your credential is in your OS keychain, which could not be read. Unlock it, or run "+ "'lite login' to start over."+ )+ case SecretFound() | SecretMissing():+ return "Your credential could not be read from your OS keychain. Run 'lite login' to start over."+++def context_secret_vault(ctx: click.Context) -> SecretVault:+ """Where this invocation reads and writes secret material; injectable through ctx.obj for tests"""+ ctx_obj: Final[CliContextObj | None] = ctx.obj+ if ctx_obj is None:+ return SYSTEM_KEYRING+ return ctx_obj.get("secret_vault") or SYSTEM_KEYRING++++def load_token(*, vault: SecretVault = SYSTEM_KEYRING) -> Mapping[str, object] | None:++ """The stored credential as a plain mapping, with the secret resolved out of the vault.++++ The PKCE renewal and revocation helpers read records by field name, so this is the++ shape they get; the keychain split lives underneath, in `load_cli_token`.++ """++ record: Final = load_cli_token(vault=vault)++ return None if record is None else record.model_dump(exclude_none=True)++-def clear_token() -> None:- """Clear stored token"""- token_file: Final = get_token_file_path()- if os.path.exists(token_file):- os.remove(token_file)++def save_token(record: CliTokenData, *, vault: SecretVault = SYSTEM_KEYRING) -> SecretSave:++ """Store a credential the PKCE layer produced, secret in the vault and the rest on disk"""++ return save_cli_token(CliTokenRecord(**record), vault=vault)++-def get_stored_api_key(expected_base_url: str | None = None) -> str | None:- """Get the stored API key from token file.++def _renewal_saver(vault: SecretVault) -> Callable[[CliTokenData], None]:++ """Persist a silently renewed credential, and say on stderr when no store would keep it.++++ A renewal rotates the refresh token, so a rotation that is never stored logs this++ machine out on the next command; the user hears about it rather than guessing.++ """++++ def save(record: CliTokenData) -> None:++ outcome: Final = save_token(record, vault=vault)++ if isinstance(outcome, (CredentialNotSaved, CredentialNotRecorded)):++ _warn(storage_notice(outcome))++++ return save++++++def _renewal_reader(vault: SecretVault) -> Callable[[], Mapping[str, object] | None]:++ """Re-read the record mid-renewal, so a rotation a sibling `lite` process saved is seen"""++++ def reload() -> Mapping[str, object] | None:++ return load_token(vault=vault)++++ return reload+++++def get_stored_api_key(+ expected_base_url: str | None = None,+ *,+ vault: SecretVault = SYSTEM_KEYRING,+) -> str | None:+ """Get the stored API key.If expected_base_url is provided, the key is only returned when it wasoriginally issued for that URL. This prevents credential leakage when the- CLI is pointed at a different (possibly malicious) server.+ CLI is pointed at a different (possibly malicious) server. A key obtained by+ ``lite login --pkce`` is refreshed here once it nears expiry."""- return get_litellm_gateway_api_key(expected_base_url=expected_base_url, vault=vault)- token_data: Final = load_token()++ token_data: Final = load_token(vault=vault)+ if token_data is None:+ return None+ if expected_base_url is not None and token_data.get("base_url") != expected_base_url.rstrip("/"):+ return None- return fresh_api_key(token_data, save_token, requests.Session(), reload=load_token, warn=_warn)++ return fresh_api_key(++ token_data,++ _renewal_saver(vault),++ requests.Session(),++ reload=_renewal_reader(vault),++ warn=_warn,++ )+++ def _warn(message: str) -> None:+ click.echo(message, err=True)+++ def _login_command(renews: bool) -> str:+ return "lite login --pkce" if renews else "lite login"# Team selection utilities@@@ -704,6 -672,41 +792,45 @@@ def _configure_claude_code(base_url: stclick.echo("Your other Claude Code settings were left untouched. Restart Claude Code to pick this up.")-def _finish_login(base_url: str, api_key: str, config_claude: bool) -> None:++def _finish_login(base_url: str, api_key: str, config_claude: bool, stored: SecretSave) -> None:+ from litellm.proxy.client.cli.interface import show_commands++ click.echo("\nLogin successful!")+ click.echo(f"JWT Token: {api_key[:20]}...")++ click.echo(storage_notice(stored))++ if isinstance(stored, (CredentialNotSaved, CredentialNotRecorded)):++ return+ click.echo("You can now use the CLI without specifying --api-key")+ if config_claude:+ _configure_claude_code(base_url)+ click.echo("\n" + "=" * 60)+ show_commands()++-def _replace_stored_token(record: CliTokenData, http: Http) -> None:- previous: Final = load_token()- save_token(record)- if previous is None:- return++def _replace_stored_token(record: CliTokenData, http: Http, vault: SecretVault) -> SecretSave:++ previous: Final = load_token(vault=vault)++ stored: Final = save_token(record, vault=vault)++ if previous is None or isinstance(stored, CredentialNotSaved):++ return stored+ revocation: Final = revoke_stored_credential(previous, http)+ if revocation is not None:+ click.echo(+ f"Could not revoke the previous login's refresh token on the proxy ({revocation.reason}); "+ "it expires on its own."+ )++ return stored++-def _pkce_login(base_url: str, config_claude: bool) -> None:++def _pkce_login(base_url: str, config_claude: bool, vault: SecretVault) -> None:+ http: Final = requests.Session()+ credential: Final = run_pkce_login(base_url, http, echo=click.echo)+ if isinstance(credential, PkceFailure):+ click.echo(f"Authentication failed: {credential.reason}")+ return- _replace_stored_token(pkce_token_record(base_url, credential), http)- _finish_login(base_url, credential.access_token, config_claude)++ stored: Final = _replace_stored_token(pkce_token_record(base_url, credential), http, vault)++ _finish_login(base_url, credential.access_token, config_claude, stored)++@click.command(name="login")@click.option("--config-claude",@@@ -724,6 -736,9 +860,9 @@@ def login(ctx: click.Context, config_clbase_url: Final = ctx_obj["base_url"]try:+ if pkce:- _pkce_login(base_url, config_claude)++ _pkce_login(base_url, config_claude, context_secret_vault(ctx))+ returncli_sso_flow: Final = _start_cli_sso_flow(base_url=base_url)key_id: Final = cli_sso_flow["login_id"]poll_secret: Final = cli_sso_flow["poll_secret"]@@@ -748,31 -763,23 +887,24 @@@api_key: Final = auth_result["api_key"]user_id: Final = auth_result["user_id"]- record: Final = CliTokenRecord(- base_url=base_url.rstrip("/"),- key=api_key,- user_id=user_id or "cli-user",- user_email="unknown",- user_role="cli",- auth_header_name="Authorization",- jwt_token="",- timestamp=time.time(),+ # Save token data. base_url is stored so we can verify origin+ # before reusing the key on a subsequent CLI invocation.- _replace_stored_token(++ stored: Final = _replace_stored_token(+ {+ "base_url": base_url.rstrip("/"),+ "key": api_key,+ "user_id": user_id or "cli-user",+ "user_email": "unknown",+ "user_role": "cli",+ "auth_header_name": "Authorization",+ "jwt_token": "",+ "timestamp": time.time(),+ },+ requests.Session(),++ context_secret_vault(ctx),)- stored: Final = save_cli_token(record, vault=context_secret_vault(ctx))-- click.echo("\nLogin successful!")- click.echo(f"JWT Token: {api_key[:20]}...")- click.echo(storage_notice(stored))- if isinstance(stored, (CredentialNotSaved, CredentialNotRecorded)):- return- click.echo("You can now use the CLI without specifying --api-key")-- if config_claude:- _configure_claude_code(base_url)- # Show available commands after successful login- click.echo("\n" + "=" * 60)- show_commands()- _finish_login(base_url, api_key, config_claude)++ _finish_login(base_url, api_key, config_claude, stored)returnelse:click.echo("Authentication timed out. Please try again.")@@@ -795,28 -802,23 +927,44 @@@@click.command(name="logout")-def logout():[email protected]_context+def logout(ctx: click.Context):"""Logout and clear stored authentication"""- token_data: Final = load_token()++ vault: Final = context_secret_vault(ctx)++ token_data: Final = load_token(vault=vault)+ revocation: Final = revoke_stored_credential(token_data, requests.Session()) if token_data is not None else None+ match revocation:+ case RevocationUnavailable(reason=reason):+ raise click.ClickException(- f"The proxy could not record the revocation ({reason}). Nothing was cleared; run `lite logout` again shortly."++ f"The proxy could not record the revocation ({reason}). Nothing was cleared; "++ "run `lite logout` again shortly."+ )+ case PkceFailure(reason=reason):- clear_token()+ click.echo(f"Could not revoke the refresh token on the proxy ({reason}); it expires on its own.")+ case None:- clear_token()++ pass+ case _:+ assert_never(revocation)- click.echo("Logged out successfully. Authentication token cleared.")+++ path: Final = get_cli_token_file_path()- match clear_cli_token(vault=context_secret_vault(ctx)):++ match clear_cli_token(vault=vault):+ case SecretErased():+ click.echo("Logged out successfully. Authentication token cleared.")+ case CredentialNotCleared(detail=detail):+ click.echo(f"Your credential is still in {path}, which could not be removed: {detail}.")+ click.echo("Delete that file, or make the directory writable and run 'lite logout' again.")+ case SecretStranded():+ click.echo(STRANDED_CREDENTIAL_MESSAGE)+ click.echo("Unlock your keychain and run 'lite logout' again to clear it.")+ case KeyringNotInstalled():+ click.echo(UNCHECKED_KEYCHAIN_MESSAGE)+ click.echo(f"Install the keyring package with: {KEYRING_INSTALL_HINT}, then run 'lite logout' again.")+ case KeyringDisabled():+ click.echo(UNCHECKED_KEYCHAIN_MESSAGE)+ click.echo(f"Unset {DISABLE_KEYRING_ENV_VAR} and run 'lite logout' again to clear it.")+ case KeyringUnreachable():+ click.echo(UNCHECKED_KEYCHAIN_MESSAGE)+ click.echo("Unlock your keychain and run 'lite logout' again to clear it.")@click.command(name="print-token")@@@ -827,10 -829,11 +975,12 @@@ def print_token(ctx: click.Context)Designed to be used as Claude Code's `apiKeyHelper`(https://docs.claude.com/en/docs/claude-code/settings): stdout mustcontain only the token, so all diagnostics go to stderr. The token- expires after `LITELLM_CLI_JWT_EXPIRATION_HOURS` (default 24h); once- expired, run `lite login` again.+ expires after `LITELLM_CLI_JWT_EXPIRATION_HOURS` (default 24h); a+ `lite login --pkce` token renews itself here first, and once a token+ has expired for good, run the same `lite login` command again."""- token_data: Final = load_cli_token(vault=context_secret_vault(ctx))- token_data: Final = load_token()++ vault: Final = context_secret_vault(ctx)++ token_data: Final = load_token(vault=vault)if not token_data:click.echo("Not authenticated. Run 'lite login'.", err=True)sys.exit(1)@@@ -850,37 -853,43 +1000,59 @@@click.echo("Token expired. Run 'lite login' again.", err=True)sys.exit(1)- api_key: Final = token_data.key++ if token_data.get("key") is None:++ click.echo(keychain_unreadable_notice(vault), err=True)++ sys.exit(1)+++ 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)++ else fresh_api_key(++ token_data,++ _renewal_saver(vault),++ requests.Session(),++ reload=_renewal_reader(vault),++ warn=_warn,++ )+ )if not api_key:- click.echo(keychain_unreadable_notice(context_secret_vault(ctx)), err=True)+ click.echo(f"Key expired. Run '{_login_command(renews)}' again.", err=True)sys.exit(1)click.echo(api_key)@click.command(name="whoami")-def whoami():[email protected]_context+def whoami(ctx: click.Context):"""Show current authentication status"""- token_data: Final = load_cli_token(vault=context_secret_vault(ctx))- token_data: Final = load_token()++ vault: Final = context_secret_vault(ctx)++ token_data: Final = load_token(vault=vault)if not token_data:click.echo("Not authenticated. Run 'lite login' to authenticate.")return- click.echo("Authenticated" if token_data.key is not None else "Signed in, but the credential cannot be read")- click.echo(f"User Email: {token_data.user_email or 'Unknown'}")- click.echo(f"User ID: {token_data.user_id or 'Unknown'}")- click.echo(f"User Role: {token_data.user_role or 'Unknown'}")-- # Check if token is still valid (basic timestamp check)- age_hours: Final = (time.time() - token_data.timestamp) / 3600- click.echo("Authenticated")- 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')}")++ key_readable: Final = token_data.get("key") is not None++ click.echo("Authenticated" if key_readable else "Signed in, but the credential cannot be read")++ click.echo(f"User Email: {token_data.get('user_email') or 'Unknown'}")++ click.echo(f"User ID: {token_data.get('user_id') or 'Unknown'}")++ click.echo(f"User Role: {token_data.get('user_role') or 'Unknown'}")+ team_id: Final = token_data.get("team_id")+ if team_id:+ click.echo(f"Team ID: {team_id}")+- timestamp: Final = token_data.get("timestamp", 0)- age_hours: Final = (time.time() - timestamp) / 3600++ stamped: Final = token_data.get("timestamp")++ age_hours: Final = (time.time() - (stamped if isinstance(stamped, (int, float)) else 0.0)) / 3600click.echo(f"Token age: {age_hours:.1f} hours")- if token_data.key is None:- click.echo(keychain_unreadable_notice(context_secret_vault(ctx)))++ if not key_readable:++ click.echo(keychain_unreadable_notice(vault))+- 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.")diff --cc litellm/proxy/client/cli/commands/up.pyindex a0fd4af8f72,80b7a04b75a..b7c02866d6f--- a/litellm/proxy/client/cli/commands/up.py+++ b/litellm/proxy/client/cli/commands/up.py@@@ -14,12 -14,10 +14,12 @@@ from typing import IO, Finaimport clickfrom pydantic import JsonValue, TypeAdapter, ValidationError+from litellm.litellm_core_utils.cli_keyring import SecretVault- from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh, load_cli_token+ from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh+from litellm.litellm_core_utils.private_json import ensure_private_dirfrom .agents import AgentRunError, resolve_api_key, verify_proxy_key- from .auth import context_secret_vault, login-from .auth import CliContextObj, get_stored_api_key, load_token, login++from .auth import CliContextObj, context_secret_vault, get_stored_api_key, load_token, loginfrom .claude_settings import (BACKUP_PATH,CLAUDE_SETTINGS_PATH,@@@ -105,28 -103,41 +105,42 @@@ def restore_claude_settings(settings_pareturn record- def _has_fresh_login(base_url: str, vault: SecretVault) -> bool:- token_data: Final = load_cli_token(vault=vault)- if token_data is None or token_data.key is None or token_data.base_url != base_url:-def _usable_login(api_key: str | None) -> bool:++def _usable_login(api_key: str | None, vault: SecretVault) -> bool:+ if api_key is None:return False- return is_cli_token_fresh(token_data)- token_data: Final = load_token()++ token_data: Final = load_token(vault=vault)+ 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:++def _key_resolved_on_the_way_in(ctx_obj: CliContextObj, base_url: str, vault: SecretVault) -> 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)++ return get_stored_api_key(expected_base_url=base_url, vault=vault)++-def _stored_login_is_pkce() -> bool:- token_data: Final = load_token()- return token_data is not None and "refresh_token" in token_data++def _stored_login_is_pkce(vault: SecretVault) -> bool:++ token_data: Final = load_token(vault=vault)++ return token_data is not None and token_data.get("refresh_token") is not Nonedef _ensure_fresh_login(ctx: click.Context) -> None:- base_url: Final = ctx.obj["base_url"].rstrip("/")+ 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)):+ vault: Final = context_secret_vault(ctx)- if _has_fresh_login(base_url, vault):++ if _usable_login(_key_resolved_on_the_way_in(ctx_obj, base_url, vault), vault):return- pkce: Final = _stored_login_is_pkce()++ pkce: Final = _stored_login_is_pkce(vault)+ 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)- if not _has_fresh_login(base_url, vault):+ ctx.invoke(login, pkce=pkce)- if not _usable_login(get_stored_api_key(expected_base_url=base_url)):++ if not _usable_login(get_stored_api_key(expected_base_url=base_url, vault=vault), vault):raise UpError("Login did not produce a usable token; cannot start `lite up`.")diff --cc litellm/proxy/client/cli/main.pyindex 664bf5a216c,6dba1399acb..2674bf49ff0--- a/litellm/proxy/client/cli/main.py+++ b/litellm/proxy/client/cli/main.py@@@ -93,11 -93,12 +93,16 @@@ def cli(ctx: click.Context, show_versio# 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, vault=context_secret_vault(ctx))+ 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_key++ resolved_api_key: Final = (++ get_stored_api_key(expected_base_url=base_url, vault=context_secret_vault(ctx))++ if api_key_from_token_file++ else api_key++ )ctx.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 fromdiff --cc tests/test_litellm/litellm_core_utils/test_cli_token_utils.pyindex 357d3ae1b10,5593211ba6f..b8ac1987453--- a/tests/test_litellm/litellm_core_utils/test_cli_token_utils.py+++ b/tests/test_litellm/litellm_core_utils/test_cli_token_utils.py@@@ -9,1103 -9,108 +9,1129 @@@ import timimport pytest-from litellm.litellm_core_utils.cli_token_utils import get_litellm_gateway_api_key---class TestCLITokenUtils:- """Test CLI token utility functions"""-- def test_get_litellm_gateway_api_key_success(self):- """Test getting CLI API key when token file exists and is valid"""- token_data = {- "key": "sk-test-cli-key-123",- "user_id": "test-user",- "user_email": "[email protected]",- "timestamp": 1234567890,- }-- with (- patch("os.path.exists", return_value=True),- patch("builtins.open", mock_open(read_data=json.dumps(token_data))),- patch(- "litellm.litellm_core_utils.cli_token_utils.get_cli_token_file_path",- return_value="/test/.litellm/token.json",- ),- ):-- result = get_litellm_gateway_api_key()-- assert result == "sk-test-cli-key-123"-- def test_get_litellm_gateway_api_key_no_file(self):- """Test getting CLI API key when token file doesn't exist"""- with (- patch("os.path.exists", return_value=False),- patch(- "litellm.litellm_core_utils.cli_token_utils.get_cli_token_file_path",- return_value="/test/.litellm/token.json",- ),- ):-- result = get_litellm_gateway_api_key()-- assert result is None-- def test_get_litellm_gateway_api_key_invalid_json(self):- """Test getting CLI API key when token file has invalid JSON"""- with (- patch("os.path.exists", return_value=True),- patch("builtins.open", mock_open(read_data="invalid json")),- patch(- "litellm.litellm_core_utils.cli_token_utils.get_cli_token_file_path",- return_value="/test/.litellm/token.json",- ),- ):-- result = get_litellm_gateway_api_key()-- assert result is None-- def test_get_litellm_gateway_api_key_no_key_field(self):- """Test getting CLI API key when token file exists but has no key field"""- token_data = {- "user_id": "test-user",- "user_email": "[email protected]",- # Missing 'key' field- }-- with (- patch("os.path.exists", return_value=True),- patch("builtins.open", mock_open(read_data=json.dumps(token_data))),- patch(- "litellm.litellm_core_utils.cli_token_utils.get_cli_token_file_path",- return_value="/test/.litellm/token.json",- ),- ):-- result = get_litellm_gateway_api_key()-- assert result is None+from litellm.constants import CLI_JWT_EXPIRATION_HOURS+from litellm.litellm_core_utils.cli_keyring import (+ DISABLE_KEYRING_ENV_VAR,+ KEYRING_ACCOUNT,+ KEYRING_PREFLIGHT_ACCOUNT,+ KEYRING_SERVICE,- KeyringVault,- SecretFound,- SecretMissing,+ KeyringDisabled,+ KeyringDiscardsWrites,+ KeyringNotInstalled,+ KeyringUnreachable,++ KeyringVault,+ SecretErased,++ SecretFound,++ SecretMissing,+ SecretStored,+ SecretStranded,+)+from litellm.litellm_core_utils.cli_token_utils import (+ CliTokenRecord,- CredentialNotRecorded,+ CredentialNotCleared,++ CredentialNotRecorded,+ CredentialNotSaved,+ clear_cli_token,+ get_cli_token_file_path,+ get_litellm_gateway_api_key,+ is_cli_token_fresh,+ load_cli_token,+ save_cli_token,+)++SERVER = "https://proxy.example.com"+OTHER_SERVER = "https://other-proxy.example.com"+++def isolated_home(monkeypatch, tmp_path):+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ return tmp_path+++def _token_file(home):+ return home / ".litellm" / "token.json"+++def _write_legacy_file(home, **overrides):+ payload = {+ "base_url": SERVER,+ "key": "sk-legacy",+ "user_id": "u-1",+ "user_email": "[email protected]",+ "user_role": "cli",+ "timestamp": time.time(),+ **overrides,+ }+ path = _token_file(home)+ path.parent.mkdir(exist_ok=True)+ path.write_text(json.dumps(payload))+ path.chmod(0o600)+ return path+++def _write_metadata_only_file(home):+ """What a post-migration token.json looks like: everything except the secret material."""+ path = _token_file(home)+ path.parent.mkdir(exist_ok=True)+ path.write_text(json.dumps({"base_url": SERVER, "user_id": "u-1", "timestamp": time.time()}))+ path.chmod(0o600)+ return path+++def _blob(base_url=SERVER, key="sk-vault", jwt_token="", timestamp=0.0):+ return json.dumps({"base_url": base_url, "key": key, "jwt_token": jwt_token, "timestamp": timestamp})+++_REAL_MKSTEMP = tempfile.mkstemp+++class _MkstempThatNeedsTheOldFileGone:+ """A disk with exactly one token file's worth of room left on it.++ Staging a replacement needs room for a second file, which is what a full disk refuses. Removing+ the file already there is what gives that room back.+ """++ def __init__(self, path):+ self.path = path++ def __call__(self, *args, **kwargs):+ if self.path.exists():+ raise OSError(errno.ENOSPC, "No space left on device")+ return _REAL_MKSTEMP(*args, **kwargs)+++_REAL_REPLACE = os.replace+++def _refuse_replace(*args, **kwargs):+ raise OSError("device or resource busy")+++class _ReplaceThatStartsRefusing:+ """`os.replace` standing in for a path that cannot be replaced yet: a file another process holds+ open on Windows, a directory that went read-only between staging and the rewrite."""++ def __init__(self):+ self.allowed = False++ def __call__(self, src, dst):+ if not self.allowed:+ raise OSError("device or resource busy")+ _REAL_REPLACE(src, dst)+++class TestGetCliTokenFilePath:+ def test_points_at_the_home_config_file(self, isolated_home):+ assert get_cli_token_file_path() == str(isolated_home / ".litellm" / "token.json")++ def test_does_not_create_the_directory(self, isolated_home):+ """Merely asking for the path must not leave a directory behind, so an SDK import that+ never logs in cannot create a ~/.litellm on someone's machine."""+ get_cli_token_file_path()++ assert not (isolated_home / ".litellm").exists()+++class TestLoadCliToken:+ def test_no_token_file_never_touches_the_keychain(self, isolated_home, secret_vault_factory):+ """The SDK calls this on machines that never ran `lite login`; it must not prompt for+ keychain access there."""+ vault = secret_vault_factory(blob=_blob())++ assert load_cli_token(vault=vault) is None+ assert vault.reads == 0++ def test_secret_comes_from_the_vault_when_the_file_holds_only_metadata(self, isolated_home, secret_vault_factory):+ _write_metadata_only_file(isolated_home)+ vault = secret_vault_factory(blob=_blob(key="sk-from-keychain"))++ record = load_cli_token(vault=vault)++ assert record.key == "sk-from-keychain"+ assert "sk-from-keychain" not in _token_file(isolated_home).read_text()++ def test_jwt_token_round_trips_through_the_vault(self, isolated_home, secret_vault_factory):+ _write_metadata_only_file(isolated_home)+ vault = secret_vault_factory(blob=_blob(key="sk-a", jwt_token="jwt-a"))++ record = load_cli_token(vault=vault)++ assert (record.key, record.jwt_token) == ("sk-a", "jwt-a")++ def test_legacy_plaintext_file_still_authenticates_and_is_migrated(self, isolated_home, secret_vault_factory):+ """A token.json written by an older `lite` keeps working, and reading it moves the secret+ into the keychain and scrubs it from disk."""+ path = _write_legacy_file(isolated_home)+ vault = secret_vault_factory()++ record = load_cli_token(vault=vault)++ assert record.key == "sk-legacy"+ assert json.loads(vault.blob)["key"] == "sk-legacy"+ on_disk = json.loads(path.read_text())+ assert "key" not in on_disk+ assert on_disk["user_email"] == "[email protected]"+ assert stat.S_IMODE(path.stat().st_mode) == 0o600++ def test_migration_tightens_a_world_readable_legacy_file(self, isolated_home, secret_vault_factory):+ """An older `lite`, a loose umask, or a restored backup can leave token.json readable by+ every account on the box. Migrating it must not preserve those permissions."""+ path = _write_legacy_file(isolated_home)+ path.chmod(0o644)++ load_cli_token(vault=secret_vault_factory())++ assert stat.S_IMODE(path.stat().st_mode) == 0o600++ def test_legacy_file_survives_a_vault_that_refuses_to_store(self, isolated_home, secret_vault_factory):+ """Scrubbing the only copy of the secret after a failed keychain write would log the user+ out for good."""+ path = _write_legacy_file(isolated_home)+ before = path.read_text()++ record = load_cli_token(vault=secret_vault_factory(writable=False))++ assert record.key == "sk-legacy"+ assert path.read_text() == before++ def test_a_secret_left_on_disk_outranks_a_stale_keychain_entry(self, isolated_home, secret_vault_factory):+ """A failed keychain write leaves the fresh secret on disk while the vault still holds the+ previous one; the next read must serve the file's secret and move it into the vault, never+ resurrect the stale key or scrub the only copy of the fresh one."""+ path = _write_legacy_file(isolated_home, key="sk-fresh")+ vault = secret_vault_factory(blob=_blob(key="sk-stale"))++ record = load_cli_token(vault=vault)++ assert record.key == "sk-fresh"+ assert json.loads(vault.blob)["key"] == "sk-fresh"+ assert "key" not in json.loads(path.read_text())++ def test_a_login_the_file_could_not_record_is_the_one_that_gets_used(+ self, isolated_home, secret_vault_factory+ ):+ """A login the keychain took and the file could not be pointed at afterwards leaves the+ superseded secret sitting on disk in front of the fresh one. Serving the file's copy would+ put a credential the user just replaced, and may well have just revoked, back into every+ request, and would overwrite the keychain with it on the way past."""+ path = _write_legacy_file(isolated_home, key="sk-superseded", timestamp=1000.0)+ vault = secret_vault_factory(blob=_blob(key="sk-fresh", timestamp=2000.0))++ record = load_cli_token(vault=vault)++ assert record.key == "sk-fresh"+ assert record.timestamp == 2000.0+ assert json.loads(vault.blob)["key"] == "sk-fresh"+ assert "key" not in json.loads(path.read_text())++ def test_a_secret_written_to_disk_after_the_keychain_entry_still_wins(+ self, isolated_home, secret_vault_factory+ ):+ """The other direction of the same rule, which is the common one: a login that fell back to+ the file because the keychain refused it is newer than whatever the keychain kept."""+ path = _write_legacy_file(isolated_home, key="sk-fresh", timestamp=2000.0)+ vault = secret_vault_factory(blob=_blob(key="sk-stale", timestamp=1000.0))++ record = load_cli_token(vault=vault)++ assert record.key == "sk-fresh"+ assert json.loads(vault.blob)["key"] == "sk-fresh"+ assert "key" not in json.loads(path.read_text())++ def test_a_disk_secret_survives_when_the_stale_vault_refuses_the_rewrite(+ self, isolated_home, secret_vault_factory+ ):+ path = _write_legacy_file(isolated_home, key="sk-fresh")+ before = path.read_text()++ record = load_cli_token(vault=secret_vault_factory(blob=_blob(key="sk-stale"), writable=False))++ assert record.key == "sk-fresh"+ assert path.read_text() == before++ def test_legacy_file_survives_an_unreachable_vault_without_write_attempts(+ self, isolated_home, secret_vault_factory+ ):+ path = _write_legacy_file(isolated_home)+ before = path.read_text()+ vault = secret_vault_factory(available=False)++ record = load_cli_token(vault=vault)++ assert record.key == "sk-legacy"+ assert vault.writes == []+ assert path.read_text() == before++ def test_metadata_only_file_with_an_empty_vault_is_not_a_login(self, isolated_home, secret_vault_factory):+ _write_metadata_only_file(isolated_home)++ assert load_cli_token(vault=secret_vault_factory()) is None++ def test_metadata_only_file_with_an_unreachable_vault_reports_a_missing_secret(+ self, isolated_home, secret_vault_factory+ ):+ """The caller needs to tell "never logged in" apart from "locked keychain", so the record+ comes back with no key rather than as None."""+ _write_metadata_only_file(isolated_home)++ record = load_cli_token(vault=secret_vault_factory(available=False))++ assert record.key is None+ assert record.user_id == "u-1"++ def test_a_secret_minted_for_another_server_is_never_handed_out(self, isolated_home, secret_vault_factory):+ _write_metadata_only_file(isolated_home)++ assert load_cli_token(vault=secret_vault_factory(blob=_blob(base_url=OTHER_SERVER))) is None++ def test_a_secret_minted_for_another_server_loses_to_the_file(self, isolated_home, secret_vault_factory):+ _write_legacy_file(isolated_home)+ vault = secret_vault_factory(blob=_blob(base_url=OTHER_SERVER, key="sk-elsewhere"))++ record = load_cli_token(vault=vault)++ assert record.key == "sk-legacy"+ assert json.loads(vault.blob)["key"] == "sk-legacy"++ def test_unreadable_vault_blob_falls_back_to_the_file_secret(self, isolated_home, secret_vault_factory):+ _write_legacy_file(isolated_home)++ record = load_cli_token(vault=secret_vault_factory(blob="not json at all {{{"))++ assert record.key == "sk-legacy"++ def test_a_token_file_that_is_not_text_is_not_a_login(self, isolated_home, secret_vault_factory):+ """A truncated write or a half-synced backup can leave bytes that are not UTF-8 at all.+ Reading them must fail the way an absent file does, not crash every `lite` command."""+ path = _token_file(isolated_home)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b"\xff\xfe not utf-8 at all")++ assert load_cli_token(vault=secret_vault_factory()) is None++ def test_corrupt_token_file_is_not_a_login(self, isolated_home, secret_vault_factory):+ _token_file(isolated_home).parent.mkdir()+ _token_file(isolated_home).write_text("not json at all {{{")++ assert load_cli_token(vault=secret_vault_factory(blob=_blob())) is None+++class TestGetLitellmGatewayApiKey:+ def test_returns_the_vault_secret_when_the_origin_matches(self, isolated_home, secret_vault_factory):+ _write_metadata_only_file(isolated_home)++ key = get_litellm_gateway_api_key(expected_base_url=SERVER, vault=secret_vault_factory(blob=_blob()))++ assert key == "sk-vault"++ def test_trailing_slash_on_the_expected_url_is_normalised(self, isolated_home, secret_vault_factory):+ _write_metadata_only_file(isolated_home)++ key = get_litellm_gateway_api_key(expected_base_url=SERVER + "/", vault=secret_vault_factory(blob=_blob()))++ assert key == "sk-vault"++ def test_origin_mismatch_returns_nothing_without_reading_the_keychain(self, isolated_home, secret_vault_factory):+ """Pointing the SDK at a different server must fail before the keychain is even consulted,+ so a hostile base_url cannot provoke an unlock prompt."""+ _write_legacy_file(isolated_home)+ vault = secret_vault_factory(blob=_blob())++ assert get_litellm_gateway_api_key(expected_base_url=OTHER_SERVER, vault=vault) is None+ assert vault.reads == 0++ def test_no_token_file_returns_nothing(self, isolated_home, secret_vault_factory):+ assert get_litellm_gateway_api_key(vault=secret_vault_factory(blob=_blob())) is None+++class TestSaveCliToken:+ def test_secret_goes_to_the_keychain_and_never_to_the_file(self, isolated_home, secret_vault_factory):+ vault = secret_vault_factory()++ stored = save_cli_token(+ CliTokenRecord(base_url=SERVER, key="sk-new", user_id="u-1", timestamp=time.time()),+ vault=vault,+ )++ assert stored == SecretStored()+ assert "sk-new" not in _token_file(isolated_home).read_text()+ assert json.loads(vault.blob)["key"] == "sk-new"+ assert load_cli_token(vault=vault).key == "sk-new"++ def test_falls_back_to_the_owner_only_file_when_there_is_no_keychain(self, isolated_home, secret_vault_factory):+ stored = save_cli_token(+ CliTokenRecord(base_url=SERVER, key="sk-new", timestamp=time.time()),+ vault=secret_vault_factory(available=False),+ )++ path = _token_file(isolated_home)+ assert stored == KeyringUnreachable()+ assert json.loads(path.read_text())["key"] == "sk-new"+ assert stat.S_IMODE(path.stat().st_mode) == 0o600+ assert list(path.parent.glob(".tmp-*")) == []++ def test_creates_the_config_directory_owner_only(self, isolated_home, secret_vault_factory):+ """A 0755 ~/.litellm lets any local process list, and in the fallback case read, the+ credential's directory."""+ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-new"), vault=secret_vault_factory())++ assert stat.S_IMODE((isolated_home / ".litellm").stat().st_mode) == 0o700++ def test_tightens_a_directory_left_group_readable_by_an_older_cli(self, isolated_home, secret_vault_factory):+ config_dir = isolated_home / ".litellm"+ config_dir.mkdir(mode=0o755)++ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-new"), vault=secret_vault_factory())++ assert stat.S_IMODE(config_dir.stat().st_mode) == 0o700++ def test_a_credential_no_store_would_keep_is_reported_rather_than_raised(+ self, isolated_home, secret_vault_factory, monkeypatch+ ):+ """`lite login` catches whatever escapes here and calls it an authentication failure, which+ is the one thing that did not happen: the proxy minted a real credential. Saying so lets the+ user act on the actual problem instead of retrying a sign-in that already worked."""++ def _explode(*args, **kwargs):+ raise OSError("read-only file system")++ monkeypatch.setattr("litellm.litellm_core_utils.private_json.json.dump", _explode)++ outcome = save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-new"), vault=secret_vault_factory())++ assert isinstance(outcome, CredentialNotSaved)+ assert "read-only file system" in outcome.detail++ def test_a_file_that_will_not_be_written_stops_the_save_before_the_keychain_is_touched(+ self, isolated_home, secret_vault_factory, monkeypatch+ ):+ """The token file is what makes a keychain entry findable again, so it is staged first.+ Handing the keychain a secret and only then finding out that nothing will point at it+ would strand a live credential under a machine with no idea it is there."""+ vault = secret_vault_factory()++ def _explode(*args, **kwargs):+ raise OSError("read-only file system")++ monkeypatch.setattr("litellm.litellm_core_utils.private_json.json.dump", _explode)++ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-new"), vault=vault)++ assert vault.blob is None++ @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores directory permissions")+ def test_a_login_that_cannot_be_saved_leaves_the_working_one_alone(+ self, isolated_home, secret_vault_factory+ ):+ """Signing in again on a machine whose ~/.litellm has gone read-only must not cost the user+ the credential they already had. Overwriting the keychain and then failing to record it, or+ undoing that write afterwards, would take a login that still works out from under them."""+ _write_legacy_file(isolated_home, key=None)+ vault = secret_vault_factory(blob=_blob(key="sk-in-use"))+ path = _token_file(isolated_home)+ path.parent.chmod(0o500)+ try:+ outcome = save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-new"), vault=vault)+ finally:+ path.parent.chmod(0o700)++ assert isinstance(outcome, CredentialNotSaved)+ assert json.loads(vault.blob)["key"] == "sk-in-use"+ assert load_cli_token(vault=vault).key == "sk-in-use"++ def test_a_keychain_write_the_file_cannot_be_pointed_at_is_reported_as_that(+ self, isolated_home, secret_vault_factory+ ):+ """Staging the file can succeed and the replacement still fail, and that is the one path+ where the keychain already took the new secret. Reporting it as a save that kept nothing+ would send the user looking for a credential that is sitting in their keychain."""+ vault = secret_vault_factory()+ path = _token_file(isolated_home)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.mkdir()++ outcome = save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-new"), vault=vault)++ assert isinstance(outcome, CredentialNotRecorded)+ assert json.loads(vault.blob)["key"] == "sk-new"++ def test_the_credential_the_file_cannot_name_is_left_in_the_keychain(+ self, isolated_home, secret_vault_factory+ ):+ """The keychain holds one entry, so the secret that was there went the moment this one+ landed. Taking the new one back out would turn a login this machine may still be able to+ use into no login at all, and it cannot restore the old one either way."""+ vault = secret_vault_factory(blob=_blob(key="sk-in-use"))+ path = _token_file(isolated_home)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.mkdir()++ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-new"), vault=vault)++ assert vault.blob is not None++ def test_a_failed_write_leaves_the_previous_credential_intact(self, isolated_home, secret_vault_factory, monkeypatch):+ path = _write_legacy_file(isolated_home)+ before = path.read_text()++ def _explode(*args, **kwargs):+ raise TypeError("not serialisable")++ monkeypatch.setattr("litellm.litellm_core_utils.private_json.json.dump", _explode)++ with pytest.raises(TypeError):+ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-new"), vault=secret_vault_factory(available=False))++ assert path.read_text() == before+ assert list(path.parent.glob(".tmp-*")) == []++ def test_a_login_is_stamped_past_the_one_it_replaces_even_on_a_clock_that_went_back(+ self, isolated_home, secret_vault_factory+ ):+ """The stamp is what decides the keychain secret against the one on disk, so a login that+ carries an earlier wall clock than the login before it must not be filed as the older of+ the two."""+ _write_legacy_file(isolated_home, key="sk-old", timestamp=2000.0)+ vault = secret_vault_factory()++ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-new", timestamp=1000.0), vault=vault)++ assert json.loads(vault.blob)["timestamp"] > 2000.0++ def test_a_clock_that_went_back_does_not_hand_the_win_to_the_superseded_login(+ self, isolated_home, secret_vault_factory+ ):+ """The disk state a login reports as CredentialNotRecorded: the keychain took the new+ secret and the file still holds the previous one. Reading it back has to produce the login+ that was just made, and an earlier wall clock is no reason to serve the one it replaced."""+ _write_legacy_file(isolated_home, key="sk-superseded", timestamp=2000.0)+ vault = secret_vault_factory()++ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-fresh", timestamp=1000.0), vault=vault)+ _write_legacy_file(isolated_home, key="sk-superseded", timestamp=2000.0)++ assert load_cli_token(vault=vault).key == "sk-fresh"++ def test_a_login_on_a_clock_that_moved_forwards_keeps_its_own_time(+ self, isolated_home, secret_vault_factory+ ):+ """Pinning the stamp above the previous login is only ever a floor. The ordinary case has+ to record when the user actually signed in, because that is what decides expiry."""+ _write_legacy_file(isolated_home, key="sk-old", timestamp=1000.0)+ vault = secret_vault_factory()++ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-new", timestamp=2000.0), vault=vault)++ assert json.loads(vault.blob)["timestamp"] == 2000.0+ assert json.loads(_token_file(isolated_home).read_text())["timestamp"] == 2000.0++ def test_a_login_is_stamped_past_the_keychain_the_file_could_not_keep_up_with(+ self, isolated_home, secret_vault_factory+ ):+ """A login reported as CredentialNotRecorded leaves the keychain holding a later sign-in+ than the file names, so the file alone is no longer the floor. A later login on a clock+ that went back past that keychain entry still has to be the one served."""+ _write_legacy_file(isolated_home, key="sk-superseded", timestamp=1000.0)+ vault = secret_vault_factory(blob=_blob(key="sk-recorded", timestamp=2000.0), writable=False)++ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-fresh", timestamp=1500.0), vault=vault)++ assert load_cli_token(vault=vault).key == "sk-fresh"+++class TestScrubFailure:+ """A keychain that took the secret while the file kept it is the worst of both stores: the+ credential is live, it is in cleartext on disk, and every command reports success."""++ @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores directory permissions")+ def test_a_file_that_will_not_give_its_copy_up_rolls_the_vault_write_back(+ self, isolated_home, secret_vault_factory+ ):+ """Handing the keychain a copy without taking the file's away leaves the credential live in+ two stores instead of one. A directory that permits neither the rewrite nor the delete, a+ root-owned ~/.litellm left behind by a `sudo lite login`, must widen nothing."""+ path = _write_legacy_file(isolated_home)+ vault = secret_vault_factory()+ path.parent.chmod(0o500)+ try:+ record = load_cli_token(vault=vault)+ finally:+ path.parent.chmod(0o700)++ assert record.key == "sk-legacy"+ assert json.loads(path.read_text())["key"] == "sk-legacy"+ assert vault.blob is None++ def test_a_full_disk_stops_the_migration_before_the_keychain_is_handed_anything(+ self, isolated_home, secret_vault_factory, monkeypatch+ ):+ """The scrubbed file is staged first precisely so this is knowable in advance. A disk that+ cannot take the rewrite leaves the credential where it already was, in one store."""+ path = _write_legacy_file(isolated_home)+ vault = secret_vault_factory()++ def _explode(*args, **kwargs):+ raise OSError("no space left on device")++ monkeypatch.setattr("litellm.litellm_core_utils.private_json.json.dump", _explode)++ record = load_cli_token(vault=vault)++ assert record.key == "sk-legacy"+ assert vault.blob is None+ assert json.loads(path.read_text())["key"] == "sk-legacy"+ assert list(path.parent.glob(".tmp-*")) == []++ def test_a_rewrite_the_directory_refuses_is_finished_in_place(+ self, isolated_home, secret_vault_factory, monkeypatch+ ):+ """Staging can succeed and the rewrite still fail afterwards, which is the one window where+ both stores hold the credential. Shortening the file already there needs neither a second+ file nor a cooperative directory, so the move finishes rather than handing the keychain copy+ back and leaving the cleartext where it was."""+ path = _write_legacy_file(isolated_home)+ vault = secret_vault_factory()+ monkeypatch.setattr("litellm.litellm_core_utils.private_json.os.replace", _refuse_replace)++ record = load_cli_token(vault=vault)++ assert record.key == "sk-legacy"+ assert vault.blob is not None+ assert json.loads(path.read_text()).get("key") is None+ assert list(path.parent.glob(".tmp-*")) == []++ @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores file permissions")+ def test_a_rollback_the_keychain_refuses_is_finished_by_the_next_read(+ self, isolated_home, secret_vault_factory, monkeypatch+ ):+ """A file that will take neither a replacement nor an overwrite, and a keychain that will not+ give back what it just took, leave the credential in both stores. Nothing is lost by that,+ and nothing is abandoned either: the next read carries the move the rest of the way, so the+ duplicate outlives only the conditions that caused it."""+ path = _write_legacy_file(isolated_home)+ vault = secret_vault_factory(erasable=False)+ replace = _ReplaceThatStartsRefusing()+ monkeypatch.setattr("litellm.litellm_core_utils.private_json.os.replace", replace)+ path.chmod(0o400)++ assert load_cli_token(vault=vault).key == "sk-legacy"+ assert vault.blob is not None+ assert json.loads(path.read_text())["key"] == "sk-legacy"++ replace.allowed = True+ path.chmod(0o600)++ assert load_cli_token(vault=vault).key == "sk-legacy"+ assert json.loads(path.read_text()).get("key") is None+++class TestClearCliToken:+ def test_removes_the_credential_from_both_stores(self, isolated_home, secret_vault_factory):+ vault = secret_vault_factory()+ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-new"), vault=vault)++ assert clear_cli_token(vault=vault) == SecretErased()+ assert vault.blob is None+ assert not _token_file(isolated_home).exists()+ assert load_cli_token(vault=vault) is None++ def test_reports_a_keychain_that_will_not_release_the_secret(self, isolated_home, secret_vault_factory):+ _write_legacy_file(isolated_home)+ vault = secret_vault_factory(blob=_blob(), erasable=False)++ assert clear_cli_token(vault=vault) == SecretStranded()+ assert not _token_file(isolated_home).exists()++ def test_a_keychain_that_will_not_release_the_secret_still_ends_the_local_login(+ self, isolated_home, secret_vault_factory+ ):+ """The warning this returns says the machine is logged out locally and the keychain entry is+ what is left over. Keeping the file that names that entry makes the first half untrue: every+ later command reads the credential straight back out of the keychain and keeps working."""+ _write_metadata_only_file(isolated_home)+ vault = secret_vault_factory(blob=_blob(), erasable=False)++ assert clear_cli_token(vault=vault) == SecretStranded()+ assert load_cli_token(vault=vault) is None++ @pytest.mark.parametrize(+ "failure", [KeyringDisabled(), KeyringUnreachable(), KeyringNotInstalled()]+ )+ def test_a_secret_in_the_file_is_no_evidence_about_a_keychain_that_exists(+ self, isolated_home, secret_vault_factory, failure+ ):+ """Store a secret in the keychain, sign in again while the keychain is unusable so the new+ secret lands in the file, then log out while it is still unusable. The file now carries its+ own secret and the first login's entry is still there, so reading the file as proof of a+ clean keychain reports a logout that did not happen.++ The three unusable states are the whole of what an erase can answer besides erased and+ stranded; a backend that keeps nothing it is given is something only a write finds out."""+ _write_legacy_file(isolated_home)+ vault = secret_vault_factory(available=False, failure=failure)++ assert clear_cli_token(vault=vault) == failure+ assert json.loads(_token_file(isolated_home).read_text()).get("key") is None++ def test_a_second_logout_still_reports_the_keychain_it_could_not_clear(+ self, isolated_home, secret_vault_factory+ ):+ """The first logout deletes the file and tells the user to run it again once the keychain is+ reachable. If the second run reads that missing file as proof of a clean keychain, the advice+ turns into the very false all-clear it was issued to prevent."""+ _write_metadata_only_file(isolated_home)+ vault = secret_vault_factory(available=False, failure=KeyringUnreachable())++ assert clear_cli_token(vault=vault) == KeyringUnreachable()+ assert clear_cli_token(vault=vault) == KeyringUnreachable()++ def test_logout_from_an_install_without_keyring_does_not_claim_the_keychain_is_clear(+ self, isolated_home, secret_vault_factory+ ):+ """A file holding only metadata put its secret in a keychain by definition. Losing the+ package that reaches it does not take the entry with it, so this cannot report success."""+ _write_metadata_only_file(isolated_home)+ vault = secret_vault_factory(available=False, failure=KeyringNotInstalled())++ assert clear_cli_token(vault=vault) == KeyringNotInstalled()+ assert json.loads(_token_file(isolated_home).read_text()).get("key") is None++ def test_a_logout_that_cannot_clear_the_keychain_keeps_the_record_that_it_has_to(+ self, isolated_home, secret_vault_factory+ ):+ """The file left behind holds no secret. It is what a later run reads to tell a machine with+ a credential it cannot reach apart from one that never had a login, which is the difference+ between warning the user and inventing a credential for them to worry about."""+ _write_metadata_only_file(isolated_home)+ vault = secret_vault_factory(available=False, failure=KeyringUnreachable())++ clear_cli_token(vault=vault)++ assert json.loads(_token_file(isolated_home).read_text()).get("key") is None++ def test_a_logout_that_cannot_clear_the_keychain_still_takes_the_file_secret_away(+ self, isolated_home, secret_vault_factory+ ):+ """Keeping a record of the unreachable keychain must never mean keeping the cleartext copy+ the user just asked to be rid of."""+ _write_legacy_file(isolated_home)+ vault = secret_vault_factory(available=False, failure=KeyringUnreachable())++ clear_cli_token(vault=vault)++ assert "sk-legacy" not in _token_file(isolated_home).read_text()++ def test_a_repeat_logout_never_answers_its_own_warning_with_an_all_clear(+ self, isolated_home, secret_vault_factory+ ):+ """Sign in while the keychain works, sign in again once it has gone out of reach so the+ second secret lands in the file, then log out twice. The first logout cannot say the first+ login's entry is gone, and says so. If the second one reads the file the first one took+ away as proof of a clean keychain, it retracts that warning while the credential behind it+ is still live."""+ vault = secret_vault_factory()+ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-first"), vault=vault)+ vault.available = False+ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-second"), vault=vault)++ assert clear_cli_token(vault=vault) == KeyringUnreachable()+ assert clear_cli_token(vault=vault) == KeyringUnreachable()+ assert vault.blob is not None+ assert "sk-second" not in _token_file(isolated_home).read_text()++ @pytest.mark.parametrize("failure", [KeyringNotInstalled(), KeyringDisabled(), KeyringUnreachable()])+ def test_logging_out_of_a_machine_that_never_logged_in_invents_nothing_to_warn_about(+ self, isolated_home, secret_vault_factory, failure+ ):+ """`lite logout` with no token file has nothing to end. Warning that a credential may be+ stranded in a keychain it cannot check sends the user after something that was never there,+ and `pip install keyring` will not make it appear."""+ vault = secret_vault_factory(available=False, failure=failure)++ assert clear_cli_token(vault=vault) == SecretErased()++ def test_a_file_backed_login_cannot_vouch_for_a_keychain_no_package_can_reach(+ self, isolated_home, secret_vault_factory+ ):+ """Sign in with the keyring package installed, lose the package, then sign in again so the+ second secret lands in the file. The first login's entry outlives both, and the file that+ replaced it holds a secret of its own, which is the shape a logout must not read as proof+ that no keychain was ever involved."""+ vault = secret_vault_factory()+ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-keychain"), vault=vault)+ vault.available = False+ vault.failure = KeyringNotInstalled()+ save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-in-file"), vault=vault)++ assert clear_cli_token(vault=vault) == KeyringNotInstalled()+ assert vault.blob is not None+ assert "sk-in-file" not in _token_file(isolated_home).read_text()++ @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores file permissions")+ def test_a_file_that_gives_up_neither_its_secret_nor_itself_is_reported_not_raised(+ self, isolated_home, secret_vault_factory+ ):+ """A `~/.litellm` gone read-only refuses the staged rewrite and the removal, and a token file+ left read-only with it, as a `sudo lite login` leaves both, refuses the overwrite too. The+ credential is still readable on disk, which is the one thing logging out is for, so it has to+ come back as an answer rather than as a traceback the user has to read the code to+ understand."""+ path = _write_legacy_file(isolated_home)+ path.chmod(0o400)+ path.parent.chmod(0o500)+ try:+ outcome = clear_cli_token(vault=secret_vault_factory())+ finally:+ path.parent.chmod(0o700)+ path.chmod(0o600)++ assert isinstance(outcome, CredentialNotCleared)+ assert json.loads(path.read_text())["key"] == "sk-legacy"++ @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores directory permissions")+ def test_a_directory_that_takes_no_new_file_still_gives_up_the_secret_in_the_old_one(+ self, isolated_home, secret_vault_factory+ ):+ """A read-only `~/.litellm` accepts no replacement token file and no removal of the one it+ has, and still lets that one be shortened. The secret goes, the file stays as the note that+ the keychain went unchecked, and the logout after it warns again instead of reading the gap+ the removal would have left as a clean keychain.++ The key is a realistic length so the file genuinely shrinks: a rewrite in place that leaves+ the tail of the old contents behind hands the next run a file it cannot parse."""+ path = _write_legacy_file(isolated_home, key="sk-" + "a" * 700)+ vault = secret_vault_factory(available=False, failure=KeyringUnreachable())+ path.parent.chmod(0o500)+ try:+ assert clear_cli_token(vault=vault) == KeyringUnreachable()+ assert clear_cli_token(vault=vault) == KeyringUnreachable()+ finally:+ path.parent.chmod(0o700)++ assert json.loads(path.read_text()).get("key") is None++ @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores file permissions")+ def test_a_note_the_logout_had_to_remove_is_written_again_for_the_next_one(+ self, isolated_home, secret_vault_factory, monkeypatch+ ):+ """A full disk refuses the replacement file and a read-only token file refuses the rewrite+ in place, so the only way left to get the secret off disk is to remove the file carrying it.+ That file was also the note saying the keychain went unchecked, and its absence is what the+ next logout would read as a keychain already known to be clean.++ Removing it is what frees the room the replacement was refused for, so the note is written+ again on the way out and the logout after this one still warns."""+ path = _write_legacy_file(isolated_home)+ path.chmod(0o400)+ monkeypatch.setattr(+ "litellm.litellm_core_utils.private_json.tempfile.mkstemp",+ _MkstempThatNeedsTheOldFileGone(path),+ )+ vault = secret_vault_factory(available=False, failure=KeyringUnreachable())++ assert clear_cli_token(vault=vault) == KeyringUnreachable()+ assert clear_cli_token(vault=vault) == KeyringUnreachable()++ assert json.loads(path.read_text()).get("key") is None++ @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores directory permissions")+ def test_a_metadata_file_that_will_not_go_is_not_worth_alarming_the_user_over(+ self, isolated_home, secret_vault_factory+ ):+ """The secret was in the keychain and the keychain gave it up. What is stuck on disk names a+ credential that no longer exists, so the logout it describes really did happen."""+ path = _write_metadata_only_file(isolated_home)+ path.parent.chmod(0o500)+ try:+ outcome = clear_cli_token(vault=secret_vault_factory(blob=_blob()))+ finally:+ path.parent.chmod(0o700)++ assert outcome == SecretErased()++ def test_is_safe_when_nothing_was_ever_stored(self, isolated_home, secret_vault_factory):+ assert clear_cli_token(vault=secret_vault_factory()) == SecretErased()+++class TestIsCliTokenFresh:+ def test_a_just_issued_token_is_fresh(self):+ assert is_cli_token_fresh(CliTokenRecord(timestamp=time.time())) is True++ def test_a_token_past_its_expiry_is_stale(self):+ stale = CliTokenRecord(timestamp=time.time() - (CLI_JWT_EXPIRATION_HOURS + 1) * 3600)++ assert is_cli_token_fresh(stale) is False++ def test_the_buffer_retires_a_token_just_before_it_expires(self):+ almost = CliTokenRecord(timestamp=time.time() - (CLI_JWT_EXPIRATION_HOURS * 3600 - 60))++ assert is_cli_token_fresh(almost, buffer_hours=0.1) is False++ def test_a_stamp_left_in_the_future_keeps_reporting_fresh_until_the_clock_catches_up(self):+ """The stamp both orders the two stores and drives this shortcut, so a store left stamped+ ahead of the clock hands that stamp to the next sign-in and keeps it looking fresh past the+ expiry the gateway will actually enforce. Pinning that here so the shared stamp cannot stop+ being a deliberate trade without this failing first."""+ ahead = CliTokenRecord(timestamp=time.time() + CLI_JWT_EXPIRATION_HOURS * 3600)++ assert is_cli_token_fresh(ahead) is True+++class _FakeKeyringModule:+ def __init__(self, stored=None, *, get_error=None, set_error=None, delete_error=None, discard=False):+ self.stored = stored+ self.get_error = get_error+ self.set_error = set_error+ self.delete_error = delete_error+ self.discard = discard+ self.calls = []++ def get_password(self, service_name, username):+ self.calls.append(("get", service_name, username))+ if self.get_error is not None:+ raise self.get_error+ return self.stored++ def set_password(self, service_name, username, password):+ self.calls.append(("set", service_name, username))+ if self.set_error is not None:+ raise self.set_error+ if self.discard or username != KEYRING_ACCOUNT:+ return+ self.stored = password++ def delete_password(self, service_name, username):+ self.calls.append(("delete", service_name, username))+ if self.delete_error is not None:+ raise self.delete_error+ if username == KEYRING_ACCOUNT:+ self.stored = None+++class _NeverAnsweringKeyringModule(_FakeKeyringModule):+ """A keychain whose writes block instead of returning, the way macOS does under a HOME that+ has no usable login keychain."""++ def __init__(self):+ super().__init__()+ self.blocked = threading.Event()++ def set_password(self, service_name, username, password):+ self.calls.append(("set", service_name, username))+ self.blocked.set()+ threading.Event().wait()+++class _KeychainHeldByABlockedWrite(_NeverAnsweringKeyringModule):+ """The same keychain, plus what the blocked write does to everything after it: the stuck call+ holds the keychain, so every later read blocks behind it too."""++ def get_password(self, service_name, username):+ self.calls.append(("get", service_name, username))+ if self.blocked.is_set():+ threading.Event().wait()+ return self.stored+++def _answered_within(seconds, call):+ answers = []+ worker = threading.Thread(target=lambda: answers.append(call()), daemon=True)+ worker.start()+ worker.join(seconds)+ assert not worker.is_alive(), f"{call.__qualname__} never returned"+ return answers[0]+++def install_fake_keyring(monkeypatch):+ def _install(fake):+ monkeypatch.delenv(DISABLE_KEYRING_ENV_VAR, raising=False)+ monkeypatch.setitem(sys.modules, "keyring", fake)+ return fake++ return _install+++class TestKeyringVault:+ def test_round_trips_through_the_installed_keyring(self, install_fake_keyring):+ fake = install_fake_keyring(_FakeKeyringModule())+ vault = KeyringVault()++ assert vault.write("blob-1") == SecretStored()+ assert vault.read() == SecretFound("blob-1")+ assert vault.erase() == SecretErased()+ assert vault.read() == SecretMissing()+ assert {call[1] for call in fake.calls} == {KEYRING_SERVICE}+ assert {call[2] for call in fake.calls} == {KEYRING_ACCOUNT, KEYRING_PREFLIGHT_ACCOUNT}++ def test_the_kill_switch_reports_no_keychain(self, monkeypatch):+ """`LITELLM_CLI_DISABLE_KEYRING` has to work without importing keyring, because keyring+ caches its backend on first use and cannot be reconfigured later. Erase still fails: a+ credential stored before the switch was set may be in the keychain, and with reads+ disabled `lite logout` cannot verify it is gone, so it must say so instead."""+ monkeypatch.setenv(DISABLE_KEYRING_ENV_VAR, "1")+ vault = KeyringVault()++ assert vault.read() == KeyringDisabled()+ assert vault.write("blob-1") == KeyringDisabled()+ assert vault.erase() == KeyringDisabled()++ def test_an_uninstalled_keyring_library_degrades_to_the_file(self, monkeypatch):+ """keyring is an optional extra, so the SDK must survive its absence rather than raise on+ the hot path. Erase cannot succeed: the entry belongs to the OS and outlives the package,+ so an install without it is not evidence that the keychain is empty."""+ monkeypatch.delenv(DISABLE_KEYRING_ENV_VAR, raising=False)+ monkeypatch.setitem(sys.modules, "keyring", None)+ vault = KeyringVault()++ assert vault.read() == KeyringNotInstalled()+ assert vault.write("blob-1") == KeyringNotInstalled()+ assert vault.erase() == KeyringNotInstalled()++ def test_a_locked_keychain_is_reported_not_raised(self, install_fake_keyring):+ install_fake_keyring(_FakeKeyringModule(get_error=RuntimeError("keyring is locked")))++ assert KeyringVault().read() == KeyringUnreachable()++ def test_a_refused_write_is_reported_not_raised(self, install_fake_keyring):+ install_fake_keyring(_FakeKeyringModule(set_error=RuntimeError("no backend")))++ assert KeyringVault().write("blob-1") == KeyringUnreachable()++ def test_a_refused_delete_is_reported_so_logout_can_warn(self, install_fake_keyring):+ install_fake_keyring(_FakeKeyringModule(stored="blob-1", delete_error=RuntimeError("locked")))++ assert KeyringVault().erase() == SecretStranded()++ def test_a_backend_that_keeps_nothing_is_not_a_successful_write(self, install_fake_keyring):+ """keyring's null backend accepts every write, stores nothing, and raises nothing to say so.+ Taking its silence for success is how a credential gets deleted: the caller drops its own+ copy on our word. Only reading the value back tells the two apart."""+ fake = install_fake_keyring(_FakeKeyringModule(discard=True))++ assert KeyringVault().write("blob-1") == KeyringDiscardsWrites()+ assert fake.stored is None++ def test_a_keychain_that_never_answers_does_not_hang_the_login(self, install_fake_keyring):+ """macOS derives the login keychain from `$HOME`, and `set_password` under a HOME with no+ usable one blocks forever with no timeout of its own. Containers, CI images, `sudo -H`, and+ service accounts all run there, and `lite login` never touched a keychain before this, so a+ sign-in that simply never returns would be a new way for it to fail."""+ fake = install_fake_keyring(_NeverAnsweringKeyringModule())+ vault = KeyringVault(preflight_timeout_seconds=0.2)++ started = time.monotonic()+ outcome = vault.write("blob-1")++ assert outcome == KeyringUnreachable()+ assert time.monotonic() - started < 5+ assert fake.blocked.is_set()++ def test_a_keychain_that_never_answers_is_never_handed_the_credential(self, install_fake_keyring):+ """Giving up on the write is only safe if the secret was never the thing being written. A+ blocked call can still land later, and a keychain copy nobody waited for would sit beside+ the file copy the user was told about."""+ fake = install_fake_keyring(_NeverAnsweringKeyringModule())++ KeyringVault(preflight_timeout_seconds=0.2).write("blob-1")++ assert [call[2] for call in fake.calls] == [KEYRING_PREFLIGHT_ACCOUNT]++ def test_a_keychain_that_stopped_answering_is_not_asked_again(self, install_fake_keyring):+ """The write that timed out is still holding the keychain when we give up on it, so the+ call after it is the one that hangs, and read has nothing to time out against. Anything+ resolving the credential more than once in a process hits that: an SDK client built twice+ pays the pre-flight timeout on the first build and never returns from the second."""+ install_fake_keyring(_KeychainHeldByABlockedWrite())+ vault = KeyringVault(preflight_timeout_seconds=0.05)++ assert vault.write("blob-1") == KeyringUnreachable()++ assert _answered_within(5, vault.read) == KeyringUnreachable()+ assert _answered_within(5, vault.erase) == KeyringUnreachable()+ assert _answered_within(5, lambda: vault.write("blob-2")) == KeyringUnreachable()++ def test_a_keychain_that_stopped_answering_leaves_the_credential_in_the_file(+ self, isolated_home, install_fake_keyring+ ):+ """The end of the same story: giving up on the keychain has to leave a login that still+ works, and loading it back must not go asking the keychain that already stopped answering."""+ install_fake_keyring(_KeychainHeldByABlockedWrite())+ vault = KeyringVault(preflight_timeout_seconds=0.05)++ outcome = save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-only-copy"), vault=vault)++ assert outcome == KeyringUnreachable()+ assert _answered_within(5, lambda: load_cli_token(vault=vault)).key == "sk-only-copy"++ def test_a_login_survives_a_keychain_that_never_answers(self, isolated_home, install_fake_keyring):+ """The end of the same story: the credential still has to be usable afterwards."""+ install_fake_keyring(_NeverAnsweringKeyringModule())++ outcome = save_cli_token(+ CliTokenRecord(base_url=SERVER, key="sk-only-copy"),+ vault=KeyringVault(preflight_timeout_seconds=0.2),+ )++ assert outcome == KeyringUnreachable()+ assert json.loads(_token_file(isolated_home).read_text())["key"] == "sk-only-copy"++ def test_the_real_null_backend_is_rejected(self, monkeypatch):+ """Pinned against the actual library rather than the double above, because the whole risk is+ that upstream's no-op write looks exactly like a successful one."""+ keyring = pytest.importorskip("keyring")+ null_backend = pytest.importorskip("keyring.backends.null")+ monkeypatch.delenv(DISABLE_KEYRING_ENV_VAR, raising=False)+ previous = keyring.get_keyring()+ keyring.set_keyring(null_backend.Keyring())+ try:+ assert KeyringVault().write("blob-1") == KeyringDiscardsWrites()+ finally:+ keyring.set_keyring(previous)++ def test_a_credential_survives_a_backend_that_keeps_nothing(+ self, isolated_home, install_fake_keyring+ ):+ """The end of the same story: the credential must still be usable afterwards. Reporting the+ discard is only worth anything if the token file then keeps the copy the keychain refused."""+ install_fake_keyring(_FakeKeyringModule(discard=True))++ outcome = save_cli_token(CliTokenRecord(base_url=SERVER, key="sk-only-copy"))++ assert outcome == KeyringDiscardsWrites()+ assert json.loads(_token_file(isolated_home).read_text())["key"] == "sk-only-copy"+ assert load_cli_token().key == "sk-only-copy"++ def test_erasing_a_locked_keychain_is_a_failure(self, install_fake_keyring):+ install_fake_keyring(_FakeKeyringModule(get_error=RuntimeError("locked")))++ assert KeyringVault().erase() == KeyringUnreachable()+++ class TestIsCliTokenFreshWithExpiresAt:+ """A ``lite login --pkce`` record carries the proxy's own ``expires_at``, which wins+ over the age-based guess made from ``timestamp``."""++ def test_future_expiry_is_fresh(self):+ from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh++ assert is_cli_token_fresh({"expires_at": time.time() + 3600, "timestamp": 0}) is True++ def test_expiry_inside_the_buffer_is_stale(self):+ from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh++ assert is_cli_token_fresh({"expires_at": time.time() + 100}) is False+ assert is_cli_token_fresh({"expires_at": time.time() + 100}, buffer_hours=0) is True++ def test_past_expiry_is_stale_even_with_a_fresh_timestamp(self):+ from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh++ assert is_cli_token_fresh({"expires_at": time.time() - 1, "timestamp": time.time()}) is False++ def test_non_numeric_expiry_falls_back_to_the_timestamp(self):+ from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh++ assert is_cli_token_fresh({"expires_at": "soon", "timestamp": time.time()}) is Truediff --cc tests/test_litellm/proxy/client/cli/test_auth_commands.pyindex 4f44514167c,c494cf8b45b..eb40f54a1f3--- a/tests/test_litellm/proxy/client/cli/test_auth_commands.py+++ b/tests/test_litellm/proxy/client/cli/test_auth_commands.py@@@ -13,16 -13,12 +13,17 @@@ import pytesfrom click.testing import CliRunnerfrom litellm.constants import CLI_JWT_EXPIRATION_HOURS+from litellm.litellm_core_utils.cli_keyring import (+ DISABLE_KEYRING_ENV_VAR,+ KeyringDisabled,+ KeyringNotInstalled,++ SecretErased,++ SecretStored,+)+from litellm.litellm_core_utils.cli_token_utils import CliTokenRecord, save_cli_tokenfrom litellm.proxy.client.cli import clifrom litellm.proxy.client.cli.commands.auth import (- DISABLE_KEYRING_ENV_VAR,- clear_token,get_stored_api_key,- get_token_file_path,- load_token,login,logout,print_token,@@@ -257,6 -381,40 +264,40 @@@ class TestLoginCommand"""Setup for each test"""self.runner = CliRunner()+ def test_login_replaces_a_pkce_record_and_revokes_its_refresh_token(self):+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {+ "status": "ready",+ "key": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.test.jwt",+ "user_id": "test-user-123",+ "team_id": "team-1",+ "teams": ["team-1"],+ }+ _FakeSession.instances.clear()++ with (+ patch("webbrowser.open"),+ patch("requests.post", return_value=_mock_cli_sso_start_response()),+ patch("requests.get", return_value=mock_response),+ patch("litellm.proxy.client.cli.commands.auth.requests.Session", _FakeSession),+ patch("litellm.proxy.client.cli.commands.auth.load_token", return_value=_pkce_record()),- patch("litellm.proxy.client.cli.commands.auth.save_token") as mock_save,++ patch("litellm.proxy.client.cli.commands.auth.save_token", return_value=SecretStored()) as mock_save,+ patch("litellm.proxy.client.cli.interface.show_commands"),+ ):+ result = self.runner.invoke(login, obj={"base_url": "https://test.example.com"})++ assert result.exit_code == 0, result.output+ assert "Login successful!" in result.output+ assert "Could not revoke" not in result.output+ assert mock_save.call_args.args[0]["key"] == "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.test.jwt"+ assert _FakeSession.instances[0].posts == [+ (+ f"{PKCE_BASE_URL}/revoke",+ {"token": "llm_srefresh_old", "token_type_hint": "refresh_token", "client_id": "llm_dcrc_abc"},+ )+ ]+def test_login_success(self):"""Test successful login flow with single team (JWT generated immediately)"""mock_context = Mock()@@@ -614,14 -666,63 +655,66 @@@ class TestWhoamiCommandassert "Authenticated" in result.outputassert "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 = {++ "key": "sk-cli",+ "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 = {++ "key": "sk-cli",+ "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_expired_pkce_record_that_could_not_be_renewed_asks_for_a_new_pkce_login(self):+ token_data = {++ "key": "sk-cli",+ "user_id": "user-1",+ "team_id": "team-alpha",+ "timestamp": time.time() - 3600,+ "expires_at": time.time() - 60,+ "refresh_token": "llm_srefresh_spent",+ }++ 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 "Key expired. Run 'lite login --pkce' again" in result.output+ assert "renewed on next use" not in result.output+def test_whoami_no_timestamp(self):"""Test whoami with token missing timestamp"""- token_data = {- "user_email": "[email protected]",- "user_id": "test-user-123",- "user_role": "admin",- # Missing timestamp- }+ token_data = CliTokenRecord(+ user_email="[email protected]",+ user_id="test-user-123",+ user_role="admin",+ key="sk-live",+ )with (patch(@@@ -1309,3 -1195,486 +1402,487 @@@ class TestLoginConfigClaudeassert "could not configure Claude Code" in result.outputassert "invalid JSON" in result.outputassert "Authentication failed" not in result.output+++ class _FakeHttpResponse:+ def __init__(self, status_code, payload):+ self.status_code = status_code+ self._payload = payload+ self.text = json.dumps(payload)+ self.content = self.text.encode()++ def json(self):+ return self._payload+++ class _FakeSession:+ """Stands in for ``requests.Session`` so the CLI's refresh and revoke calls can be observed."""++ instances = []++ def __init__(self):+ self.posts = []+ self.response = _FakeHttpResponse(200, {})+ _FakeSession.instances.append(self)++ def post(self, url, *, data=None, json=None, timeout, allow_redirects):+ self.posts.append((url, data))+ return self.response++ def get(self, url, *, timeout):+ raise AssertionError(f"unexpected GET {url}")+++ PKCE_BASE_URL = "https://llm.example.com"+ PKCE_TOKEN_RESPONSE = {+ "access_token": "sk-cli-rotated",+ "token_type": "Bearer",+ "expires_in": 3600,+ "refresh_token": "llm_srefresh_rotated",+ "user_id": "u1",+ "team_id": "team-b",+ }+++ def _pkce_record(**overrides):+ return {+ "base_url": PKCE_BASE_URL,+ "key": "sk-cli-old",+ "user_id": "u1",+ "user_email": "unknown",+ "user_role": "cli",+ "auth_header_name": "Authorization",+ "jwt_token": "",+ "timestamp": time.time(),+ "expires_at": time.time() + 30,+ "refresh_token": "llm_srefresh_old",+ "client_id": "llm_dcrc_abc",+ "token_endpoint": f"{PKCE_BASE_URL}/token",+ "revocation_endpoint": f"{PKCE_BASE_URL}/revoke",+ "resource": PKCE_BASE_URL,+ "team_id": "team-b",+ **overrides,+ }+++ def _pkce_credential():+ from litellm.proxy.client.cli.commands.pkce_login import PkceCredential++ return PkceCredential(+ access_token="sk-cli-fresh",+ refresh_token="llm_srefresh_fresh",+ expires_at=time.time() + 3600,+ client_id="llm_dcrc_abc",+ token_endpoint=f"{PKCE_BASE_URL}/token",+ revocation_endpoint=f"{PKCE_BASE_URL}/revoke",+ resource=PKCE_BASE_URL,+ user_id="u1",+ team_id="team-b",+ )+++ class TestPkceLoginCommand:+ """``lite login --pkce`` swaps the proxy-mediated SSO poll for the browser PKCE flow."""++ @pytest.fixture(autouse=True)+ def isolated_home(self, monkeypatch, tmp_path):+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ return tmp_path++ def setup_method(self):+ self.runner = CliRunner()+ _FakeSession.instances.clear()++ def test_pkce_login_saves_the_new_record_then_revokes_the_refresh_token_it_replaced(self):+ posts_when_saved = []+++ def record_posts(record, **_):++ posts_when_saved.append(list(_FakeSession.instances[0].posts))++ return SecretStored()+++ with (+ patch("litellm.proxy.client.cli.commands.auth.run_pkce_login", return_value=_pkce_credential()),+ patch("litellm.proxy.client.cli.commands.auth.load_token", return_value=_pkce_record(team_id="team-a")),- patch(- "litellm.proxy.client.cli.commands.auth.save_token",- side_effect=lambda record: posts_when_saved.append(list(_FakeSession.instances[0].posts)),- ) as save,++ patch("litellm.proxy.client.cli.commands.auth.save_token", side_effect=record_posts) as save,+ patch("litellm.proxy.client.cli.commands.auth.requests.Session", _FakeSession),+ patch("litellm.proxy.client.cli.interface.show_commands"),+ ):+ result = self.runner.invoke(login, ["--pkce"], obj={"base_url": PKCE_BASE_URL})++ assert result.exit_code == 0, result.output+ assert "Login successful!" in result.output+ assert "Could not revoke" not in result.output+ assert save.call_args.args[0]["refresh_token"] == "llm_srefresh_fresh"+ assert save.call_args.args[0]["team_id"] == "team-b"+ assert posts_when_saved == [[]]+ assert _FakeSession.instances[0].posts == [+ (+ f"{PKCE_BASE_URL}/revoke",+ {"token": "llm_srefresh_old", "token_type_hint": "refresh_token", "client_id": "llm_dcrc_abc"},+ )+ ]++ def test_pkce_login_keeps_the_new_record_when_the_old_refresh_token_cannot_be_revoked(self):+ class _FailingSession(_FakeSession):+ def __init__(self):+ super().__init__()+ self.response = _FakeHttpResponse(503, {"error": "temporarily_unavailable"})++ with (+ patch("litellm.proxy.client.cli.commands.auth.run_pkce_login", return_value=_pkce_credential()),+ 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.save_token", return_value=SecretStored()) as save,+ patch("litellm.proxy.client.cli.commands.auth.requests.Session", _FailingSession),+ patch("litellm.proxy.client.cli.interface.show_commands"),+ ):+ result = self.runner.invoke(login, ["--pkce"], obj={"base_url": PKCE_BASE_URL})++ assert result.exit_code == 0, result.output+ assert (+ "Could not revoke the previous login's refresh token on the proxy (revocation failed with 503"+ in result.output+ )+ assert "Login successful!" in result.output+ assert save.call_args.args[0]["refresh_token"] == "llm_srefresh_fresh"++ @pytest.mark.parametrize("previous", [None, {"key": "sk-classic", "base_url": PKCE_BASE_URL}])+ def test_pkce_login_without_a_previous_refresh_token_makes_no_revocation_request(self, previous):+ with (+ patch("litellm.proxy.client.cli.commands.auth.run_pkce_login", return_value=_pkce_credential()),+ patch("litellm.proxy.client.cli.commands.auth.load_token", return_value=previous),- patch("litellm.proxy.client.cli.commands.auth.save_token") as save,++ patch("litellm.proxy.client.cli.commands.auth.save_token", return_value=SecretStored()) as save,+ patch("litellm.proxy.client.cli.commands.auth.requests.Session", _FakeSession),+ patch("litellm.proxy.client.cli.interface.show_commands"),+ ):+ result = self.runner.invoke(login, ["--pkce"], obj={"base_url": PKCE_BASE_URL})++ assert result.exit_code == 0, result.output+ assert "Login successful!" in result.output+ save.assert_called_once()+ assert _FakeSession.instances[0].posts == []++ def test_pkce_login_saves_the_refreshable_record_and_skips_the_sso_poll(self):+ with (+ patch("litellm.proxy.client.cli.commands.auth.run_pkce_login", return_value=_pkce_credential()) as run,+ patch("litellm.proxy.client.cli.commands.auth._start_cli_sso_flow") as sso_start,- patch("litellm.proxy.client.cli.commands.auth.save_token") as save,++ patch("litellm.proxy.client.cli.commands.auth.save_token", return_value=SecretStored()) as save,+ patch("litellm.proxy.client.cli.interface.show_commands"),+ ):+ result = self.runner.invoke(login, ["--pkce"], obj={"base_url": f"{PKCE_BASE_URL}/"})++ assert result.exit_code == 0, result.output+ assert "Login successful!" in result.output+ assert "JWT Token: sk-cli-fresh..." in result.output+ sso_start.assert_not_called()+ assert run.call_args.args[0] == f"{PKCE_BASE_URL}/"+ saved = save.call_args.args[0]+ assert saved["base_url"] == PKCE_BASE_URL+ assert saved["key"] == "sk-cli-fresh"+ assert saved["refresh_token"] == "llm_srefresh_fresh"+ assert saved["client_id"] == "llm_dcrc_abc"+ assert saved["token_endpoint"] == f"{PKCE_BASE_URL}/token"+ assert saved["revocation_endpoint"] == f"{PKCE_BASE_URL}/revoke"+ assert saved["resource"] == PKCE_BASE_URL+ assert saved["user_id"] == "u1"+ assert saved["team_id"] == "team-b"++ def test_pkce_login_failure_is_reported_and_nothing_is_saved(self):+ from litellm.proxy.client.cli.commands.pkce_login import PkceFailure++ with (+ patch(+ "litellm.proxy.client.cli.commands.auth.run_pkce_login",+ return_value=PkceFailure("sign-in was not approved (access_denied): no details"),+ ),- patch("litellm.proxy.client.cli.commands.auth.save_token") as save,++ patch("litellm.proxy.client.cli.commands.auth.save_token", return_value=SecretStored()) as save,+ ):+ result = self.runner.invoke(login, ["--pkce"], obj={"base_url": PKCE_BASE_URL})++ assert result.exit_code == 0+ assert "Authentication failed: sign-in was not approved (access_denied): no details" in result.output+ save.assert_not_called()++ def test_login_without_the_flag_never_touches_the_pkce_flow(self):+ with (+ patch("litellm.proxy.client.cli.commands.auth.run_pkce_login") as run,+ patch("litellm.proxy.client.cli.commands.auth._start_cli_sso_flow", side_effect=KeyboardInterrupt),+ ):+ result = self.runner.invoke(login, obj={"base_url": PKCE_BASE_URL})++ assert "cancelled" in result.output+ run.assert_not_called()+++ class TestPkceLogoutCommand:+ def setup_method(self):+ self.runner = CliRunner()+ _FakeSession.instances.clear()++ def test_logout_revokes_the_refresh_token_before_clearing(self):+ with (+ patch("litellm.proxy.client.cli.commands.auth.load_token", return_value=_pkce_record()),- patch("litellm.proxy.client.cli.commands.auth.clear_token") as clear,++ patch("litellm.proxy.client.cli.commands.auth.clear_cli_token", return_value=SecretErased()) as clear,+ patch("litellm.proxy.client.cli.commands.auth.requests.Session", _FakeSession),+ ):+ result = self.runner.invoke(logout)++ assert result.exit_code == 0+ assert result.output == "Logged out successfully. Authentication token cleared.\n"+ clear.assert_called_once()+ assert _FakeSession.instances[0].posts == [+ (+ f"{PKCE_BASE_URL}/revoke",+ {"token": "llm_srefresh_old", "token_type_hint": "refresh_token", "client_id": "llm_dcrc_abc"},+ )+ ]++ def test_logout_still_clears_when_the_proxy_refuses_the_revocation(self):+ class _RefusingSession(_FakeSession):+ def __init__(self):+ super().__init__()+ self.response = _FakeHttpResponse(401, {"error": "invalid_client"})++ with (+ patch("litellm.proxy.client.cli.commands.auth.load_token", return_value=_pkce_record()),- patch("litellm.proxy.client.cli.commands.auth.clear_token") as clear,++ patch("litellm.proxy.client.cli.commands.auth.clear_cli_token", return_value=SecretErased()) as clear,+ patch("litellm.proxy.client.cli.commands.auth.requests.Session", _RefusingSession),+ ):+ result = self.runner.invoke(logout)++ assert result.exit_code == 0+ assert (+ "Could not revoke the refresh token on the proxy (revocation failed with 401: invalid_client); "+ "it expires on its own." in result.output+ )+ assert "Logged out successfully" in result.output+ clear.assert_called_once()++ def test_logout_keeps_the_record_when_the_proxy_cannot_record_the_revocation(self):+ class _UnavailableSession(_FakeSession):+ def __init__(self):+ super().__init__()+ self.response = _FakeHttpResponse(+ 503, {"error": "temporarily_unavailable", "error_description": "the record is unavailable"}+ )++ with (+ patch("litellm.proxy.client.cli.commands.auth.load_token", return_value=_pkce_record()),- patch("litellm.proxy.client.cli.commands.auth.clear_token") as clear,++ patch("litellm.proxy.client.cli.commands.auth.clear_cli_token", return_value=SecretErased()) as clear,+ patch("litellm.proxy.client.cli.commands.auth.requests.Session", _UnavailableSession),+ ):+ result = self.runner.invoke(logout)++ assert result.exit_code == 1+ assert (+ "Error: The proxy could not record the revocation (revocation failed with 503: the record is unavailable). "+ "Nothing was cleared; run `lite logout` again shortly." in result.output+ )+ assert "Logged out successfully" not in result.output+ clear.assert_not_called()++ def test_logout_of_a_classic_token_makes_no_request(self):+ with (+ patch("litellm.proxy.client.cli.commands.auth.load_token", return_value={"key": "sk-classic"}),- patch("litellm.proxy.client.cli.commands.auth.clear_token") as clear,++ patch("litellm.proxy.client.cli.commands.auth.clear_cli_token", return_value=SecretErased()) as clear,+ patch("litellm.proxy.client.cli.commands.auth.requests.Session", _FakeSession),+ ):+ result = self.runner.invoke(logout)++ assert result.output == "Logged out successfully. Authentication token cleared.\n"+ clear.assert_called_once()+ assert _FakeSession.instances[0].posts == []+++ class TestPkcePrintToken:+ """``lite print-token`` is Claude Code's apiKeyHelper, so a near-expiry PKCE key must be+ refreshed silently and stdout must carry nothing but the key."""++ def setup_method(self):+ self.runner = CliRunner()+ _FakeSession.instances.clear()++ def test_print_token_refreshes_a_near_expiry_key_and_saves_the_rotation(self):+ 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(print_token, obj={})++ assert result.exit_code == 0, result.output+ assert result.stdout == "sk-cli-rotated\n"+ assert _FakeSession.instances[0].posts[0][0] == f"{PKCE_BASE_URL}/token"+ assert _FakeSession.instances[0].posts[0][1]["refresh_token"] == "llm_srefresh_old"+ saved = save.call_args.args[0]+ assert saved["key"] == "sk-cli-rotated"+ assert saved["refresh_token"] == "llm_srefresh_rotated"++ def test_print_token_prints_a_fresh_pkce_key_without_a_request(self):+ with (+ patch(+ "litellm.proxy.client.cli.commands.auth.load_token",+ return_value=_pkce_record(expires_at=time.time() + 3600),+ ),+ patch("litellm.proxy.client.cli.commands.auth.requests.Session", _FakeSession),+ ):+ result = self.runner.invoke(print_token, obj={})++ assert result.stdout == "sk-cli-old\n"+ assert _FakeSession.instances[0].posts == []++ def test_print_token_fails_when_the_key_expired_and_refresh_is_refused(self):+ class _RefusingSession(_FakeSession):+ def __init__(self):+ super().__init__()+ self.response = _FakeHttpResponse(400, {"error": "invalid_grant"})++ 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(print_token, obj={})++ assert result.exit_code == 1+ assert result.stdout == ""+ assert "Could not renew the key: token request failed with 400: invalid_grant" in result.output+ assert "Key expired. Run 'lite login --pkce' again." in result.output+ assert "Run 'lite login' again" not in result.output+ save.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_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))+ 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(+ "litellm.proxy.client.cli.commands.auth.load_token",+ return_value={"key": "sk-classic", "timestamp": time.time() - (CLI_JWT_EXPIRATION_HOURS + 1) * 3600},+ ),+ patch("litellm.proxy.client.cli.commands.auth.requests.Session", _FakeSession),+ ):+ result = self.runner.invoke(print_token, obj={})++ assert result.exit_code == 1+ assert "Token expired" in result.output+ assert _FakeSession.instances == []+++ class TestGetStoredApiKeyRefresh:+ def test_get_stored_api_key_refreshes_a_near_expiry_pkce_key(self):+ _FakeSession.instances.clear()++ 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),+ ):+ assert get_stored_api_key(PKCE_BASE_URL) == "sk-cli-rotated"+ assert get_stored_api_key("https://other.example.com") is None++ assert save.call_count == 1+ assert len(_FakeSession.instances) == 1++ def test_get_stored_api_key_reports_a_refused_renewal_on_stderr_and_keeps_the_valid_key(self, capsys):+ _FakeSession.instances.clear()++ class _RefusingSession(_FakeSession):+ def __init__(self):+ super().__init__()+ self.response = _FakeHttpResponse(503, {"error": "temporarily_unavailable"})++ 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", _RefusingSession),+ ):+ assert get_stored_api_key(PKCE_BASE_URL) == "sk-cli-old"++ captured = capsys.readouterr()+ assert captured.out == ""+ assert captured.err == "Could not renew the key: token request failed with 503: temporarily_unavailable\n"+ save.assert_not_called()diff --cc tests/test_litellm/proxy/client/cli/test_up_commands.pyindex a8d81f1c4bb,264de328c37..9958286884b--- a/tests/test_litellm/proxy/client/cli/test_up_commands.py+++ b/tests/test_litellm/proxy/client/cli/test_up_commands.py@@@ -221,8 -221,56 +221,56 @@@ def _make_ctx(base_url)return click.Context(click.Command("test"), obj={"base_url": base_url})- def _token(key, base_url):- return CliTokenRecord(key=key, 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",+ "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, "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):++ 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_callsclass TestEnsureFreshLogin:@@@ -260,38 -299,92 +299,105 @@@_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_forces_a_fresh_login_when_the_cached_token_has_no_readable_key(self, monkeypatch):+ monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: True)- tokens = iter(- [- _token(None, "http://proxy-a:4000"),- _token("sk-a", "http://proxy-a:4000"),- ]- )- monkeypatch.setattr(up_module, "load_cli_token", lambda **_: next(tokens))++ store = _FakeTokenStore(monkeypatch, {"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-a", "base_url": "http://proxy-a:4000"}, "sk-a"),++ )++ _ensure_fresh_login(_make_ctx("http://proxy-a:4000"))+- assert login_calls == ["http://proxy-a:4000"]++ assert login_calls == [("http://proxy-a:4000", False)]+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_cli_token", lambda **_: _token("sk-a", "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"))++ 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):