Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(cli): never report success while a credential is still readable

mateo-berri1750893a6905
diff --git a/litellm/litellm_core_utils/cli_keyring.py b/litellm/litellm_core_utils/cli_keyring.py
index b19b3d3bc83..0497991c2a0 100644
--- a/litellm/litellm_core_utils/cli_keyring.py
+++ b/litellm/litellm_core_utils/cli_keyring.py
@@ -36,6 +36,16 @@ class SecretStored:
pass
+@dataclass(frozen=True, slots=True)
+class SecretErased:
+ pass
+
+
+@dataclass(frozen=True, slots=True)
+class SecretStranded:
+ pass
+
+
@dataclass(frozen=True, slots=True)
class KeyringNotInstalled:
pass
@@ -54,6 +64,7 @@ class KeyringUnreachable:
KeyringUnusable: TypeAlias = KeyringNotInstalled | KeyringDisabled | KeyringUnreachable
SecretRead: TypeAlias = SecretFound | SecretMissing | KeyringUnusable
SecretWrite: TypeAlias = SecretStored | KeyringUnusable
+SecretErase: TypeAlias = SecretErased | SecretStranded | KeyringUnusable
class SecretVault(Protocol):
@@ -63,7 +74,7 @@ class SecretVault(Protocol):
def write(self, blob: str) -> SecretWrite: ...
- def erase(self) -> bool: ...
+ def erase(self) -> SecretErase: ...
class KeyringApi(Protocol):
@@ -117,33 +128,31 @@ class KeyringVault:
return KeyringUnreachable()
return SecretStored()
- def erase(self) -> bool:
- """Whether the keychain is guaranteed to hold no credential afterwards.
+ def erase(self) -> SecretErase:
+ """Remove our entry, reporting whether the keychain is guaranteed to be free of it.
- An uninstalled `keyring` package can never have stored one. A kill switch set after
- a credential was stored leaves that entry out of reach, so erasure cannot be promised.
+ A keychain out of reach is never an erasure: the entry belongs to the OS, not to this
+ install, so it outlives an uninstalled `keyring` package and a kill switch set after login.
+ Those cases are reported apart from a confirmed entry that would not delete, because only
+ the caller knows whether this machine ever put a secret in a keychain.
"""
- if _import_keyring() is None:
- return True
- if _keyring_disabled():
- return False
match self.read():
- case KeyringNotInstalled() | KeyringDisabled() | KeyringUnreachable():
- return False
+ case KeyringNotInstalled() | KeyringDisabled() | KeyringUnreachable() as unusable:
+ return unusable
case SecretMissing():
- return True
+ return SecretErased()
case SecretFound():
return self._delete()
- def _delete(self) -> bool:
+ def _delete(self) -> SecretErase:
api: Final = _keyring_api()
if isinstance(api, (KeyringNotInstalled, KeyringDisabled)):
- return False
+ return api
try:
api.delete_password(KEYRING_SERVICE, KEYRING_ACCOUNT)
except Exception: # noqa: BLE001 # report the failure as a value so `lite logout` can warn
- return False
- return True
+ return SecretStranded()
+ return SecretErased()
SYSTEM_KEYRING: Final[SecretVault] = KeyringVault()
diff --git a/litellm/litellm_core_utils/cli_token_utils.py b/litellm/litellm_core_utils/cli_token_utils.py
index 40822e5b335..cd69f9470a3 100644
--- a/litellm/litellm_core_utils/cli_token_utils.py
+++ b/litellm/litellm_core_utils/cli_token_utils.py
@@ -25,9 +25,12 @@ from litellm.litellm_core_utils.cli_keyring import (
KeyringDisabled,
KeyringNotInstalled,
KeyringUnreachable,
+ SecretErase,
+ SecretErased,
SecretFound,
SecretMissing,
SecretStored,
+ SecretStranded,
SecretVault,
SecretWrite,
)
@@ -84,7 +87,7 @@ def load_cli_token(*, vault: SecretVault = SYSTEM_KEYRING) -> CliTokenRecord | N
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"""
+ """Store a freshly minted credential. Reports where its secret material ended up, and why"""
outcome: Final = (
SecretStored()
if record.key is None
@@ -94,11 +97,33 @@ def save_cli_token(record: CliTokenRecord, *, vault: SecretVault = SYSTEM_KEYRIN
return outcome
-def clear_cli_token(*, vault: SecretVault = SYSTEM_KEYRING) -> bool:
- """Remove the credential from both stores. Returns whether the keychain is now free of it"""
- erased: Final = vault.erase()
+def clear_cli_token(*, vault: SecretVault = SYSTEM_KEYRING) -> SecretErase:
+ """Remove the credential from both stores. Reports whether the keychain is now free of it"""
+ outcome: Final = vault.erase()
+ settled: Final = _nothing_left_behind(outcome)
Path(get_cli_token_file_path()).unlink(missing_ok=True)
- return erased
+ return SecretErased() if settled else outcome
+
+
+def _nothing_left_behind(outcome: SecretErase) -> bool:
+ """Whether the keychain can be trusted to hold no credential of ours once the file is gone"""
+ match outcome:
+ case SecretErased():
+ return True
+ case SecretStranded():
+ return False
+ case KeyringNotInstalled() | KeyringDisabled() | KeyringUnreachable():
+ return not _secret_lives_in_keychain()
+
+
+def _secret_lives_in_keychain() -> bool:
+ """Whether the token file is the metadata half of a pair whose secret half went to a keychain.
+
+ A file that still carries its own secret rules one out, which keeps `lite logout` quiet on the
+ machines that never had a keychain to begin with.
+ """
+ record: Final = _read_token_file()
+ return record is not None and record.key is None and not record.jwt_token
def get_litellm_gateway_api_key(
@@ -200,10 +225,22 @@ def _migrate_file_secret(record: CliTokenRecord, vault: SecretVault) -> CliToken
def _scrub_file_secret(record: CliTokenRecord) -> None:
+ """Leave no secret material in the token file once the vault holds it.
+
+ A file that cannot be rewritten without the secret is removed instead. Signing in again costs
+ the user one command; a live credential left behind in cleartext costs them the credential.
+ """
if record.key is None and not record.jwt_token:
return
- with contextlib.suppress(OSError):
+ try:
_write_token_file(_without_secret(record))
+ except OSError:
+ _discard_token_file()
+
+
+def _discard_token_file() -> None:
+ with contextlib.suppress(OSError):
+ Path(get_cli_token_file_path()).unlink(missing_ok=True)
def _without_secret(record: CliTokenRecord) -> CliTokenRecord:
diff --git a/litellm/proxy/client/cli/commands/auth.py b/litellm/proxy/client/cli/commands/auth.py
index 03906f9b6df..4cf18435473 100644
--- a/litellm/proxy/client/cli/commands/auth.py
+++ b/litellm/proxy/client/cli/commands/auth.py
@@ -17,7 +17,9 @@ from litellm.litellm_core_utils.cli_keyring import (
KeyringDisabled,
KeyringNotInstalled,
KeyringUnreachable,
+ SecretErased,
SecretStored,
+ SecretStranded,
SecretVault,
SecretWrite,
)
@@ -80,12 +82,16 @@ class CliAuthResult(TypedDict):
team_id: str | None
-KEYCHAIN_UNREACHABLE_MESSAGE: Final = (
- "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]'"
+
+STRANDED_CREDENTIAL_MESSAGE: Final = (
+ "Logged out locally, but your credential is still in the OS keychain and could not be removed."
)
-KEYRING_INSTALL_HINT: Final = "pip install 'litellm[cli]'"
+KEYCHAIN_UNREACHABLE_MESSAGE: Final = (
+ "Your credential is stored in your OS keychain, which could not be read. Unlock it, or install "
+ f"the keyring package with: {KEYRING_INSTALL_HINT}. Run 'lite login' to start over."
+)
def storage_notice(outcome: SecretWrite) -> str:
@@ -742,11 +748,18 @@ def login(ctx: click.Context, config_claude: bool):
@click.pass_context
def logout(ctx: click.Context):
"""Logout and clear stored authentication"""
- if clear_cli_token(vault=context_secret_vault(ctx)):
- click.echo("Logged out successfully. Authentication token cleared.")
- return
- click.echo("Logged out. The local token file is gone, but the OS keychain entry could not be removed.")
- click.echo("Unlock your keychain and run 'lite logout' again to clear it.")
+ match clear_cli_token(vault=context_secret_vault(ctx)):
+ case SecretErased():
+ click.echo("Logged out successfully. Authentication token cleared.")
+ case KeyringNotInstalled():
+ click.echo(STRANDED_CREDENTIAL_MESSAGE)
+ click.echo(f"Install the keyring package with: {KEYRING_INSTALL_HINT}, then run 'lite logout' again.")
+ case KeyringDisabled():
+ click.echo(STRANDED_CREDENTIAL_MESSAGE)
+ click.echo(f"Unset {DISABLE_KEYRING_ENV_VAR} and run 'lite logout' again to clear it.")
+ case SecretStranded() | KeyringUnreachable():
+ click.echo(STRANDED_CREDENTIAL_MESSAGE)
+ click.echo("Unlock your keychain and run 'lite logout' again to clear it.")
@click.command(name="print-token")
diff --git a/tests/test_litellm/conftest.py b/tests/test_litellm/conftest.py
index a716ec0e0aa..b42355fa045 100644
--- a/tests/test_litellm/conftest.py
+++ b/tests/test_litellm/conftest.py
@@ -25,10 +25,13 @@ from litellm._logging import ALL_LOGGERS
from litellm.litellm_core_utils.cli_keyring import (
KeyringUnreachable,
KeyringUnusable,
+ SecretErase,
+ SecretErased,
SecretFound,
SecretMissing,
SecretRead,
SecretStored,
+ SecretStranded,
SecretWrite,
)
from litellm.litellm_core_utils.prompt_templates import (
@@ -163,12 +166,14 @@ class FakeSecretVault:
self.blob = blob
return SecretStored()
- def erase(self) -> bool:
+ def erase(self) -> SecretErase:
self.erases += 1
- if not (self.available and self.erasable):
- return False
+ if not self.available:
+ return self.failure
+ if not self.erasable:
+ return SecretStranded() if self.blob is not None else SecretErased()
self.blob = None
- return True
+ return SecretErased()
@pytest.fixture
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.py
index 961d986e8f5..925b440dfb7 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
@@ -16,7 +16,9 @@ from litellm.litellm_core_utils.cli_keyring import (
KeyringDisabled,
KeyringNotInstalled,
KeyringUnreachable,
+ SecretErased,
SecretStored,
+ SecretStranded,
)
from litellm.litellm_core_utils.cli_token_utils import (
CliTokenRecord,
@@ -126,6 +128,16 @@ class TestLoadCliToken:
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."""
@@ -304,12 +316,35 @@ class TestSaveCliToken:
assert list(path.parent.glob(".tmp-*")) == []
+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."""
+
+ def test_a_file_that_cannot_be_rewritten_is_removed_instead(
+ self, isolated_home, secret_vault_factory, monkeypatch
+ ):
+ 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 json.loads(vault.blob)["key"] == "sk-legacy"
+ assert not path.exists()
+ assert list(path.parent.glob(".tmp-*")) == []
+
+
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) is True
+ 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
@@ -318,11 +353,32 @@ class TestClearCliToken:
_write_legacy_file(isolated_home)
vault = secret_vault_factory(blob=_blob(), erasable=False)
- assert clear_cli_token(vault=vault) is False
+ assert clear_cli_token(vault=vault) == SecretStranded()
+ assert not _token_file(isolated_home).exists()
+
+ def test_logout_from_an_install_without_keyring_does_not_claim_the_keychain_is_clear(
+ self, isolated_home, secret_vault_factory
+ ):
+ """Log in where `litellm[cli]` is installed and the secret goes to the OS keychain; log out
+ from a venv without it and the entry survives, because it belongs to the OS rather than to
+ the package. Reporting a clean logout there leaves a live credential the user thinks is gone."""
+ _write_metadata_only_file(isolated_home)
+ vault = secret_vault_factory(available=False, failure=KeyringNotInstalled())
+
+ assert clear_cli_token(vault=vault) == KeyringNotInstalled()
+ assert not _token_file(isolated_home).exists()
+
+ def test_a_file_backed_login_logs_out_quietly_without_keyring(self, isolated_home, secret_vault_factory):
+ """The complement: a user who never had a keychain keeps their whole credential in the file,
+ so removing it is a complete logout and must not warn about an entry that cannot exist."""
+ _write_legacy_file(isolated_home)
+ vault = secret_vault_factory(available=False, failure=KeyringNotInstalled())
+
+ assert clear_cli_token(vault=vault) == SecretErased()
assert not _token_file(isolated_home).exists()
def test_is_safe_when_nothing_was_ever_stored(self, isolated_home, secret_vault_factory):
- assert clear_cli_token(vault=secret_vault_factory()) is True
+ assert clear_cli_token(vault=secret_vault_factory()) == SecretErased()
class TestIsCliTokenFresh:
@@ -384,7 +440,7 @@ class TestKeyringVault:
assert vault.write("blob-1") == SecretStored()
assert vault.read() == SecretFound("blob-1")
- assert vault.erase() is True
+ assert vault.erase() == SecretErased()
assert vault.read() == SecretMissing()
assert {call[1:] for call in fake.calls} == {(KEYRING_SERVICE, KEYRING_ACCOUNT)}
@@ -392,24 +448,25 @@ class TestKeyringVault:
"""`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 warn instead."""
+ 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() is False
+ 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."""
+ 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() is True
+ 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")))
@@ -424,9 +481,9 @@ class TestKeyringVault:
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() is False
+ assert KeyringVault().erase() == SecretStranded()
def test_erasing_a_locked_keychain_is_a_failure(self, install_fake_keyring):
install_fake_keyring(_FakeKeyringModule(get_error=RuntimeError("locked")))
- assert KeyringVault().erase() is False
+ assert KeyringVault().erase() == KeyringUnreachable()
diff --git a/tests/test_litellm/proxy/client/cli/test_auth_commands.py b/tests/test_litellm/proxy/client/cli/test_auth_commands.py
index 1f2d48f6547..33bd8307c21 100644
--- a/tests/test_litellm/proxy/client/cli/test_auth_commands.py
+++ b/tests/test_litellm/proxy/client/cli/test_auth_commands.py
@@ -46,6 +46,12 @@ def _write_home_json(home: Path, filename: str, payload: dict[str, object]) -> N
(litellm_dir / filename).write_text(json.dumps(payload))
+def _write_token_file(home: Path, *, key: str | None) -> None:
+ """A stored login: `key=None` is the metadata half of a keychain-backed pair, a key is a file-backed one."""
+ payload: dict[str, object] = {"base_url": "https://test.example.com", "user_id": "u-1", "timestamp": time.time()}
+ _write_home_json(home, "token.json", payload if key is None else {**payload, "key": key})
+
+
def _secret_blob(base_url: str, key: str) -> str:
return json.dumps({"base_url": base_url, "key": key, "jwt_token": ""})
@@ -427,14 +433,62 @@ class TestLogoutCommand:
"""Setup for each test"""
self.runner = CliRunner()
- def test_logout_success(self):
+ def test_logout_success(self, isolated_home, secret_vault_factory):
"""Test successful logout"""
- with patch("litellm.proxy.client.cli.commands.auth.clear_cli_token") as mock_clear:
- result = self.runner.invoke(logout)
+ vault = secret_vault_factory(blob=_secret_blob("https://test.example.com", "sk-stored"))
+ _write_token_file(isolated_home, key=None)
- assert result.exit_code == 0
- assert "Logged out successfully" in result.output
- mock_clear.assert_called_once()
+ result = self.runner.invoke(logout, obj={"secret_vault": vault})
+
+ assert result.exit_code == 0
+ assert "Logged out successfully" in result.output
+ assert vault.blob is None
+ assert not (isolated_home / ".litellm" / "token.json").exists()
+
+ def test_logout_without_the_keyring_package_does_not_claim_the_keychain_is_clear(
+ self, isolated_home, secret_vault_factory
+ ):
+ """Logging out from an install without the cli extra cannot touch an entry a keychain-backed
+ login left behind, so it must point at the package rather than report a clean logout."""
+ _write_token_file(isolated_home, key=None)
+
+ result = self.runner.invoke(
+ logout, obj={"secret_vault": secret_vault_factory(available=False, failure=KeyringNotInstalled())}
+ )
+
+ assert result.exit_code == 0
+ assert "Logged out successfully" not in result.output
+ assert "still in the OS keychain" in result.output
+ assert "pip install 'litellm[cli]'" in result.output
+
+ def test_logout_warns_when_the_keychain_refuses_to_release_the_entry(
+ self, isolated_home, secret_vault_factory
+ ):
+ """A locked keychain leaves a live credential behind that the user believes is gone."""
+ vault = secret_vault_factory(
+ blob=_secret_blob("https://test.example.com", "sk-stored"), erasable=False
+ )
+ _write_token_file(isolated_home, key=None)
+
+ result = self.runner.invoke(logout, obj={"secret_vault": vault})
+
+ assert result.exit_code == 0
+ assert "Logged out successfully" not in result.output
+ assert "still in the OS keychain" in result.output
+ assert "Unlock your keychain" in result.output
+
+ def test_logout_from_a_file_only_login_stays_quiet(self, isolated_home, secret_vault_factory):
+ """The credential never went to a keychain, so removing the file is the whole logout and
+ warning about a keychain entry would send the user chasing one that cannot exist."""
+ _write_token_file(isolated_home, key="sk-in-file")
+
+ result = self.runner.invoke(
+ logout, obj={"secret_vault": secret_vault_factory(available=False, failure=KeyringNotInstalled())}
+ )
+
+ assert result.exit_code == 0
+ assert "Logged out successfully" in result.output
+ assert "still in the OS keychain" not in result.output
class TestWhoamiCommand: