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): finish a refused token file rewrite in place
mateo-berri4ca1f3148a9d
diff --git a/litellm/litellm_core_utils/cli_token_utils.py b/litellm/litellm_core_utils/cli_token_utils.pyindex f2c0f8ed001..2f45742ce03 100644--- a/litellm/litellm_core_utils/cli_token_utils.py+++ b/litellm/litellm_core_utils/cli_token_utils.py@@ -38,6 +38,7 @@ 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,)@@ -180,7 +181,7 @@ def clear_cli_token(*, vault: SecretVault = SYSTEM_KEYRING) -> SecretClear:if not settled and _keep_the_unchecked_keychain_on_record(outcome, record):return outcomeremoval: Final = _remove_token_file()- if removal is not None and record is not None and record.key is not None:+ if removal is not None and record is not None and not _scrub_file_secret(record):return removalreturn SecretErased() if settled else outcome@@ -198,8 +199,9 @@ def _keep_the_unchecked_keychain_on_record(outcome: SecretErase, record: CliTokeOnly a keychain that could not be reached leaves the question open. One that answered for itselfis remembered without any help from the file, and a file it can still pair a live entry with- would leave the machine signed in to the login that was just ended. A copy that cannot be- replaced with a secret-free one is not kept either, because the secret goes first.+ would leave the machine signed in to the login that was just ended. A copy that will give up+ its secret neither to a staged replacement nor to an overwrite is not kept either, because the+ secret goes first."""if record is None or isinstance(outcome, SecretStranded):return False@@ -210,11 +212,12 @@ def _nothing_left_behind(outcome: SecretErase, record: CliTokenRecord | None) ->"""Whether the keychain can be trusted to hold no credential of ours once the file is gone.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 could not be reached is never trusted, whatever the- file looks like. Even a file holding its own secret says only that the login which wrote it had- no keychain to write to, and the login before it may well have had one: the entry that login- left outlives both the uninstalled package and the file that replaced it. `SecretStranded` is+ whenever the keychain is left unconfirmed, taking the secret out in place when it cannot stage a+ replacement, so a missing file is real evidence rather than the absence of it. Past that, a+ keychain that could not be reached is never trusted, whatever the file looks like. Even a file+ holding its own secret says only that the login which wrote it had no keychain to write to, and+ the login before it may well have had one: the entry that login left outlives both the+ uninstalled package and the file that replaced it. `SecretStranded` isthe keychain answering for itself and outranks the file."""match outcome:@@ -323,6 +326,11 @@ def _migrate_file_secret(record: CliTokenRecord, vault: SecretVault) -> CliTokenbefore the keychain is handed anything. Copying the credential into a second store and onlythen 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@@ -332,7 +340,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_token_file(staged):+ if not _commit_token_file(staged) and not _overwrite_file_secret(record):vault.erase()return record@@ -342,7 +350,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_token_file(staged)+ 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 Truedef _stage_scrubbed_file(record: CliTokenRecord) -> str | None:diff --git a/litellm/litellm_core_utils/private_json.py b/litellm/litellm_core_utils/private_json.pyindex fbeb74aab5a..30f64c8fc27 100644--- a/litellm/litellm_core_utils/private_json.py+++ b/litellm/litellm_core_utils/private_json.py@@ -45,6 +45,21 @@ def commit_staged_json(staged: str, path: str) -> None:raise+def overwrite_private_json(path: str, data: Mapping[str, object]) -> None:+ """Rewrite a file that is already there, in place, keeping the mode it was created with.++ `write_private_json` needs room for a second file and a directory that will accept it, which is+ what a full disk and a read-only `~/.litellm` respectively refuse. Shortening the file already+ in place needs neither. It is not atomic, so an interrupted write leaves a partial file, and it+ never creates one, so it cannot put a world-readable file where a private one was.+ """+ fd: Final = os.open(path, os.O_WRONLY | os.O_TRUNC)+ with os.fdopen(fd, "w") as f:+ json.dump(data, f, indent=2)+ f.flush()+ os.fsync(f.fileno())++def discard_staged_json(staged: str) -> None:"""Throw a staged file away when the change it was part of is abandoned"""Path(staged).unlink(missing_ok=True)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 2830fad58b4..e3d14c6da46 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@@ -480,12 +480,13 @@ class TestScrubFailure:assert json.loads(path.read_text())["key"] == "sk-legacy"assert list(path.parent.glob(".tmp-*")) == []- def test_a_rewrite_that_fails_after_the_keychain_took_the_secret_hands_it_back(+ 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. The keychain copy goes back, so the file is left exactly as- it was found and the move can be tried again."""+ 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)@@ -493,26 +494,30 @@ class TestScrubFailure: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 vault.blob is not None+ assert json.loads(path.read_text()).get("key") is Noneassert 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 keychain that will not give back what it just took leaves 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 condition that caused it."""+ """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 Noneassert 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@@ -657,24 +662,49 @@ class TestClearCliToken:assert vault.blob is not Noneassert "sk-in-file" not in _token_file(isolated_home).read_text()- @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores directory permissions")- def test_a_file_that_can_be_neither_scrubbed_nor_removed_is_reported_not_raised(+ @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, or one left root-owned by a `sudo lite login`, refuses the- scrubbed rewrite and the removal alike. 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."""+ """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 directory permissions")def test_a_metadata_file_that_will_not_go_is_not_worth_alarming_the_user_over(self, isolated_home, secret_vault_factorydiff --git a/tests/test_litellm/litellm_core_utils/test_private_json.py b/tests/test_litellm/litellm_core_utils/test_private_json.pynew file mode 100644index 00000000000..cedff61959f--- /dev/null+++ b/tests/test_litellm/litellm_core_utils/test_private_json.py@@ -0,0 +1,37 @@+import json+import os+import stat++import pytest++from litellm.litellm_core_utils.private_json import overwrite_private_json, write_private_json+++class TestOverwritePrivateJson:+ def test_replaces_the_contents_of_the_file_already_there(self, tmp_path):+ path = tmp_path / "token.json"+ write_private_json(str(path), {"key": "sk-" + "a" * 700})++ overwrite_private_json(str(path), {"user_id": "u-1"})++ assert json.loads(path.read_text()) == {"user_id": "u-1"}++ def test_refuses_to_create_the_file_it_was_asked_to_rewrite(self, tmp_path):+ """This is the one writer that does not go through a private temp file, so a path it creates+ would land with whatever the umask allows. Refusing keeps it unable to put a world-readable+ file where the caller believed a private one already was."""+ path = tmp_path / "token.json"++ with pytest.raises(FileNotFoundError):+ overwrite_private_json(str(path), {"user_id": "u-1"})++ assert not path.exists()++ @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores file permissions")+ def test_keeps_the_owner_only_mode_the_file_was_created_with(self, tmp_path):+ path = tmp_path / "token.json"+ write_private_json(str(path), {"key": "sk-live"})++ overwrite_private_json(str(path), {"user_id": "u-1"})++ assert stat.S_IMODE(path.stat().st_mode) == 0o600diff --git a/tests/test_litellm/proxy/client/cli/test_auth_commands.py b/tests/test_litellm/proxy/client/cli/test_auth_commands.pyindex 71fc1cd3e6a..8191a8edca7 100644--- a/tests/test_litellm/proxy/client/cli/test_auth_commands.py+++ b/tests/test_litellm/proxy/client/cli/test_auth_commands.py@@ -492,23 +492,47 @@ class TestLogoutCommand:assert "still in the OS keychain" in result.outputassert "Unlock your keychain" in result.output- @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores directory permissions")- def test_logout_reports_a_token_file_it_cannot_remove(self, isolated_home, secret_vault_factory):- """`lite logout` on a read-only ~/.litellm used to end in a PermissionError traceback with- the credential still sitting in the file. The user has to be told what is left and where."""+ @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores file permissions")+ def test_logout_reports_a_token_file_it_cannot_clear(self, isolated_home, secret_vault_factory):+ """`lite logout` on a read-only ~/.litellm holding a read-only token file used to end in a+ PermissionError traceback with the credential still sitting in the file. The user has to be+ told what is left and where."""_write_token_file(isolated_home, key="sk-in-file")config_dir = isolated_home / ".litellm"+ path = config_dir / "token.json"+ path.chmod(0o400)config_dir.chmod(0o500)try:result = self.runner.invoke(logout, obj={"secret_vault": secret_vault_factory()})finally:config_dir.chmod(0o700)+ path.chmod(0o600)assert result.exit_code == 0assert "Logged out successfully" not in result.outputassert "still in" in result.outputassert str(config_dir / "token.json") in result.output+ @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores directory permissions")+ def test_logout_on_a_read_only_directory_still_takes_the_secret_out_of_the_file(+ self, isolated_home, secret_vault_factory+ ):+ """A ~/.litellm that will accept no replacement file and no removal still lets the file it+ has be shortened, so the logout the user asked for happens rather than being handed back to+ them with instructions."""+ _write_token_file(isolated_home, key="sk-in-file")+ config_dir = isolated_home / ".litellm"+ path = config_dir / "token.json"+ config_dir.chmod(0o500)+ try:+ result = self.runner.invoke(logout, obj={"secret_vault": secret_vault_factory()})+ finally:+ config_dir.chmod(0o700)++ assert result.exit_code == 0+ assert "Logged out successfully" in result.output+ assert "sk-in-file" not in path.read_text()+def test_logout_without_the_keyring_package_still_warns_about_a_file_held_secret(self, isolated_home, secret_vault_factory):