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): keep lite login and logout honest when the keychain will not answer
mateo-berriba637553f8cd
diff --git a/litellm/litellm_core_utils/cli_keyring.py b/litellm/litellm_core_utils/cli_keyring.pyindex 15282fc522c..8da3e5226d4 100644--- a/litellm/litellm_core_utils/cli_keyring.py+++ b/litellm/litellm_core_utils/cli_keyring.py@@ -11,18 +11,24 @@ token file and tell the user what to do about it.A write is only reported as stored once it has been read back, because keyring'snull backend, which `keyring --disable` and headless CI images both select,-accepts every write and keeps nothing.+accepts every write and keeps nothing. Writes are also pre-flighted with a+throwaway value, because a keychain can answer neither way and block forever."""import os+import threading+from contextlib import suppressfrom dataclasses import dataclassfrom typing import Final, Protocol, TypeAliasKEYRING_SERVICE: Final = "litellm-cli"KEYRING_ACCOUNT: Final = "credential"+KEYRING_PREFLIGHT_ACCOUNT: Final = "credential-preflight"DISABLE_KEYRING_ENV_VAR: Final = "LITELLM_CLI_DISABLE_KEYRING"_DISABLED_VALUES: Final = frozenset(("1", "true", "yes", "on"))+_PREFLIGHT_VALUE: Final = "preflight"+_PREFLIGHT_TIMEOUT_SECONDS: Final = 5.0@dataclass(frozen=True, slots=True)@@ -70,9 +76,9 @@ class KeyringDiscardsWrites:pass-KeyringUnusable: TypeAlias = KeyringNotInstalled | KeyringDisabled | KeyringUnreachable | KeyringDiscardsWrites+KeyringUnusable: TypeAlias = KeyringNotInstalled | KeyringDisabled | KeyringUnreachableSecretRead: TypeAlias = SecretFound | SecretMissing | KeyringUnusable-SecretWrite: TypeAlias = SecretStored | KeyringUnusable+SecretWrite: TypeAlias = SecretStored | KeyringUnusable | KeyringDiscardsWritesSecretErase: TypeAlias = SecretErased | SecretStranded | KeyringUnusable@@ -113,10 +119,43 @@ def _keyring_api() -> KeyringApi | KeyringNotInstalled | KeyringDisabled:return KeyringNotInstalled() if api is None else api+def _answers_a_write(api: KeyringApi, timeout_seconds: float) -> bool:+ """Whether the keychain answers a write at all, asked with a value worth nothing.++ macOS derives the login keychain from `$HOME`, and `set_password` against 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 reads answer normally, so nothing cheaper tells them apart. Asking+ with a throwaway value keeps a keychain that never answers from taking `lite login` down with+ it, and keeps the real credential out of a store that might accept it long after we gave up.+ A keychain that refuses the probe outright still answered it, so only silence counts against it.+ """+ answered: Final = threading.Event()++ def ask() -> None:+ with suppress(Exception):+ api.set_password(KEYRING_SERVICE, KEYRING_PREFLIGHT_ACCOUNT, _PREFLIGHT_VALUE)+ answered.set()++ threading.Thread(target=ask, daemon=True, name="litellm-cli-keyring-preflight").start()+ return answered.wait(timeout_seconds)+++def _forget_the_preflight(api: KeyringApi) -> None:+ """Take the throwaway probe back out.++ A backend that kept nothing has nothing to remove, and the probe is worth nothing either way,+ so a keychain that refuses to give it up costs the caller nothing.+ """+ with suppress(Exception):+ api.delete_password(KEYRING_SERVICE, KEYRING_PREFLIGHT_ACCOUNT)++@dataclass(frozen=True, slots=True)class KeyringVault:"""The OS keychain, reached through the optional `keyring` package."""+ preflight_timeout_seconds: float = _PREFLIGHT_TIMEOUT_SECONDS+def read(self) -> SecretRead:api: Final = _keyring_api()if isinstance(api, (KeyringNotInstalled, KeyringDisabled)):@@ -134,10 +173,16 @@ class KeyringVault:and `PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring` select, raises nothing todistinguish itself. Reading the value back is the only way to tell it apart from a keychainthat really stored the credential, and the caller is about to drop its own copy on our word.++ The keychain is pre-flighted first, because one that blocks rather than answering would+ otherwise hang `lite login` outright."""api: Final = _keyring_api()if isinstance(api, (KeyringNotInstalled, KeyringDisabled)):return api+ if not _answers_a_write(api, self.preflight_timeout_seconds):+ return KeyringUnreachable()+ _forget_the_preflight(api)try:api.set_password(KEYRING_SERVICE, KEYRING_ACCOUNT, blob)except Exception: # noqa: BLE001 # a keychain that refuses the write falls back to the token file@@ -153,7 +198,7 @@ class KeyringVault:the caller knows whether this machine ever put a secret in a keychain."""match self.read():- case KeyringNotInstalled() | KeyringDisabled() | KeyringUnreachable() | KeyringDiscardsWrites() as unusable:+ case KeyringNotInstalled() | KeyringDisabled() | KeyringUnreachable() as unusable:return unusablecase SecretMissing():return SecretErased()diff --git a/litellm/litellm_core_utils/cli_token_utils.py b/litellm/litellm_core_utils/cli_token_utils.pyindex af1b918fc2a..825967e6866 100644--- a/litellm/litellm_core_utils/cli_token_utils.py+++ b/litellm/litellm_core_utils/cli_token_utils.py@@ -23,7 +23,6 @@ from pydantic import BaseModel, ConfigDict, ValidationErrorfrom litellm.litellm_core_utils.cli_keyring import (SYSTEM_KEYRING,KeyringDisabled,- KeyringDiscardsWrites,KeyringNotInstalled,KeyringUnreachable,SecretErase,@@ -53,6 +52,8 @@ class CredentialNotSaved:SecretSave: TypeAlias = SecretWrite | CredentialNotSaved+_UNREPLACEABLE_FILE: Final = "the staged file could not replace the one already there"+class CliTokenRecord(BaseModel):"""A stored CLI credential.@@ -106,57 +107,71 @@ def load_cli_token(*, vault: SecretVault = SYSTEM_KEYRING) -> CliTokenRecord | Ndef save_cli_token(record: CliTokenRecord, *, vault: SecretVault = SYSTEM_KEYRING) -> SecretSave:"""Store a freshly minted credential. Reports where its secret material ended up, and why.- The token file is what makes a keychain-backed credential findable again, so a file that will- not be written takes the keychain copy down with it rather than leaving a live credential- stored under a machine that has no record of it.+ The token file is what makes a keychain-backed credential findable again, and it is also the+ half that a read-only or full directory refuses, so it is staged before the keychain is handed+ anything. A save that cannot land then leaves both stores exactly as it found them, which+ matters most when the login it failed to replace is still perfectly good."""+ staged: Final = _stage_token_file(_without_secret(record))+ if isinstance(staged, CredentialNotSaved):+ return stagedoutcome: Final = (SecretStored()if record.key is Noneelse vault.write(_encode_secret(record.base_url, record.key, record.jwt_token)))+ if isinstance(outcome, SecretStored):+ return outcome if _commit_token_file(staged) else CredentialNotSaved(_UNREPLACEABLE_FILE)+ discard_staged_json(staged)+ return _keep_the_secret_in_the_file(record, outcome)+++def _keep_the_secret_in_the_file(record: CliTokenRecord, outcome: SecretWrite) -> SecretSave:+ """Fall back to the owner-only file, which is all that is left when no keychain took the secret"""try:- _write_token_file(_without_secret(record) if isinstance(outcome, SecretStored) else record)+ _write_token_file(record)except OSError as error:- if record.key is not None and isinstance(outcome, SecretStored):- vault.erase()return CredentialNotSaved(str(error))return outcomedef clear_cli_token(*, vault: SecretVault = SYSTEM_KEYRING) -> SecretErase:- """Remove the credential from both stores. Reports whether the keychain is now free of it"""+ """Remove the credential from both stores. Reports whether the keychain is now free of it.++ A file that holds no secret of its own is kept when the keychain will not confirm the entry is+ gone, because it is the only remaining record that something is still in there to remove. That+ is what lets a later run tell a machine with a credential it cannot reach apart from one that+ never had a login at all. Anything still holding a secret is removed either way.+ """outcome: Final = vault.erase()- settled: Final = _nothing_left_behind(outcome)- Path(get_cli_token_file_path()).unlink(missing_ok=True)+ record: Final = _read_token_file()+ settled: Final = _nothing_left_behind(outcome, record)+ if settled or record is None or record.key is not None:+ Path(get_cli_token_file_path()).unlink(missing_ok=True)return SecretErased() if settled else outcome-def _nothing_left_behind(outcome: SecretErase) -> bool:+def _nothing_left_behind(outcome: SecretErase, record: CliTokenRecord | None) -> bool:"""Whether the keychain can be trusted to hold no credential of ours once the file is gone.- A keychain that exists but is out of reach right now is never trusted, whatever the token file- looks like: the login that stored a secret there and the logout that cannot remove it are- separate runs, free to differ in whether the keychain was usable at the time.+ A machine with no token file has no stored login to end, and `clear_cli_token` keeps one behind+ whenever the keychain is left unconfirmed, so a missing file is real evidence rather than the+ absence of it. Past that, a keychain that exists but is out of reach right now is+ never trusted, whatever the file looks like: the login that stored a secret there and the+ logout that cannot remove it are separate runs, free to differ in whether the keychain was+ usable at the time. The exception is a missing `keyring` package, which had to be missing when+ the credential was stored too, so a file still holding its own secret proves no keychain was+ ever involved. `SecretStranded` is the keychain answering for itself and outranks the file."""match outcome:case SecretErased():return True- case SecretStranded() | KeyringDisabled() | KeyringUnreachable() | KeyringDiscardsWrites():+ case SecretStranded():return False+ case KeyringDisabled() | KeyringUnreachable():+ return record is Nonecase KeyringNotInstalled():- return _file_holds_its_own_secret()---def _file_holds_its_own_secret() -> bool:- """Whether the stored login keeps its secret in the token file, ruling out a keychain entry.-- Sound only against a missing `keyring` package, the one way to lose the keychain that had to- hold at storage time too, since nothing here can reach a keychain without it. A file whose- secret half is absent went to a keychain by definition, and so rules nothing out.- """- record: Final = _read_token_file()- return record is not None and record.key is not None+ return record is None or record.key is not Nonedef get_litellm_gateway_api_key(@@ -227,7 +242,7 @@ def _resolve_secret(record: CliTokenRecord, vault: SecretVault) -> CliTokenRecorreturn _apply_vault_secret(record, blob, vault)case SecretMissing():return _migrate_file_secret(record, vault)- case KeyringNotInstalled() | KeyringDisabled() | KeyringUnreachable() | KeyringDiscardsWrites():+ case KeyringNotInstalled() | KeyringDisabled() | KeyringUnreachable():return record@@ -265,7 +280,7 @@ def _migrate_file_secret(record: CliTokenRecord, vault: SecretVault) -> CliTokenif not isinstance(vault.write(_encode_secret(record.base_url, record.key, record.jwt_token)), SecretStored):discard_staged_json(staged)return record- if not _commit_scrubbed_file(staged):+ if not _commit_token_file(staged):vault.erase()return record@@ -275,19 +290,24 @@ def _scrub_file_secret(record: CliTokenRecord) -> bool:if record.key is None and not record.jwt_token:return Truestaged: Final = _stage_scrubbed_file(record)- return staged is not None and _commit_scrubbed_file(staged)+ return staged is not None and _commit_token_file(staged)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), _without_secret(record).model_dump(exclude_none=True))- except OSError:- return None+ return stage_private_json(str(path), record.model_dump(exclude_none=True))+ except OSError as error:+ return CredentialNotSaved(str(error))-def _commit_scrubbed_file(staged: str) -> bool:+def _commit_token_file(staged: str) -> bool:try:commit_staged_json(staged, get_cli_token_file_path())except OSError:diff --git a/litellm/proxy/client/cli/commands/auth.py b/litellm/proxy/client/cli/commands/auth.pyindex eba9994f7ec..d89641d2366 100644--- a/litellm/proxy/client/cli/commands/auth.py+++ b/litellm/proxy/client/cli/commands/auth.py@@ -123,7 +123,8 @@ def storage_notice(outcome: SecretSave) -> str:case CredentialNotSaved(detail=detail):return (f"Signed in, but the credential could not be saved to {path}: {detail}. "- "Nothing was kept, so run 'lite login' again once that path is writable."+ "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.")@@ -140,7 +141,7 @@ def keychain_unreadable_notice(vault: SecretVault) -> str: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() | KeyringDiscardsWrites():+ case KeyringUnreachable():return ("Your credential is in your OS keychain, which could not be read. Unlock it, or run ""'lite login' to start over."@@ -800,7 +801,7 @@ def logout(ctx: click.Context):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() | KeyringDiscardsWrites():+ case KeyringUnreachable():click.echo(UNCHECKED_KEYCHAIN_MESSAGE)click.echo("Unlock your keychain and run 'lite logout' again to clear it.")diff --git a/pyproject.toml b/pyproject.tomlindex 32921e14d31..64adb9cd595 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -79,7 +79,7 @@ proxy = []# Thin client install for the `lite` CLI on developer laptops. The CLI's heavy# imports (fastapi, cryptography, ...) are all guarded, so it runs on the base-# SDK plus just these four; none of the server runtime in `proxy` is pulled in.+# SDK plus just these five; none of the server runtime in `proxy` is pulled in.cli = ["rich>=13.9.4,<14.0","pyyaml>=6.0.3,<7.0",diff --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 e0f5f99dc1b..69ce47b25b3 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@@ -2,6 +2,7 @@ import jsonimport osimport statimport sys+import threadingimport timeimport pytest@@ -10,6 +11,7 @@ from litellm.constants import CLI_JWT_EXPIRATION_HOURSfrom litellm.litellm_core_utils.cli_keyring import (DISABLE_KEYRING_ENV_VAR,KEYRING_ACCOUNT,+ KEYRING_PREFLIGHT_ACCOUNT,KEYRING_SERVICE,KeyringVault,SecretFound,@@ -329,12 +331,12 @@ class TestSaveCliToken:assert isinstance(outcome, CredentialNotSaved)assert "read-only file system" in outcome.detail- def test_a_credential_the_file_will_not_record_is_taken_back_out_of_the_keychain(+ 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. Leaving the secret in the- keychain with nothing pointing at it strands a live credential under a machine that has no- idea it is there, and no `lite logout` would ever go looking for it."""+ """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):@@ -346,6 +348,26 @@ class TestSaveCliToken: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_failed_write_leaves_the_previous_credential_intact(self, isolated_home, secret_vault_factory, monkeypatch):path = _write_legacy_file(isolated_home)before = path.read_text()@@ -460,8 +482,44 @@ class TestClearCliToken: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 not _token_file(isolated_home).exists()+ @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_logs_out_quietly_without_keyring(self, isolated_home, secret_vault_factory):"""The complement, and the one inference the file does support: nothing here can reach akeychain without the package, so an install that lacks it and a file that still holds its@@ -510,7 +568,7 @@ class _FakeKeyringModule:self.calls.append(("set", service_name, username))if self.set_error is not None:raise self.set_error- if self.discard:+ if self.discard or username != KEYRING_ACCOUNT:returnself.stored = password@@ -518,7 +576,22 @@ class _FakeKeyringModule:self.calls.append(("delete", service_name, username))if self.delete_error is not None:raise self.delete_error- self.stored = None+ 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()@pytest.fixture@@ -540,7 +613,8 @@ class TestKeyringVault:assert vault.read() == SecretFound("blob-1")assert vault.erase() == SecretErased()assert vault.read() == SecretMissing()- assert {call[1:] for call in fake.calls} == {(KEYRING_SERVICE, KEYRING_ACCOUNT)}+ 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@@ -590,6 +664,43 @@ class TestKeyringVault: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_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 isthat upstream's no-op write looks exactly like a successful one."""diff --git a/tests/test_litellm/proxy/client/cli/test_auth_commands.py b/tests/test_litellm/proxy/client/cli/test_auth_commands.pyindex 8e1551c0720..e491dbd5aca 100644--- a/tests/test_litellm/proxy/client/cli/test_auth_commands.py+++ b/tests/test_litellm/proxy/client/cli/test_auth_commands.py@@ -1074,7 +1074,7 @@ class TestKeychainBackedCommands:assert result.exit_code == 0assert "could not be removed" in result.output- assert not (isolated_home / ".litellm" / "token.json").exists()+ assert json.loads((isolated_home / ".litellm" / "token.json").read_text()).get("key") is Nonedef test_print_token_explains_a_locked_keychain_instead_of_printing_nothing(self, isolated_home, secret_vault_factory