The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(cli): name why a login fell back to the token file
mateo-berri01add582982a
diff --git a/litellm/litellm_core_utils/cli_keyring.py b/litellm/litellm_core_utils/cli_keyring.pyindex fcbf5ada55a..b19b3d3bc83 100644--- a/litellm/litellm_core_utils/cli_keyring.py+++ b/litellm/litellm_core_utils/cli_keyring.py@@ -5,9 +5,9 @@ SDK-level access to the OS keychain (macOS Keychain, Windows Credential Manager,Linux Secret Service) that holds the credential minted by `lite login`.The `keyring` package is optional and imported lazily, so importing this module-never pulls it in. Every failure is returned as a value: a machine with no-keychain, or one whose keychain is locked, must degrade to the token file rather-than break `lite` or the SDK.+never pulls it in. Every failure is returned as a value, naming which of the+three ways the keychain can be out of reach applies, so callers can degrade to+the token file and tell the user what to do about it."""import os@@ -32,11 +32,28 @@ class SecretMissing:@dataclass(frozen=True, slots=True)-class SecretUnavailable:+class SecretStored:pass-SecretRead: TypeAlias = SecretFound | SecretMissing | SecretUnavailable+@dataclass(frozen=True, slots=True)+class KeyringNotInstalled:+ pass+++@dataclass(frozen=True, slots=True)+class KeyringDisabled:+ pass+++@dataclass(frozen=True, slots=True)+class KeyringUnreachable:+ pass+++KeyringUnusable: TypeAlias = KeyringNotInstalled | KeyringDisabled | KeyringUnreachable+SecretRead: TypeAlias = SecretFound | SecretMissing | KeyringUnusable+SecretWrite: TypeAlias = SecretStored | KeyringUnusableclass SecretVault(Protocol):@@ -44,7 +61,7 @@ class SecretVault(Protocol):def read(self) -> SecretRead: ...- def write(self, blob: str) -> bool: ...+ def write(self, blob: str) -> SecretWrite: ...def erase(self) -> bool: ...@@ -69,8 +86,11 @@ def _import_keyring() -> KeyringApi | None:return keyring-def _keyring_api() -> KeyringApi | None:- return None if _keyring_disabled() else _import_keyring()+def _keyring_api() -> KeyringApi | KeyringNotInstalled | KeyringDisabled:+ if _keyring_disabled():+ return KeyringDisabled()+ api: Final = _import_keyring()+ return KeyringNotInstalled() if api is None else api@dataclass(frozen=True, slots=True)@@ -79,23 +99,23 @@ class KeyringVault:def read(self) -> SecretRead:api: Final = _keyring_api()- if api is None:- return SecretUnavailable()+ if isinstance(api, (KeyringNotInstalled, KeyringDisabled)):+ return apitry:blob: Final = api.get_password(KEYRING_SERVICE, KEYRING_ACCOUNT)except Exception: # noqa: BLE001 # backends raise outside keyring.errors; never break the SDK- return SecretUnavailable()+ return KeyringUnreachable()return SecretMissing() if blob is None else SecretFound(blob)- def write(self, blob: str) -> bool:+ def write(self, blob: str) -> SecretWrite:api: Final = _keyring_api()- if api is None:- return False+ if isinstance(api, (KeyringNotInstalled, KeyringDisabled)):+ return apitry:api.set_password(KEYRING_SERVICE, KEYRING_ACCOUNT, blob)except Exception: # noqa: BLE001 # a keychain that refuses the write falls back to the token file- return False- return True+ return KeyringUnreachable()+ return SecretStored()def erase(self) -> bool:"""Whether the keychain is guaranteed to hold no credential afterwards.@@ -108,7 +128,7 @@ class KeyringVault:if _keyring_disabled():return Falsematch self.read():- case SecretUnavailable():+ case KeyringNotInstalled() | KeyringDisabled() | KeyringUnreachable():return Falsecase SecretMissing():return True@@ -117,7 +137,7 @@ class KeyringVault:def _delete(self) -> bool:api: Final = _keyring_api()- if api is None:+ if isinstance(api, (KeyringNotInstalled, KeyringDisabled)):return Falsetry:api.delete_password(KEYRING_SERVICE, KEYRING_ACCOUNT)diff --git a/litellm/litellm_core_utils/cli_token_utils.py b/litellm/litellm_core_utils/cli_token_utils.pyindex dd263ccd412..40822e5b335 100644--- a/litellm/litellm_core_utils/cli_token_utils.py+++ b/litellm/litellm_core_utils/cli_token_utils.py@@ -22,10 +22,14 @@ from pydantic import BaseModel, ConfigDict, ValidationErrorfrom litellm.litellm_core_utils.cli_keyring import (SYSTEM_KEYRING,+ KeyringDisabled,+ KeyringNotInstalled,+ KeyringUnreachable,SecretFound,SecretMissing,- SecretUnavailable,+ SecretStored,SecretVault,+ SecretWrite,)from litellm.litellm_core_utils.private_json import ensure_private_dir, write_private_json@@ -79,13 +83,15 @@ def load_cli_token(*, vault: SecretVault = SYSTEM_KEYRING) -> CliTokenRecord | Nreturn _resolve_secret(record, vault)-def save_cli_token(record: CliTokenRecord, *, vault: SecretVault = SYSTEM_KEYRING) -> bool:- """Store a freshly minted credential. Returns whether the keychain took the secret"""- if record.key is None or not vault.write(_encode_secret(record.base_url, record.key, record.jwt_token)):- _write_token_file(record)- return False- _write_token_file(_without_secret(record))- return True+def save_cli_token(record: CliTokenRecord, *, vault: SecretVault = SYSTEM_KEYRING) -> SecretWrite:+ """Store a freshly minted credential. Reports whether the keychain took the secret, and why not"""+ outcome: Final = (+ SecretStored()+ if record.key is None+ else vault.write(_encode_secret(record.base_url, record.key, record.jwt_token))+ )+ _write_token_file(_without_secret(record) if isinstance(outcome, SecretStored) else record)+ return outcomedef clear_cli_token(*, vault: SecretVault = SYSTEM_KEYRING) -> bool:@@ -163,7 +169,7 @@ def _resolve_secret(record: CliTokenRecord, vault: SecretVault) -> CliTokenRecorreturn _apply_vault_secret(record, blob, vault)case SecretMissing():return _migrate_file_secret(record, vault)- case SecretUnavailable():+ case KeyringNotInstalled() | KeyringDisabled() | KeyringUnreachable():return record@@ -188,7 +194,7 @@ def _apply_vault_secret(record: CliTokenRecord, blob: str, vault: SecretVault) -def _migrate_file_secret(record: CliTokenRecord, vault: SecretVault) -> CliTokenRecord | None:if record.key is None:return None- if vault.write(_encode_secret(record.base_url, record.key, record.jwt_token)):+ if isinstance(vault.write(_encode_secret(record.base_url, record.key, record.jwt_token)), SecretStored):_scrub_file_secret(record)return recorddiff --git a/litellm/proxy/client/README.md b/litellm/proxy/client/README.mdindex 9ece4c2be3d..d46c7174b4c 100644--- a/litellm/proxy/client/README.md+++ b/litellm/proxy/client/README.md@@ -377,7 +377,7 @@ The key itself goes into the OS keychain (macOS Keychain, Windows Credential Man}```-Headless boxes and CI runners usually have no keychain. There the key stays in the same `0600` file alongside the metadata, exactly as it did before, and `lite login` tells you which of the two happened. 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.+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.diff --git a/litellm/proxy/client/cli/commands/auth.py b/litellm/proxy/client/cli/commands/auth.pyindex c2b5b6a620f..03906f9b6df 100644--- a/litellm/proxy/client/cli/commands/auth.py+++ b/litellm/proxy/client/cli/commands/auth.py@@ -11,7 +11,16 @@ from rich.table import Tablefrom typing_extensions import NotRequired, ReadOnly, TypedDictfrom litellm.constants import CLI_JWT_EXPIRATION_HOURS-from litellm.litellm_core_utils.cli_keyring import SYSTEM_KEYRING, SecretVault+from litellm.litellm_core_utils.cli_keyring import (+ DISABLE_KEYRING_ENV_VAR,+ SYSTEM_KEYRING,+ KeyringDisabled,+ KeyringNotInstalled,+ KeyringUnreachable,+ SecretStored,+ SecretVault,+ SecretWrite,+)from litellm.litellm_core_utils.cli_token_utils import (CliTokenRecord,clear_cli_token,@@ -72,9 +81,29 @@ class CliAuthResult(TypedDict):KEYCHAIN_UNREACHABLE_MESSAGE: Final = (- "Your credential is stored in your OS keychain, which could not be read. Unlock it and retry, or run 'lite login'."+ "Your credential is stored in your OS keychain, which could not be read. Unlock it and retry, "+ "install the keyring package with: pip install 'litellm[cli]', or run 'lite login'.")+KEYRING_INSTALL_HINT: Final = "pip install 'litellm[cli]'"+++def storage_notice(outcome: SecretWrite) -> 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)."+def context_secret_vault(ctx: click.Context) -> SecretVault:"""Where this invocation reads and writes secret material; injectable through ctx.obj for tests"""@@ -675,15 +704,11 @@ def login(ctx: click.Context, config_claude: bool):jwt_token="",timestamp=time.time(),)- in_keychain: Final = save_cli_token(record, vault=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(- "Credential stored in your OS keychain."- if in_keychain- else f"No OS keychain available; credential stored in {get_cli_token_file_path()} (owner-only)."- )+ click.echo(storage_notice(stored))click.echo("You can now use the CLI without specifying --api-key")if config_claude:diff --git a/tests/test_litellm/conftest.py b/tests/test_litellm/conftest.pyindex ce0fd197538..a716ec0e0aa 100644--- a/tests/test_litellm/conftest.py+++ b/tests/test_litellm/conftest.py@@ -23,10 +23,13 @@ from litellm import router as litellm_router_modulefrom litellm import utils as litellm_utils_modulefrom litellm._logging import ALL_LOGGERSfrom litellm.litellm_core_utils.cli_keyring import (+ KeyringUnreachable,+ KeyringUnusable,SecretFound,SecretMissing,SecretRead,- SecretUnavailable,+ SecretStored,+ SecretWrite,)from litellm.litellm_core_utils.prompt_templates import (image_handling as image_handling_module,@@ -125,7 +128,8 @@ class FakeSecretVault:"""In-memory stand-in for the OS keychain, injected wherever CLI credential storage is exercised.`available=False` models a keychain that is locked or has no backend, `writable=False` one that- refuses to store, and `erasable=False` one that will not release what it already holds.+ refuses to store, `erasable=False` one that will not release what it already holds, and `failure`+ picks which unusable state those report."""def __init__(@@ -135,11 +139,13 @@ class FakeSecretVault:available: bool = True,writable: bool = True,erasable: bool = True,+ failure: KeyringUnusable = KeyringUnreachable(),) -> None:self.blob: str | None = blobself.available: bool = availableself.writable: bool = writableself.erasable: bool = erasable+ self.failure: KeyringUnusable = failureself.reads: int = 0self.writes: list[str] = []self.erases: int = 0@@ -147,15 +153,15 @@ class FakeSecretVault:def read(self) -> SecretRead:self.reads += 1if not self.available:- return SecretUnavailable()+ return self.failurereturn SecretMissing() if self.blob is None else SecretFound(self.blob)- def write(self, blob: str) -> bool:+ def write(self, blob: str) -> SecretWrite:self.writes.append(blob)if not (self.available and self.writable):- return False+ return self.failureself.blob = blob- return True+ return SecretStored()def erase(self) -> bool:self.erases += 1diff --git a/tests/test_litellm/litellm_core_utils/test_cli_token_utils.py b/tests/test_litellm/litellm_core_utils/test_cli_token_utils.pyindex 56ab6bcbfe0..961d986e8f5 100644--- a/tests/test_litellm/litellm_core_utils/test_cli_token_utils.py+++ b/tests/test_litellm/litellm_core_utils/test_cli_token_utils.py@@ -13,7 +13,10 @@ from litellm.litellm_core_utils.cli_keyring import (KeyringVault,SecretFound,SecretMissing,- SecretUnavailable,+ KeyringDisabled,+ KeyringNotInstalled,+ KeyringUnreachable,+ SecretStored,)from litellm.litellm_core_utils.cli_token_utils import (CliTokenRecord,@@ -253,7 +256,7 @@ class TestSaveCliToken:vault=vault,)- assert stored is True+ 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"@@ -265,7 +268,7 @@ class TestSaveCliToken:)path = _token_file(isolated_home)- assert stored is False+ assert stored == KeyringUnreachable()assert json.loads(path.read_text())["key"] == "sk-new"assert stat.S_IMODE(path.stat().st_mode) == 0o600assert list(path.parent.glob(".tmp-*")) == []@@ -379,7 +382,7 @@ class TestKeyringVault:fake = install_fake_keyring(_FakeKeyringModule())vault = KeyringVault()- assert vault.write("blob-1") is True+ assert vault.write("blob-1") == SecretStored()assert vault.read() == SecretFound("blob-1")assert vault.erase() is Trueassert vault.read() == SecretMissing()@@ -393,8 +396,8 @@ class TestKeyringVault:monkeypatch.setenv(DISABLE_KEYRING_ENV_VAR, "1")vault = KeyringVault()- assert vault.read() == SecretUnavailable()- assert vault.write("blob-1") is False+ assert vault.read() == KeyringDisabled()+ assert vault.write("blob-1") == KeyringDisabled()assert vault.erase() is Falsedef test_an_uninstalled_keyring_library_degrades_to_the_file(self, monkeypatch):@@ -404,19 +407,19 @@ class TestKeyringVault:monkeypatch.setitem(sys.modules, "keyring", None)vault = KeyringVault()- assert vault.read() == SecretUnavailable()- assert vault.write("blob-1") is False+ assert vault.read() == KeyringNotInstalled()+ assert vault.write("blob-1") == KeyringNotInstalled()assert vault.erase() is Truedef 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() == SecretUnavailable()+ 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") is False+ 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")))diff --git a/tests/test_litellm/proxy/client/cli/test_auth_commands.py b/tests/test_litellm/proxy/client/cli/test_auth_commands.pyindex e93f05cb4aa..1f2d48f6547 100644--- a/tests/test_litellm/proxy/client/cli/test_auth_commands.py+++ b/tests/test_litellm/proxy/client/cli/test_auth_commands.py@@ -13,6 +13,11 @@ import pytestfrom 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,+)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 (@@ -931,6 +936,29 @@ class TestKeychainBackedCommands:assert str(token_file) in result.outputassert json.loads(token_file.read_text())["key"] == "sk-minted"+ def test_login_points_a_user_missing_the_keyring_package_at_the_install(+ self, isolated_home, secret_vault_factory+ ):+ """`lite` ships with every install, the keyring package only with the cli extra. Telling+ that user their machine has no keychain sends them looking for a problem they do not have."""+ result = self._login(secret_vault_factory(available=False, failure=KeyringNotInstalled()))++ token_file = isolated_home / ".litellm" / "token.json"+ assert result.exit_code == 0+ assert "pip install 'litellm[cli]'" in result.output+ assert "No OS keychain available" not in result.output+ assert json.loads(token_file.read_text())["key"] == "sk-minted"++ def test_login_names_the_kill_switch_instead_of_blaming_the_machine(+ self, isolated_home, secret_vault_factory+ ):+ result = self._login(secret_vault_factory(available=False, failure=KeyringDisabled()))++ assert result.exit_code == 0+ assert DISABLE_KEYRING_ENV_VAR in result.output+ assert "No OS keychain available" not in result.output+ assert json.loads((isolated_home / ".litellm" / "token.json").read_text())["key"] == "sk-minted"+def test_whoami_and_print_token_read_through_the_keychain(self, isolated_home, secret_vault_factory):vault = secret_vault_factory()self._login(vault)