litellm/tests/unit/proxy/client/cli/test_up_commands.py
norkelbyte dc378de207
fix(cli): let Claude Code renew a --pkce login's key through lite's apiKeyHelper (#51319)
* fix(cli): let Claude Code renew a --pkce login's key through lite's apiKeyHelper

* fix(cli): keep an explicit --api-key over lite's apiKeyHelper and persist its absolute path

An explicit --api-key or LITELLM_PROXY_API_KEY is now exported to Claude Code
even when lite's renewing helper is configured, since the helper prints the
stored login's key instead. The helper command also uses the absolute path of
the lite found on PATH, so a relative PATH entry cannot make Claude Code run
another repository's bin/lite

* fix(cli): keep an explicit key and --pkce when lite's renewing helper is set

A --settings that blanks apiKeyHelper now keeps the exported key, and a key passed with --api-key turns lite's helper off for that launch, so Claude Code no longer warns about two credentials or sends the stored login's key beside it

The helper names the lite installed beside the Python that ran the login before one found on PATH, so a pyenv shim no longer fails in projects pinned to another Python

lite claude signs in again with --pkce when the stored login used it, and print-token's hints name the proxy and --pkce

* fix(cli): keep a shell token from beating the renewing helper and reuse --pkce only for the same proxy

The --pkce --config-claude login now writes an empty env.ANTHROPIC_AUTH_TOKEN beside the helper, since a token exported in the shell wins over apiKeyHelper

lite claude sends any other key through a private settings file that blanks the helper and merges the user's own --settings

A re-login keeps --pkce only when the stored login is for the same proxy, else the saved default decides

* fix(cli): let any lite install's helper renew for its proxy and name the renewing login in print-token hints

lite claude now treats a lite auth print-token helper for this proxy as renewing whichever lite path it names, since every lite reads the same token store

Every print-token hint to sign in again, including an expired key and an unreadable keychain, names lite login --pkce with the proxy

Shorter docstrings

* fix(cli): send a launch key to the proxy it was issued for

The private settings file lite claude writes for a key that lite's helper would not renew now also sets ANTHROPIC_BASE_URL. Without it, lite --base-url B --api-key <B key> claude after a --pkce --config-claude login to A sent the B key to A, since the login's settings point Claude Code at A

* fix(proxy): preserve caller metadata on auth failures (#51745)

* fix(proxy): keep x-litellm-spend-logs-metadata on auth-rejected failure spend logs

Budget, invalid-key and other auth-stage rejections are raised before the
request headers are merged into metadata, so the persisted failure row lost
the caller's spend logs metadata header. The auth failure handler now parses
it with the same pre-call helper and stamps it into the metadata bucket it
already uses for the requester IP and user agent.

* fix(proxy): type the spend logs metadata header parser honestly

The parser takes the request headers as a str mapping and returns the parsed
JSON as object, which is what successful requests already store. The auth
failure path keeps only JSON objects. The precedence regression now also
asserts the caller's request body is left untouched.

* fix(proxy): stamp the auth failure spend logs metadata into the route's bucket

A chat request whose body also carried litellm_metadata got the header in
litellm_metadata, which the failure spend row never reads on chat routes.
The header now goes into the bucket picked by metadata_variable_name_for_request
for the route, and the failure row lifts spend_logs_metadata from that bucket
the same way it already lifts the requester IP and user agent. The regression
tests now assert on the built failure spend row.

* fix(proxy): keep the auth failure spend logs metadata fix inside the auth handler

Restores the failure spend row's lifted fields to main, so failures after auth
on litellm_metadata routes keep their current logging. The auth handler now
writes the parsed header into metadata, which the failure spend row reads on
every route, and into the route's own bucket for callbacks on litellm_metadata
routes.

* fix(proxy): make the spend logs metadata header field read-only and test the real spend writer

The header collector now sets spend_logs_metadata when it is built, so the
field can be ReadOnly with the same stored value. The auth failure tests run
the real DBSpendUpdateWriter and read the queued spend log row from a fake
database client instead of an autospec writer.

* test(proxy): read auth failure spend rows from a real unconnected PrismaClient

Replaces the mocked database client and the class-level queue byte reset.
The test now enqueues into a real PrismaClient's own queue and dequeues
its row in cleanup, which keeps the shared byte counter balanced.

---------

Co-authored-by: Joshua Valluru <326636767+joshua-berri@users.noreply.github.com>

* fix(logging): keep a content-block system prompt in logged messages (#51699)

* fix(logging): keep a content-block system prompt in logged messages

A /v1/messages request whose top-level system prompt is a list of content
blocks never reached the logged messages, because only a plain-text system
prompt was prepended. Accept a non-empty list too, so every logger that reads
messages sees it. Claude on Vertex also normalizes a plain-text system prompt
into blocks, so it was dropped there as well.

Fixes #36402

* fix(logging): type the logged system message

* fix(logging): type the system message without a mutable annotation, close the test client

* refactor(mcp): let the semantic filter take its MCP tool loader as a parameter (#50483)

* test(mcp): check the tool dict conversion without patching the MCP handler

* refactor(mcp): let the semantic filter take its MCP tool loader as a parameter

* refactor(mcp): type the semantic filter's default tool loader

Annotate the chosen loader as _OpenAIToolLoader and narrow its return to
FunctionToolParam, so a default that returns raw MCP tools fails the type
check. Drop the unused patch import.

* fix(mcp): give the MCP client exactly the servers left on in the connect page (#50973)

* fix(cli): send the launch key under a project apiKeyHelper and give each key its own settings file

A `lite login --pkce --config-claude` leaves an empty ANTHROPIC_AUTH_TOKEN in Claude Code's user settings. When a repo's project settings set their own apiKeyHelper, `lite claude` skipped its private settings file, so the empty token hid the exported key and Claude Code sent the project helper's key. `lite claude` now also writes that file whenever the settings files leave ANTHROPIC_AUTH_TOKEN empty

Every key launch also wrote the one file `--subscription` uses, so two launches started together could read each other's key and proxy. A key launch's file is now named after a hash of its contents, and every overlay is written to a temp file and renamed so a starting Claude Code never reads half of one

* fix(proxy): keep carried end-user spend when a budget reset is retried (#51143)

* fix(proxy): keep carried end-user spend when a budget reset is retried

End-user pages commit before the budget window advance. When the advance
failed, the tier stayed due and the next tick replayed every page, so a
rollover-capped row already cut to its carryover (15 -> 5) matched the
under-cap zero and lost it, and spend accrued since the first pass was
zeroed again. Each end-user reset now stamps the tier window it closes
in a new spend_reset_window column and skips rows already stamped with it.

Fixes #50898

* fix(proxy): leave never-reset tiers unguarded and test each tier's own window

A tier with no budget_reset_at falls back to the old unguarded reset
instead of stamping created_at, which an admin clearing the reset time
would reuse and silently skip end users. Tests now give tiers distinct
windows and cover a second window closing.

* test(proxy): give the end-user ledger its own fake prisma client

* fix(proxy): pin a reset time on tiers without one before end-user pages commit

* fix(proxy): read the reset-time pin from the writer and skip tiers another sweep advanced

* fix(proxy): keep linked rows of a tier another sweep advanced out of the rollover reset

* fix(proxy): order the end-user reset window migration after upstream's same-timestamp migration

* fix(proxy): reset end users again when an admin moves a tier's reset time back to a closed window

* fix(proxy): clear end-user reset stamps in the same transaction as the tier's reset time

A failed /budget/update used to leave the new reset time written with the
stamps still set, so repeating the request found the time unchanged and
skipped the clear. The update and the clear now commit together, and a
reset time in the future no longer scans the tier's end users

* fix(proxy): name each end-user reset window by the tier's last write

Stamp end-user resets with the tier's updated_at read on the writer instead
of its reset time. A failed window advance leaves updated_at as it was, so the
retry still skips the end users already reset, while the advance or any
/budget/update moves it and opens a new window. That covers a forced reset on
the default end-user tier and drops the stamp clear, so /budget/update is the
one-row update it is on main. The writer read also leaves out a tier another
sweep already advanced, which a lagging read replica still showed as due

* fix(proxy): name end-user reset windows by the tier and its advance count

Tiers advanced in one batch share updated_at, so a customer moved between
them could skip the new tier's reset, and any unrelated tier edit during a
failed advance reopened the window. A budget_reset_count that only the
window advance bumps, prefixed with the tier id, names the window instead.

* fix(proxy): keep carried spend for customer teams and members on a retried reset

Customer team and member pages commit before the window advance like end-user
pages, so they now stamp the window they close and a retry skips them too. A
member runs on its unexpired override when that has its own duration, else on
its template.

The window name now joins the tier id, its creation time, its count of closed
windows and its reset time, so a duration change or a tier recreated under the
same id opens a new window even when the advance failed.

* test(integration): list every budget column and relation in the budget update field check

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>

* test(otel): keep proxy startup out of the per-test timeout in the excluded services matrix (#51759)

Co-authored-by: mateo <277851410+mateo-berri@users.noreply.github.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(cli): skip the working directory when the login looks up lite for its helper

On Windows, shutil.which searches the current directory before the directories it is given, so a lite.exe planted in the repo where someone ran `lite login --pkce --config-claude` could become their user-level apiKeyHelper

The login now checks each directory by full path, this Python's scripts directory first and then each PATH entry, skipping empty entries

* fix(bedrock): answer 400 for service tiers Bedrock cannot serve, forward reserved (#50516)

* fix(bedrock): answer 400 for service tiers Bedrock cannot serve, forward reserved

Converse used to drop any service_tier outside default, flex, and priority
with no error, rewrite auto to default, and drop reserved. Now reserved and
standard_only map to Bedrock tiers, auto sends no tier, and any other value
answers 400 unless drop_params is on. Nova batch rows honor the row's
drop_params.

* fix(bedrock): keep a Responses batch row's drop_params and keep it out of passthrough rows

* test(bedrock): annotate service tier test locals as Final and drop the row helper's kwargs

* fix(bedrock): refuse a service tier on Nova batch rows unless drop_params, and honor the deployment's drop_params

* fix(bedrock): map standard and any-case service tiers, and drop tiers from Claude batch rows under the deployment's drop_params

* fix(bedrock): forward the tiers OpenAI-format batch rows take, accept auto on Claude rows, and label tiers in lowercase

* fix(bedrock): mark the service tier block field read-only

* fix(bedrock): read drop_params given as a string on batch rows, and cover the Nova row mapper's drop_params

* test(prometheus): sort the service tier label test imports

* fix(bedrock): send the Invoke route's service tier as a header and name the accepted tiers in the 400

* fix(bedrock): report and bill the tier Bedrock served on Invoke calls and streams, and send the tier header only to Nova

* fix(bedrock): return copies when stamping the served tier, read its header without re-encoding the others, and pin it per stream chunk

The Nova Invoke mapper and the event-stream decoder now return model_copy results instead of writing service_tier in place. One shared reader finds the X-Amzn-Bedrock-Service-Tier response header case-insensitively, so a non-ASCII request id no longer breaks the stream decoder, and the passthrough uses the same reader. Tests now vary the served tier in both directions, check every chunk, and cover a stream with no tier header or an empty one

* test(bedrock): check the served tier on a stream whose headers come as a plain dict with an upper-case name

The non-ASCII request id stream test now also carries X-AMZN-BEDROCK-SERVICE-TIER in a plain dict and asserts every chunk reports that tier, so a case-sensitive header reader or a lookup by the canonical name fails it

* refactor(bedrock): drop the passthrough's own service tier header reader that main re-added

The passthrough already reads the served tier through the shared case-insensitive reader in common_utils, so the httpx.Headers copy main brought back with the embeddings change has no callers and references a constant this branch removed

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>

* fix(cli): delete the key files lite claude leaves on logout and unconfigure

lite claude hands its process to Claude Code, so the --settings files holding
its key stayed in the Claude config dir. lite logout and lite unconfigure claude
now delete them, and Claude Code reads one only at startup, so open sessions
keep working

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
Co-authored-by: joshua-berri <joshua@berri.ai>
Co-authored-by: Joshua Valluru <326636767+joshua-berri@users.noreply.github.com>
Co-authored-by: ryan-crabbe-berri <ryan@berri.ai>
Co-authored-by: shrey <shrey@berri.ai>
Co-authored-by: Ankit Jha <45779665+PyExtreme@users.noreply.github.com>
Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: quietjules <349048734+quietjules@users.noreply.github.com>
2026-11-14 04:04:38 +00:00

643 lines
29 KiB
Python

import json
import shutil
import stat
import sys
import time
from unittest.mock import patch
import click
import pytest
from click.testing import CliRunner
from litellm.proxy.client.cli.commands import up as up_module
from litellm.proxy.client.cli.commands.agents import AgentRunError
from litellm.proxy.client.cli.commands.claude_settings import ClaudeSettingsError, StaticToken
from litellm.proxy.client.cli.commands.up import (
BackupRecord,
UpError,
down,
ensure_fresh_login,
load_json_or_empty,
merge_claude_settings,
read_backup,
restore_claude_settings,
up,
write_backup,
)
UP_MODULE = "litellm.proxy.client.cli.commands.up"
AUTH_MODULE = "litellm.proxy.client.cli.commands.auth"
def _patch_paths(monkeypatch, tmp_path):
settings_path = tmp_path / "claude_settings.json"
backup_path = tmp_path / "backup.json"
monkeypatch.setattr(up_module, "CLAUDE_SETTINGS_PATH", settings_path)
monkeypatch.setattr(up_module, "BACKUP_PATH", backup_path)
return settings_path, backup_path
class TestMergeClaudeSettings:
def test_preserves_unrelated_top_level_keys(self):
merged = merge_claude_settings({"theme": "dark"}, "http://localhost:4000", StaticToken("sk-fresh"), status_line="statusline-cmd")
assert merged["theme"] == "dark"
def test_preserves_unrelated_env_keys(self):
settings = {"env": {"SOME_OTHER_VAR": "value"}}
merged = merge_claude_settings(settings, "http://localhost:4000", StaticToken("sk-fresh"), status_line="statusline-cmd")
assert merged["env"]["SOME_OTHER_VAR"] == "value"
def test_overrides_base_url_and_strips_an_old_helper(self):
settings = {
"env": {"ANTHROPIC_BASE_URL": "https://old.example.com"},
"apiKeyHelper": "old-helper",
}
merged = merge_claude_settings(settings, "http://localhost:4000/", StaticToken("sk-fresh"), status_line="statusline-cmd")
assert merged["env"]["ANTHROPIC_BASE_URL"] == "http://localhost:4000"
assert merged["env"]["ANTHROPIC_AUTH_TOKEN"] == "sk-fresh"
assert merged["env"]["ENABLE_TOOL_SEARCH"] == "true"
assert merged["env"]["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "1"
assert "apiKeyHelper" not in merged
def test_preserves_existing_gateway_model_discovery(self):
settings = {"env": {"CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "0"}}
merged = merge_claude_settings(settings, "http://localhost:4000", StaticToken("sk-fresh"), status_line="statusline-cmd")
assert merged["env"]["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "0"
def test_preserves_existing_tool_search(self):
settings = {"env": {"ENABLE_TOOL_SEARCH": "false"}}
merged = merge_claude_settings(settings, "http://localhost:4000", StaticToken("sk-fresh"), status_line="statusline-cmd")
assert merged["env"]["ENABLE_TOOL_SEARCH"] == "false"
def test_drops_stray_api_key(self):
settings = {"env": {"ANTHROPIC_API_KEY": "leaked-key"}}
merged = merge_claude_settings(settings, "http://localhost:4000", StaticToken("sk-fresh"), status_line="statusline-cmd")
assert "ANTHROPIC_API_KEY" not in merged["env"]
def test_works_from_empty_settings(self):
merged = merge_claude_settings({}, "http://localhost:4000", StaticToken("sk-fresh"), status_line="statusline-cmd")
assert merged["env"] == {
"ANTHROPIC_BASE_URL": "http://localhost:4000",
"ANTHROPIC_AUTH_TOKEN": "sk-fresh",
"ENABLE_TOOL_SEARCH": "true",
"CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1",
}
assert "apiKeyHelper" not in merged
def test_does_not_mutate_input(self):
settings = {"env": {"FOO": "bar"}}
merge_claude_settings(settings, "http://localhost:4000", StaticToken("sk-fresh"), status_line="statusline-cmd")
assert settings == {"env": {"FOO": "bar"}}
class TestLoadJsonOrEmpty:
def test_returns_empty_dict_when_file_does_not_exist(self, tmp_path):
assert load_json_or_empty(tmp_path / "missing.json") == {}
def test_returns_empty_dict_when_file_is_empty(self, tmp_path):
path = tmp_path / "settings.json"
path.write_text("")
assert load_json_or_empty(path) == {}
def test_returns_empty_dict_when_file_is_whitespace_only(self, tmp_path):
path = tmp_path / "settings.json"
path.write_text(" \n")
assert load_json_or_empty(path) == {}
def test_parses_real_content(self, tmp_path):
path = tmp_path / "settings.json"
path.write_text(json.dumps({"theme": "dark"}))
assert load_json_or_empty(path) == {"theme": "dark"}
def test_raises_clean_error_on_invalid_json(self, tmp_path):
path = tmp_path / "settings.json"
path.write_text("not json at all {{{")
with pytest.raises(ClaudeSettingsError, match="invalid JSON"):
load_json_or_empty(path)
def test_raises_clean_error_on_non_object_root(self, tmp_path):
path = tmp_path / "settings.json"
path.write_text(json.dumps([1, 2, 3]))
with pytest.raises(ClaudeSettingsError, match="invalid JSON"):
load_json_or_empty(path)
class TestBackupRoundTrip:
def test_restores_original_content_when_file_existed(self, monkeypatch, tmp_path):
settings_path, backup_path = _patch_paths(monkeypatch, tmp_path)
original = {"apiKeyHelper": "old-helper", "theme": "dark"}
settings_path.write_text(json.dumps(original))
write_backup(BackupRecord(existed=True, content=original))
settings_path.write_text(json.dumps({"apiKeyHelper": "lite-helper"}))
restored = restore_claude_settings()
assert restored is not None
assert restored.existed is True
assert json.loads(settings_path.read_text()) == original
assert not backup_path.exists()
def test_deletes_settings_file_when_it_did_not_exist_before(self, monkeypatch, tmp_path):
settings_path, backup_path = _patch_paths(monkeypatch, tmp_path)
write_backup(BackupRecord(existed=False, content=None))
settings_path.write_text(json.dumps({"apiKeyHelper": "lite-helper"}))
restored = restore_claude_settings()
assert restored is not None
assert restored.existed is False
assert not settings_path.exists()
assert not backup_path.exists()
def test_no_backup_is_a_no_op_returning_none(self, monkeypatch, tmp_path):
settings_path, _backup_path = _patch_paths(monkeypatch, tmp_path)
assert restore_claude_settings() is None
assert not settings_path.exists()
def test_restore_writes_owner_only_and_through_a_symlink(self, monkeypatch, tmp_path):
# The backup can hold a token the user had in the file before `up`; a plain open() would put it
# back under the umask, and would replace a dotfiles symlink with a regular file.
target = tmp_path / "dotfiles" / "settings.json"
target.parent.mkdir()
target.write_text("{}")
target.chmod(0o644)
settings_path = tmp_path / "settings.json"
settings_path.symlink_to(target)
monkeypatch.setattr(up_module, "CLAUDE_SETTINGS_PATH", settings_path)
monkeypatch.setattr(up_module, "BACKUP_PATH", tmp_path / "backup.json")
write_backup(BackupRecord(existed=True, content={"env": {"ANTHROPIC_AUTH_TOKEN": "sk-theirs"}}))
restore_claude_settings()
assert settings_path.is_symlink()
assert json.loads(target.read_text()) == {"env": {"ANTHROPIC_AUTH_TOKEN": "sk-theirs"}}
assert stat.S_IMODE(target.stat().st_mode) == 0o600
def test_recreates_claude_dir_if_it_was_deleted_while_up_was_running(self, monkeypatch, tmp_path):
"""If ~/.claude/ is removed while `lite up` holds it open, restoring must recreate the
directory rather than crash with FileNotFoundError and strand the backup file, which
would otherwise permanently break every future `lite down`."""
claude_dir = tmp_path / "claude_dir"
settings_path = claude_dir / "settings.json"
backup_path = tmp_path / "backup.json"
monkeypatch.setattr(up_module, "CLAUDE_SETTINGS_PATH", settings_path)
monkeypatch.setattr(up_module, "BACKUP_PATH", backup_path)
original = {"theme": "dark"}
claude_dir.mkdir(parents=True)
write_backup(BackupRecord(existed=True, content=original))
shutil.rmtree(claude_dir)
restored = restore_claude_settings()
assert restored is not None
assert json.loads(settings_path.read_text()) == original
assert not backup_path.exists()
def test_read_backup_round_trips_write_backup(self, monkeypatch, tmp_path):
_patch_paths(monkeypatch, tmp_path)
write_backup(BackupRecord(existed=True, content={"a": 1}))
assert read_backup() == BackupRecord(existed=True, content={"a": 1})
def test_read_backup_missing_file_returns_none(self, monkeypatch, tmp_path):
_patch_paths(monkeypatch, tmp_path)
assert read_backup() is None
def test_read_backup_raises_clean_error_on_corrupt_content(self, monkeypatch, tmp_path):
_settings_path, backup_path = _patch_paths(monkeypatch, tmp_path)
backup_path.parent.mkdir(parents=True, exist_ok=True)
backup_path.write_text("not json at all {{{")
with pytest.raises(UpError, match="invalid or unexpected JSON"):
read_backup()
def test_write_backup_restricts_permissions_for_a_new_file(self, monkeypatch, tmp_path):
_settings_path, backup_path = _patch_paths(monkeypatch, tmp_path)
write_backup(BackupRecord(existed=True, content={"a": 1}))
assert stat.S_IMODE(backup_path.stat().st_mode) == 0o600
def test_write_backup_restricts_permissions_of_a_preexisting_permissive_file(self, monkeypatch, tmp_path):
_settings_path, backup_path = _patch_paths(monkeypatch, tmp_path)
backup_path.parent.mkdir(parents=True, exist_ok=True)
backup_path.write_text("{}")
backup_path.chmod(0o644)
write_backup(BackupRecord(existed=True, content={"a": 1}))
assert stat.S_IMODE(backup_path.stat().st_mode) == 0o600
def test_backup_file_always_removed_after_restore(self, monkeypatch, tmp_path):
_settings_path, backup_path = _patch_paths(monkeypatch, tmp_path)
write_backup(BackupRecord(existed=False, content=None))
assert backup_path.exists()
restore_claude_settings()
assert not backup_path.exists()
def _make_ctx(base_url):
return click.Context(click.Command("test"), obj={"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, "get_stored_api_key", self.get_stored_api_key)
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, config_claude=False, pkce=False):
assert config_claude is False, "`lite up` patches settings itself; the login it starts must not also configure"
login_calls.append((ctx.obj["base_url"], pkce))
on_login()
monkeypatch.setattr(up_module, "login", fake_login)
return login_calls
class TestEnsureFreshLogin:
"""A token that is fresh but was issued for a *different* proxy must not be trusted: without
this check, a user logged into proxy A who runs `up --base-url proxy-b` would silently get proxy A's
real token written into settings pointed at proxy B."""
def test_reuses_a_fresh_token_issued_for_the_same_proxy(self, monkeypatch):
_FakeTokenStore(
monkeypatch, {"key": "sk-a", "base_url": "http://proxy-a:4000"}, {"http://proxy-a:4000": "sk-a"}
)
monkeypatch.setattr(up_module, "is_cli_token_fresh", lambda token_data: True)
login_calls = _capture_login(monkeypatch)
ensure_fresh_login(_make_ctx("http://proxy-a:4000"))
assert login_calls == []
def test_forces_a_fresh_login_when_the_cached_token_is_for_a_different_proxy(self, monkeypatch):
monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: True)
store = _FakeTokenStore(monkeypatch, {"key": "sk-a", "base_url": "http://proxy-a:4000"}, {})
monkeypatch.setattr(up_module, "is_cli_token_fresh", lambda token_data: True)
login_calls = _capture_login(
monkeypatch, on_login=lambda: store.log_in({"key": "sk-b", "base_url": "http://proxy-b:4000"}, "sk-b")
)
ensure_fresh_login(_make_ctx("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)
store = _FakeTokenStore(monkeypatch, {"base_url": "http://proxy-a:4000"}, {})
monkeypatch.setattr(up_module, "is_cli_token_fresh", lambda token_data: True)
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", 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)
_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="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_a_stale_pkce_credential_for_another_proxy_leaves_the_login_mode_to_the_saved_default(self, monkeypatch):
monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: True)
store = _FakeTokenStore(monkeypatch, _pkce_record("http://proxy-a:4000", seconds_left=-10), {})
monkeypatch.setattr(up_module, "pkce_default", lambda: False)
login_calls = _capture_login(
monkeypatch,
on_login=lambda: store.log_in(_pkce_record("http://proxy-b:4000", seconds_left=86_400), "sk-b"),
)
ensure_fresh_login(_make_ctx("http://proxy-b:4000"))
assert login_calls == [("http://proxy-b:4000", False)]
def test_logs_in_with_pkce_when_the_saved_pkce_default_is_on(self, monkeypatch):
"""`lite config set pkce true` is honoured by the login `lite up` starts, not only by `lite login`."""
monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: True)
store = _FakeTokenStore(monkeypatch, {"key": "sk-a", "base_url": "http://proxy-a:4000"}, {})
monkeypatch.setattr(up_module, "is_cli_token_fresh", lambda token_data: True)
monkeypatch.setattr(up_module, "pkce_default", lambda: True)
login_calls = _capture_login(
monkeypatch,
on_login=lambda: store.log_in(_pkce_record("http://proxy-b:4000", seconds_left=86_400), "sk-pkce-fresh"),
)
ensure_fresh_login(_make_ctx("http://proxy-b:4000"))
assert login_calls == [("http://proxy-b:4000", True)]
def test_names_the_pkce_login_in_the_non_interactive_error_when_the_saved_pkce_default_is_on(self, monkeypatch):
monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: False)
_FakeTokenStore(monkeypatch, {"key": "sk-a", "base_url": "http://proxy-a:4000"}, {})
monkeypatch.setattr(up_module, "is_cli_token_fresh", lambda token_data: True)
monkeypatch.setattr(up_module, "pkce_default", lambda: True)
with pytest.raises(UpError, match="Run `lite login --pkce` first"):
ensure_fresh_login(_make_ctx("http://proxy-b:4000"))
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):
self.runner = CliRunner()
def test_refuses_double_start_without_touching_settings_file(self, monkeypatch, tmp_path):
settings_path, backup_path = _patch_paths(monkeypatch, tmp_path)
existing_backup = {"existed": False, "content": None}
backup_path.write_text(json.dumps(existing_backup))
with (
patch(f"{UP_MODULE}.load_token", return_value={"key": "sk-fresh", "base_url": "http://localhost:4000"}),
patch(f"{UP_MODULE}.get_stored_api_key", return_value="sk-fresh"),
patch(f"{UP_MODULE}.is_cli_token_fresh", return_value=True),
patch(f"{UP_MODULE}.resolve_api_key", return_value="sk-fresh"),
patch(f"{UP_MODULE}.verify_proxy_key"),
):
result = self.runner.invoke(up, obj={"base_url": "http://localhost:4000"})
assert result.exit_code != 0
assert "already" in result.output
assert "lite down" in result.output
assert not settings_path.exists()
assert json.loads(backup_path.read_text()) == existing_backup
def test_no_fresh_login_non_interactive_fails_cleanly(self, monkeypatch, tmp_path):
_patch_paths(monkeypatch, tmp_path)
monkeypatch.setattr(sys.stdin, "isatty", lambda: False)
with (
patch(f"{UP_MODULE}.load_token", return_value=None),
patch(f"{UP_MODULE}.get_stored_api_key", return_value=None),
):
result = self.runner.invoke(up, obj={"base_url": "http://localhost:4000"})
assert result.exit_code != 0
assert "lite login" in result.output
def test_unreachable_proxy_fails_cleanly(self, monkeypatch, tmp_path):
_patch_paths(monkeypatch, tmp_path)
with (
patch(f"{UP_MODULE}.load_token", return_value={"key": "sk-fresh", "base_url": "http://localhost:4000"}),
patch(f"{UP_MODULE}.get_stored_api_key", return_value="sk-fresh"),
patch(f"{UP_MODULE}.is_cli_token_fresh", return_value=True),
patch(f"{UP_MODULE}.resolve_api_key", return_value="sk-fresh"),
patch(
f"{UP_MODULE}.verify_proxy_key",
side_effect=AgentRunError("Could not reach the LiteLLM proxy at http://localhost:4000"),
),
):
result = self.runner.invoke(up, obj={"base_url": "http://localhost:4000"})
assert result.exit_code != 0
assert "Could not reach the LiteLLM proxy" in result.output
def test_happy_path_writes_settings_and_backup_then_restores_on_stop(self, monkeypatch, tmp_path):
settings_path, backup_path = _patch_paths(monkeypatch, tmp_path)
original = {"theme": "dark"}
settings_path.write_text(json.dumps(original))
settings_path.chmod(0o644)
captured = {}
def fake_wait(self, timeout=None):
captured["settings"] = json.loads(settings_path.read_text())
captured["settings_mode"] = stat.S_IMODE(settings_path.stat().st_mode)
captured["backup_existed"] = backup_path.exists()
return True
with (
patch(f"{UP_MODULE}.load_token", return_value={"key": "sk-fresh", "base_url": "http://localhost:4000"}),
patch(f"{UP_MODULE}.get_stored_api_key", return_value="sk-fresh"),
patch(f"{UP_MODULE}.is_cli_token_fresh", return_value=True),
patch(f"{UP_MODULE}.resolve_api_key", return_value="sk-fresh"),
patch(f"{UP_MODULE}.verify_proxy_key"),
patch(f"{UP_MODULE}.signal.signal"),
patch(f"{UP_MODULE}.atexit.register"),
patch("threading.Event.wait", new=fake_wait),
):
result = self.runner.invoke(up, obj={"base_url": "http://localhost:4000"})
assert result.exit_code == 0, result.output
assert captured["backup_existed"] is True
assert captured["settings"]["theme"] == "dark"
assert captured["settings"]["env"]["ANTHROPIC_BASE_URL"] == "http://localhost:4000"
assert captured["settings"]["env"]["ENABLE_TOOL_SEARCH"] == "true"
assert captured["settings"]["env"]["ANTHROPIC_AUTH_TOKEN"] == "sk-fresh"
# The file now carries the key, so the umask (and the file's earlier 0644) must not decide who reads it.
assert captured["settings_mode"] == 0o600
assert "apiKeyHelper" not in captured["settings"]
assert captured["settings"]["statusLine"]["command"].endswith("statusline.py")
assert json.loads(settings_path.read_text()) == original
assert not backup_path.exists()
class TestDownCommand:
def setup_method(self):
self.runner = CliRunner()
def test_restores_when_backup_exists(self, monkeypatch, tmp_path):
settings_path, backup_path = _patch_paths(monkeypatch, tmp_path)
original = {"apiKeyHelper": "old-helper"}
write_backup(BackupRecord(existed=True, content=original))
settings_path.write_text(json.dumps({"apiKeyHelper": "lite-helper"}))
result = self.runner.invoke(down)
assert result.exit_code == 0, result.output
assert "Restored" in result.output
assert json.loads(settings_path.read_text()) == original
assert not backup_path.exists()
def test_removes_settings_file_when_it_did_not_exist_before(self, monkeypatch, tmp_path):
settings_path, _backup_path = _patch_paths(monkeypatch, tmp_path)
write_backup(BackupRecord(existed=False, content=None))
settings_path.write_text(json.dumps({"apiKeyHelper": "lite-helper"}))
result = self.runner.invoke(down)
assert result.exit_code == 0, result.output
assert "Removed" in result.output
assert not settings_path.exists()
def test_prints_nothing_to_restore_when_no_backup(self, monkeypatch, tmp_path):
_patch_paths(monkeypatch, tmp_path)
result = self.runner.invoke(down)
assert result.exit_code == 0, result.output
assert "Nothing to restore." in result.output
def test_surfaces_clean_error_on_a_corrupt_backup_file(self, monkeypatch, tmp_path):
_settings_path, backup_path = _patch_paths(monkeypatch, tmp_path)
backup_path.parent.mkdir(parents=True, exist_ok=True)
backup_path.write_text("not json at all {{{")
result = self.runner.invoke(down)
assert result.exit_code != 0
assert result.exception is None or isinstance(result.exception, SystemExit)
assert "invalid or unexpected JSON" in result.output
class TestUpCanInvokeTheRealLoginCommand:
"""`lite up` calls ctx.invoke(login) on the real command object.
Every other test in this file monkeypatches `up_module.login` with a fake, so
none of them would notice a login parameter that ctx.invoke cannot supply.
"""
def test_ctx_invoke_supplies_every_login_parameter(self):
from litellm.proxy.client.cli.commands.auth import login as real_login
reached = []
@click.command()
@click.pass_context
def driver(ctx):
ctx.obj = {"base_url": "http://127.0.0.1:9"}
ctx.invoke(real_login, config_claude=False, pkce=False)
with patch(
f"{AUTH_MODULE}._start_cli_sso_flow",
side_effect=lambda base_url: reached.append(base_url) or RuntimeError("stop"),
):
result = CliRunner().invoke(driver, [], standalone_mode=False)
assert not isinstance(result.exception, TypeError), result.exception
assert reached == ["http://127.0.0.1:9"]
def test_ctx_invoke_leaves_claude_settings_alone(self, tmp_path):
from litellm.proxy.client.cli.commands.auth import login as real_login
settings_path = tmp_path / "settings.json"
@click.command()
@click.pass_context
def driver(ctx):
ctx.obj = {"base_url": "http://127.0.0.1:9"}
ctx.invoke(real_login, config_claude=False, pkce=False)
with patch(f"{AUTH_MODULE}._start_cli_sso_flow", side_effect=RuntimeError("stop")):
CliRunner().invoke(driver, [], standalone_mode=False, env={"CLAUDE_CONFIG_DIR": str(tmp_path)})
assert not settings_path.exists()