mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-25 22:20:43 +00:00
* 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>
1154 lines
54 KiB
Python
1154 lines
54 KiB
Python
import json
|
|
import os
|
|
import pathlib
|
|
import shlex
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError
|
|
from pathlib import Path
|
|
from threading import Event
|
|
from typing import Final
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
from click.testing import CliRunner
|
|
|
|
from litellm.litellm_core_utils.private_json import commit_staged_json, write_private_bytes
|
|
from litellm.proxy.client.cli.commands.autoroute.process import AUTOROUTE_DIR
|
|
from litellm.proxy.client.cli.commands.claude_settings import (
|
|
ANTHROPIC_DEFAULT_MODEL_ENV_KEYS,
|
|
AUTOROUTE_BACKUP_PATH,
|
|
BACKUP_PATH,
|
|
CLAUDE_SETTINGS_PATH,
|
|
CONFIGURE_STATE_PATH,
|
|
LAUNCH_KEY_OVERLAY_PREFIX,
|
|
OWNED_ENV_KEYS,
|
|
OWNED_TOP_LEVEL_KEYS,
|
|
SETTINGS_FILE_OWNERS,
|
|
ApiKeyHelper,
|
|
ClaudeSettingsError,
|
|
KeepModel,
|
|
SettingsFileOwner,
|
|
StartOn,
|
|
StaticToken,
|
|
UnpinModel,
|
|
claude_settings_path,
|
|
configure_claude_settings,
|
|
install_statusline_script,
|
|
configure_state_path,
|
|
installed_executable,
|
|
is_lite_api_key_helper,
|
|
is_lite_api_key_helper_for,
|
|
lite_api_key_helper,
|
|
merge_claude_settings,
|
|
remove_launch_settings_files,
|
|
statusline_command,
|
|
unconfigure_claude_settings,
|
|
with_status_line,
|
|
)
|
|
|
|
|
|
def _owners(*backup_paths):
|
|
"""Stand-in owners for the real `lite up` / `lite autoroute start` registry."""
|
|
return tuple(SettingsFileOwner(path, "lite up", "lite down") for path in backup_paths)
|
|
|
|
|
|
CLAUDE_SETTINGS_MODULE = "litellm.proxy.client.cli.commands.claude_settings"
|
|
AUTH_MODULE = "litellm.proxy.client.cli.commands.auth"
|
|
@pytest.fixture
|
|
def paths(tmp_path):
|
|
return tmp_path / "claude" / "settings.json", tmp_path / "backup.json"
|
|
|
|
|
|
def _static_configure(base_url, settings_path, owners, state_path=None):
|
|
"""`lite configure claude --api-key`'s shape: a virtual key as a static token, no pinned model."""
|
|
state = state_path if state_path is not None else settings_path.parent.parent / "state.json"
|
|
configure_claude_settings(base_url.rstrip("/"), StaticToken("sk-virtual-key"), KeepModel(), settings_path, state, owners)
|
|
|
|
|
|
class TestConfigureClaudeSettings:
|
|
def test_creates_the_file_and_its_parent_when_missing(self, paths):
|
|
settings_path, backup_path = paths
|
|
assert not settings_path.parent.exists()
|
|
|
|
_static_configure("https://proxy.example.com/", settings_path, _owners(backup_path))
|
|
|
|
written = json.loads(settings_path.read_text())
|
|
assert written["env"]["ANTHROPIC_BASE_URL"] == "https://proxy.example.com"
|
|
assert written["env"]["ANTHROPIC_AUTH_TOKEN"] == "sk-virtual-key"
|
|
assert written["env"]["ENABLE_TOOL_SEARCH"] == "true"
|
|
assert written["env"]["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "1"
|
|
assert "apiKeyHelper" not in written
|
|
assert "model" not in written and "ANTHROPIC_MODEL" not in written["env"]
|
|
|
|
def test_updates_an_existing_file_preserving_unrelated_settings(self, paths):
|
|
settings_path, backup_path = paths
|
|
settings_path.parent.mkdir(parents=True)
|
|
settings_path.write_text(
|
|
json.dumps(
|
|
{
|
|
"theme": "dark",
|
|
"permissions": {"allow": ["Bash"]},
|
|
"env": {"SOME_OTHER_VAR": "keep-me", "ANTHROPIC_BASE_URL": "https://old.example.com"},
|
|
}
|
|
)
|
|
)
|
|
|
|
_static_configure("https://proxy.example.com", settings_path, _owners(backup_path))
|
|
|
|
written = json.loads(settings_path.read_text())
|
|
assert written["theme"] == "dark"
|
|
assert written["permissions"] == {"allow": ["Bash"]}
|
|
assert written["env"]["SOME_OTHER_VAR"] == "keep-me"
|
|
assert written["env"]["ANTHROPIC_BASE_URL"] == "https://proxy.example.com"
|
|
|
|
def test_a_helper_left_by_an_older_lite_is_stripped_so_only_the_static_token_is_sent(self, paths):
|
|
# Older `lite` versions wrote `apiKeyHelper: lite auth print-token`; Claude Code would keep spawning
|
|
# `lite` (and its keychain probe) on every credential refresh, so configure takes the slot over.
|
|
settings_path, backup_path = paths
|
|
settings_path.parent.mkdir(parents=True)
|
|
settings_path.write_text(
|
|
json.dumps({"apiKeyHelper": "/usr/local/bin/lite auth print-token", "env": {"ANTHROPIC_API_KEY": "sk-leaked"}})
|
|
)
|
|
|
|
_static_configure("https://proxy.example.com", settings_path, _owners(backup_path))
|
|
|
|
written = json.loads(settings_path.read_text())
|
|
assert "apiKeyHelper" not in written
|
|
assert "ANTHROPIC_API_KEY" not in written["env"]
|
|
assert written["env"]["ANTHROPIC_AUTH_TOKEN"] == "sk-virtual-key"
|
|
|
|
def test_written_file_is_owner_only(self, paths):
|
|
settings_path, backup_path = paths
|
|
_static_configure("https://proxy.example.com", settings_path, _owners(backup_path))
|
|
assert stat.S_IMODE(settings_path.stat().st_mode) == 0o600
|
|
|
|
def test_refuses_while_lite_up_holds_a_backup(self, paths):
|
|
settings_path, backup_path = paths
|
|
backup_path.write_text("{}")
|
|
|
|
with pytest.raises(ClaudeSettingsError, match="lite down"):
|
|
_static_configure("https://proxy.example.com", settings_path, _owners(backup_path))
|
|
|
|
assert not settings_path.exists()
|
|
|
|
def test_refuses_on_corrupt_existing_settings_without_touching_the_file(self, paths):
|
|
settings_path, backup_path = paths
|
|
settings_path.parent.mkdir(parents=True)
|
|
settings_path.write_text("not json at all {{{")
|
|
|
|
with pytest.raises(ClaudeSettingsError, match="invalid JSON"):
|
|
_static_configure("https://proxy.example.com", settings_path, _owners(backup_path))
|
|
|
|
assert settings_path.read_text() == "not json at all {{{"
|
|
|
|
def test_reports_an_actionable_error_on_a_non_utf8_file(self, paths):
|
|
# UnicodeDecodeError is a ValueError, not an OSError, so a decode-side catch is easy to miss.
|
|
settings_path, backup_path = paths
|
|
settings_path.parent.mkdir(parents=True)
|
|
settings_path.write_bytes(b'{"theme": "\xff\xfe"}')
|
|
|
|
with pytest.raises(ClaudeSettingsError, match="invalid JSON"):
|
|
_static_configure("https://proxy.example.com", settings_path, _owners(backup_path))
|
|
|
|
def test_reports_an_actionable_error_when_the_file_cannot_be_read(self, paths):
|
|
settings_path, backup_path = paths
|
|
settings_path.parent.mkdir(parents=True)
|
|
settings_path.mkdir()
|
|
|
|
with pytest.raises(ClaudeSettingsError, match="Could not read"):
|
|
_static_configure("https://proxy.example.com", settings_path, _owners(backup_path))
|
|
|
|
def test_reports_an_actionable_error_when_the_file_cannot_be_written(self, paths):
|
|
settings_path, backup_path = paths
|
|
settings_path.parent.mkdir(parents=True)
|
|
settings_path.parent.chmod(0o500)
|
|
try:
|
|
with pytest.raises(ClaudeSettingsError, match="Could not write"):
|
|
_static_configure("https://proxy.example.com", settings_path, _owners(backup_path))
|
|
finally:
|
|
settings_path.parent.chmod(0o700)
|
|
assert not settings_path.exists()
|
|
|
|
|
|
class TestLiteApiKeyHelper:
|
|
@pytest.mark.skipif(sys.platform.startswith("win"), reason="runs the command through sh, as Claude Code does on POSIX")
|
|
def test_sh_runs_the_lite_on_path_against_this_proxy(self, tmp_path):
|
|
lite = tmp_path / "my tools" / "lite"
|
|
lite.parent.mkdir()
|
|
lite.write_text('#!/bin/sh\nprintf "%s\\n" "$0" "$@"\n')
|
|
lite.chmod(0o700)
|
|
|
|
helper = lite_api_key_helper("https://proxy.example.com/", platform="linux", which=lambda name: str(lite))
|
|
|
|
assert helper is not None
|
|
ran = subprocess.run(["sh", "-c", helper.command], capture_output=True, text=True, check=True)
|
|
assert ran.stdout.splitlines() == [str(lite), "--base-url", "https://proxy.example.com", "auth", "print-token"]
|
|
|
|
@pytest.mark.skipif(sys.platform.startswith("win"), reason="runs the command through sh, as Claude Code does on POSIX")
|
|
def test_a_lite_found_through_a_relative_path_entry_keeps_running_from_any_directory(self, tmp_path, monkeypatch):
|
|
for repo, name in ((tmp_path / "login-dir", "mine"), (tmp_path / "other-repo", "planted")):
|
|
lite = repo / "bin" / "lite"
|
|
lite.parent.mkdir(parents=True)
|
|
lite.write_text(f"#!/bin/sh\necho {name}\n")
|
|
lite.chmod(0o700)
|
|
monkeypatch.chdir(tmp_path / "login-dir")
|
|
|
|
helper = lite_api_key_helper("https://proxy.example.com", platform="linux", which=lambda name: "bin/lite")
|
|
|
|
assert helper is not None
|
|
ran = subprocess.run(
|
|
["sh", "-c", helper.command], cwd=tmp_path / "other-repo", capture_output=True, text=True, check=True
|
|
)
|
|
assert ran.stdout == "mine\n"
|
|
|
|
def test_quotes_every_token_for_cmd_on_windows(self):
|
|
helper = lite_api_key_helper(
|
|
"https://proxy.example.com", platform="win32", which=lambda name: r"C:\Program Files\lite\lite.exe"
|
|
)
|
|
|
|
assert helper is not None
|
|
assert helper.command == (
|
|
r'"C:\Program Files\lite\lite.exe" "--base-url" "https://proxy.example.com" "auth" "print-token"'
|
|
)
|
|
|
|
def test_no_lite_on_path_means_no_helper(self):
|
|
assert lite_api_key_helper("https://proxy.example.com", which=lambda name: None) is None
|
|
|
|
@pytest.mark.parametrize(
|
|
"command",
|
|
[
|
|
"/usr/local/bin/lite --base-url https://proxy.example.com auth print-token",
|
|
"'/home/me/my tools/lite' --base-url https://other.example.com auth print-token",
|
|
r'"C:\Program Files\lite\lite.exe" "--base-url" "https://proxy.example.com" "auth" "print-token"',
|
|
],
|
|
ids=["posix", "posix-quoted-path", "windows"],
|
|
)
|
|
def test_recognizes_a_helper_any_lite_wrote_for_any_proxy(self, command):
|
|
assert is_lite_api_key_helper(command)
|
|
|
|
@pytest.mark.parametrize(
|
|
"command",
|
|
["/opt/mine/helper", "/usr/local/bin/lite auth print-token --verbose", "", None, ["lite", "auth", "print-token"]],
|
|
ids=["users-own-helper", "other-trailing-args", "disabled", "unset", "not-a-string"],
|
|
)
|
|
def test_leaves_every_other_helper_alone(self, command):
|
|
assert not is_lite_api_key_helper(command)
|
|
|
|
@pytest.mark.parametrize(
|
|
("command", "matches"),
|
|
[
|
|
("/usr/local/bin/lite --base-url https://proxy.example.com auth print-token", True),
|
|
("'/home/me/my tools/lite' --base-url https://proxy.example.com auth print-token", True),
|
|
(r'"C:\Program Files\lite\lite.exe" "--base-url" "https://proxy.example.com" "auth" "print-token"', True),
|
|
("/usr/local/bin/lite --base-url https://other.example.com auth print-token", False),
|
|
("/usr/local/bin/lite --base-url https://proxy.example.com/v2 auth print-token", False),
|
|
("/opt/mine/helper", False),
|
|
(None, False),
|
|
],
|
|
ids=["posix", "posix-quoted-path", "windows", "other-proxy", "other-path-on-the-proxy", "users-own", "unset"],
|
|
)
|
|
def test_matches_a_helper_any_lite_wrote_for_this_proxy_only(self, command, matches):
|
|
assert is_lite_api_key_helper_for(command, "https://proxy.example.com/") is matches
|
|
|
|
|
|
@pytest.mark.skipif(sys.platform.startswith("win"), reason="runs the command through sh, as Claude Code does on POSIX")
|
|
class TestInstalledExecutable:
|
|
@staticmethod
|
|
def _script(path, body):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(f"#!/bin/sh\n{body}\n")
|
|
path.chmod(0o700)
|
|
|
|
def test_the_helper_runs_the_lite_installed_beside_this_python_over_a_shim_earlier_on_path(
|
|
self, tmp_path, monkeypatch
|
|
):
|
|
self._script(tmp_path / "shims" / "lite", "echo 'pyenv: lite: command not found' >&2; exit 127")
|
|
self._script(tmp_path / "venv" / "bin" / "lite", "echo real")
|
|
monkeypatch.setenv("PATH", f"{tmp_path / 'shims'}{os.pathsep}{os.environ['PATH']}")
|
|
|
|
helper = lite_api_key_helper(
|
|
"https://proxy.example.com",
|
|
platform="linux",
|
|
which=lambda name: installed_executable(name, scripts_dir=str(tmp_path / "venv" / "bin")),
|
|
)
|
|
|
|
assert helper is not None
|
|
ran = subprocess.run(["sh", "-c", helper.command], capture_output=True, text=True)
|
|
assert (ran.returncode, ran.stdout) == (0, "real\n")
|
|
|
|
def test_falls_back_to_path_when_this_python_has_no_lite(self, tmp_path, monkeypatch):
|
|
self._script(tmp_path / "pipx" / "lite", "echo pipx")
|
|
(tmp_path / "venv" / "bin").mkdir(parents=True)
|
|
monkeypatch.setenv("PATH", str(tmp_path / "pipx"))
|
|
|
|
assert installed_executable("lite", scripts_dir=str(tmp_path / "venv" / "bin")) == str(tmp_path / "pipx" / "lite")
|
|
|
|
def test_a_lite_planted_in_the_working_directory_never_becomes_the_helper(self, tmp_path, monkeypatch):
|
|
self._script(tmp_path / "repo" / "lite", "echo planted")
|
|
self._script(tmp_path / "pipx" / "lite", "echo pipx")
|
|
(tmp_path / "venv" / "bin").mkdir(parents=True)
|
|
monkeypatch.chdir(tmp_path / "repo")
|
|
|
|
found = installed_executable(
|
|
"lite", scripts_dir=str(tmp_path / "venv" / "bin"), environ={"PATH": f"{os.pathsep}{tmp_path / 'pipx'}"}
|
|
)
|
|
|
|
assert found == str(tmp_path / "pipx" / "lite")
|
|
|
|
def test_finds_the_lite_exe_launcher_a_windows_python_installs(self, tmp_path):
|
|
self._script(tmp_path / "venv" / "Scripts" / "lite.exe", "")
|
|
|
|
found = installed_executable(
|
|
"lite", scripts_dir=str(tmp_path / "venv" / "Scripts"), environ={"PATH": ""}, platform="win32"
|
|
)
|
|
|
|
assert found == str(tmp_path / "venv" / "Scripts" / "lite.exe")
|
|
|
|
|
|
class TestConflictingOwnersOfTheSettingsFile:
|
|
"""Both `lite up` and `lite autoroute start` restore a backup when they stop.
|
|
|
|
Guarding only one of them leaves the other free to silently revert this
|
|
write, which is the exact hazard the guard exists to prevent.
|
|
"""
|
|
|
|
def test_any_owner_holding_a_backup_blocks_the_write(self, tmp_path):
|
|
settings_path = tmp_path / "claude" / "settings.json"
|
|
|
|
for index, owner in enumerate(SETTINGS_FILE_OWNERS):
|
|
backup = tmp_path / f"backup-{index}.json"
|
|
backup.write_text("{}")
|
|
stand_in = SettingsFileOwner(backup, owner.start_command, owner.stop_command)
|
|
with pytest.raises(ClaudeSettingsError, match="currently managing"):
|
|
_static_configure("https://proxy.example.com", settings_path, (stand_in,))
|
|
backup.unlink()
|
|
assert not settings_path.exists()
|
|
|
|
def test_the_error_names_the_owner_that_actually_holds_the_file(self, tmp_path):
|
|
settings_path = tmp_path / "claude" / "settings.json"
|
|
backup = tmp_path / "auto.json"
|
|
backup.write_text("{}")
|
|
autoroute = SettingsFileOwner(backup, "lite autoroute start", "lite autoroute stop")
|
|
|
|
with pytest.raises(ClaudeSettingsError, match="`lite autoroute start` is currently managing"):
|
|
_static_configure("https://proxy.example.com", settings_path, (autoroute,))
|
|
with pytest.raises(ClaudeSettingsError, match="Run `lite autoroute stop` first"):
|
|
_static_configure("https://proxy.example.com", settings_path, (autoroute,))
|
|
|
|
def test_the_registry_matches_the_paths_the_commands_actually_use(self):
|
|
"""A second definition of the autoroute dir must not drift from this one."""
|
|
assert AUTOROUTE_BACKUP_PATH == AUTOROUTE_DIR / "claude_settings_backup.json"
|
|
assert {o.backup_path for o in SETTINGS_FILE_OWNERS} == {BACKUP_PATH, AUTOROUTE_BACKUP_PATH}
|
|
assert {o.stop_command for o in SETTINGS_FILE_OWNERS} == {"lite down", "lite autoroute stop"}
|
|
|
|
|
|
class TestDoesNotDestroyUserOwnedStructure:
|
|
def test_writes_through_a_symlinked_settings_file(self, tmp_path):
|
|
"""os.replace() swaps the symlink for a regular file, detaching a dotfiles repo.
|
|
|
|
There is no backup here to undo that, so the link must survive and its
|
|
target must be the thing that gets updated.
|
|
"""
|
|
real = tmp_path / "dotfiles" / "settings.json"
|
|
real.parent.mkdir()
|
|
real.write_text(json.dumps({"theme": "dark"}))
|
|
link = tmp_path / "claude" / "settings.json"
|
|
link.parent.mkdir()
|
|
link.symlink_to(real)
|
|
|
|
_static_configure("https://proxy.example.com", link, ())
|
|
|
|
assert link.is_symlink()
|
|
assert json.loads(real.read_text())["env"]["ANTHROPIC_BASE_URL"] == "https://proxy.example.com"
|
|
assert json.loads(real.read_text())["theme"] == "dark"
|
|
|
|
def test_refuses_rather_than_discarding_a_non_object_env(self, paths):
|
|
"""merge coerces a non-dict env to {}; that is silent data loss on a persistent write."""
|
|
settings_path, backup_path = paths
|
|
settings_path.parent.mkdir(parents=True)
|
|
settings_path.write_text(json.dumps({"theme": "dark", "env": "not-an-object"}))
|
|
|
|
with pytest.raises(ClaudeSettingsError, match="non-object"):
|
|
_static_configure("https://proxy.example.com", settings_path, _owners(backup_path))
|
|
|
|
assert json.loads(settings_path.read_text())["env"] == "not-an-object"
|
|
|
|
|
|
class TestClaudeSettingsPath:
|
|
def test_defaults_to_the_home_settings_file(self):
|
|
assert claude_settings_path({}) == CLAUDE_SETTINGS_PATH
|
|
assert claude_settings_path({"CLAUDE_CONFIG_DIR": ""}) == CLAUDE_SETTINGS_PATH
|
|
|
|
def test_follows_claude_config_dir_like_claude_code_does(self, tmp_path):
|
|
assert claude_settings_path({"CLAUDE_CONFIG_DIR": str(tmp_path)}) == tmp_path / "settings.json"
|
|
|
|
def test_expands_a_tilde_in_claude_config_dir(self):
|
|
assert claude_settings_path({"CLAUDE_CONFIG_DIR": "~/.claude-work"}) == (
|
|
Path.home() / ".claude-work" / "settings.json"
|
|
)
|
|
|
|
|
|
class TestConfigureStatePath:
|
|
"""Each settings file gets its own undo receipt: the default file keeps the long-standing path, and
|
|
a CLAUDE_CONFIG_DIR file gets one keyed by its resolved location, so `lite unconfigure claude`
|
|
under one config dir never restores the other file's history."""
|
|
|
|
@pytest.fixture
|
|
def default_paths(self, tmp_path):
|
|
default_settings = tmp_path / "home" / ".claude" / "settings.json"
|
|
default_state = tmp_path / "home" / ".litellm" / "claude_configure_state.json"
|
|
with (
|
|
patch(f"{CLAUDE_SETTINGS_MODULE}.CLAUDE_SETTINGS_PATH", default_settings),
|
|
patch(f"{CLAUDE_SETTINGS_MODULE}.CONFIGURE_STATE_PATH", default_state),
|
|
):
|
|
yield default_settings, default_state
|
|
|
|
def test_the_default_file_keeps_the_default_receipt(self, default_paths):
|
|
default_settings, default_state = default_paths
|
|
assert configure_state_path(default_settings) == default_state
|
|
|
|
def test_a_symlink_alias_of_the_default_file_shares_its_receipt(self, default_paths):
|
|
default_settings, default_state = default_paths
|
|
default_settings.parent.mkdir(parents=True)
|
|
alias = default_settings.parent.parent / "claude-alias"
|
|
alias.symlink_to(default_settings.parent, target_is_directory=True)
|
|
assert configure_state_path(alias / "settings.json") == default_state
|
|
|
|
def test_another_settings_file_gets_a_receipt_of_its_own_beside_the_default_one(self, default_paths, tmp_path):
|
|
_default_settings, default_state = default_paths
|
|
work_state = configure_state_path(tmp_path / "work" / "settings.json")
|
|
play_state = configure_state_path(tmp_path / "play" / "settings.json")
|
|
assert work_state != default_state and play_state != default_state
|
|
assert work_state != play_state
|
|
assert work_state.parent == play_state.parent == default_state.parent / "claude_configure_state"
|
|
assert work_state == configure_state_path(tmp_path / "work" / "settings.json")
|
|
|
|
def test_configure_and_unconfigure_under_a_config_dir_leave_the_default_receipt_alone(
|
|
self, default_paths, tmp_path
|
|
):
|
|
_default_settings, default_state = default_paths
|
|
work_settings = tmp_path / "work" / "settings.json"
|
|
work_state = configure_state_path(work_settings)
|
|
configure_claude_settings(
|
|
"https://proxy.example.com", StaticToken("sk-virtual-key"), KeepModel(), work_settings, work_state, ()
|
|
)
|
|
assert work_state.exists() and not default_state.exists()
|
|
outcome = unconfigure_claude_settings(work_settings, work_state, ())
|
|
assert outcome.file_removed and not work_settings.exists()
|
|
assert not work_state.exists()
|
|
|
|
|
|
class TestMergeClaudeSettings:
|
|
"""One merge for every way Claude Code gets wired: `lite up`, `lite configure claude` and `lite autoroute start`."""
|
|
|
|
def test_a_static_token_lands_in_env_and_the_helper_slot_is_cleared(self):
|
|
settings = {"apiKeyHelper": "/usr/local/bin/lite auth print-token", "env": {"ANTHROPIC_API_KEY": "leaked"}}
|
|
merged = merge_claude_settings(settings, "http://127.0.0.1:4000/", StaticToken("token-abc"))
|
|
assert merged["env"]["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:4000"
|
|
assert merged["env"]["ANTHROPIC_AUTH_TOKEN"] == "token-abc"
|
|
assert merged["env"]["ENABLE_TOOL_SEARCH"] == "true"
|
|
assert merged["env"]["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "1"
|
|
assert "ANTHROPIC_API_KEY" not in merged["env"]
|
|
assert "apiKeyHelper" not in merged
|
|
assert "model" not in merged
|
|
assert not any(key in merged["env"] for key in ANTHROPIC_DEFAULT_MODEL_ENV_KEYS)
|
|
|
|
def test_a_helper_lands_top_level_and_blanks_the_token_a_shell_export_would_win_with(self):
|
|
settings = {"env": {"ANTHROPIC_AUTH_TOKEN": "sk-expired-login", "ANTHROPIC_API_KEY": "leaked"}}
|
|
merged = merge_claude_settings(settings, "http://127.0.0.1:4000/", HELPER)
|
|
assert merged["apiKeyHelper"] == HELPER.command
|
|
assert merged["env"]["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:4000"
|
|
assert merged["env"]["ANTHROPIC_AUTH_TOKEN"] == ""
|
|
assert "ANTHROPIC_API_KEY" not in merged["env"]
|
|
|
|
def test_keeps_existing_switch_values_and_unrelated_keys_without_mutating_the_input(self):
|
|
settings = {"theme": "dark", "env": {"SOME_OTHER_VAR": "value", "ENABLE_TOOL_SEARCH": "false"}}
|
|
merged = merge_claude_settings(settings, "http://127.0.0.1:4000", StaticToken("token-abc"))
|
|
assert merged["theme"] == "dark"
|
|
assert merged["env"]["SOME_OTHER_VAR"] == "value"
|
|
assert merged["env"]["ENABLE_TOOL_SEARCH"] == "false"
|
|
assert settings == {"theme": "dark", "env": {"SOME_OTHER_VAR": "value", "ENABLE_TOOL_SEARCH": "false"}}
|
|
|
|
def test_a_default_model_pins_the_starting_row_and_the_model_a_resumed_session_keeps(self):
|
|
# `model` is only the row Claude Code starts on: a resumed session re-sends the model its transcript
|
|
# recorded, which behind a raw-model auto-router is the tier model (403 for a key scoped to the
|
|
# router). ANTHROPIC_MODEL outranks the transcript on resume, so the pin has to land there too.
|
|
merged = merge_claude_settings(
|
|
{}, "http://127.0.0.1:4000", StaticToken("token-abc"), default_model="claude-auto"
|
|
)
|
|
assert merged["model"] == "claude-auto"
|
|
assert merged["env"]["ANTHROPIC_MODEL"] == "claude-auto"
|
|
assert not any(key in merged["env"] for key in ANTHROPIC_DEFAULT_MODEL_ENV_KEYS)
|
|
|
|
def test_without_a_default_model_neither_pin_is_written_and_a_users_own_stays(self):
|
|
settings = {"model": "mine", "env": {"ANTHROPIC_MODEL": "mine-too"}}
|
|
merged = merge_claude_settings(settings, "http://127.0.0.1:4000", StaticToken("token-abc"))
|
|
assert merged["model"] == "mine" and merged["env"]["ANTHROPIC_MODEL"] == "mine-too"
|
|
|
|
def test_a_tier_model_forces_every_claude_code_tier_as_autoroute_needs(self):
|
|
# Router's auto-router registry is keyed by the literal requested model string with no
|
|
# wildcard resolution, so `lite autoroute start` overrides the env var each tier reads.
|
|
settings = {"env": {"ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-opus-4-8"}}
|
|
merged = merge_claude_settings(
|
|
settings, "http://127.0.0.1:4000", StaticToken("token-abc"), tier_model="autorouter"
|
|
)
|
|
assert {merged["env"][key] for key in ANTHROPIC_DEFAULT_MODEL_ENV_KEYS} == {"autorouter"}
|
|
assert "model" not in merged
|
|
|
|
def test_touches_exactly_the_declared_owned_keys(self):
|
|
# The receipt and unconfigure restore exactly OWNED_*_KEYS, so a key the merge writes outside
|
|
# that table would be written by configure and never undone.
|
|
settings = {
|
|
"theme": "dark",
|
|
"permissions": {"allow": ["Bash"]},
|
|
"env": {"KEEP_ME": "1", "ANTHROPIC_API_KEY": "old", "ENABLE_TOOL_SEARCH": "false"},
|
|
"apiKeyHelper": "old-helper",
|
|
"model": "old-model",
|
|
}
|
|
for credential in (StaticToken("token-abc"), StaticToken("token-rotated")):
|
|
merged = merge_claude_settings(settings, "http://127.0.0.1:4000", credential, default_model="claude-auto")
|
|
changed_top_level = {key for key in set(settings) | set(merged) if settings.get(key) != merged.get(key)}
|
|
assert changed_top_level - {"env"} <= set(OWNED_TOP_LEVEL_KEYS)
|
|
changed_env = {
|
|
key
|
|
for key in set(settings["env"]) | set(merged["env"])
|
|
if settings["env"].get(key) != merged["env"].get(key)
|
|
}
|
|
assert changed_env <= set(OWNED_ENV_KEYS)
|
|
assert merged["permissions"] == {"allow": ["Bash"]}
|
|
assert merged["env"]["KEEP_ME"] == "1"
|
|
|
|
|
|
PROXY = "http://127.0.0.1:4000"
|
|
ANTHROPIC = "https://api.anthropic.com"
|
|
RELOGIN = StaticToken("sk-fresh-login")
|
|
HELPER = ApiKeyHelper("/usr/local/bin/lite --base-url http://127.0.0.1:4000 auth print-token")
|
|
ORIGINAL = {
|
|
"theme": "dark",
|
|
"permissions": {"allow": ["Bash"]},
|
|
"env": {"KEEP_ME": "1", "ANTHROPIC_API_KEY": "sk-ant-mine", "ANTHROPIC_BASE_URL": ANTHROPIC},
|
|
"apiKeyHelper": "/usr/local/bin/lite auth print-token",
|
|
"model": "claude-opus-5",
|
|
}
|
|
|
|
|
|
def _set(path, value):
|
|
"""A user edit: set (or with `_ABSENT`, remove) the key at a dotted path in the settings file."""
|
|
|
|
def edit(settings):
|
|
section, _, key = path.rpartition(".")
|
|
container = settings.setdefault(section, {}) if section else settings
|
|
if value is _ABSENT:
|
|
container.pop(key, None)
|
|
else:
|
|
container[key] = value
|
|
return settings
|
|
|
|
return edit
|
|
|
|
|
|
_ABSENT = object()
|
|
|
|
|
|
class _Rig:
|
|
"""One settings file plus receipt under tmp_path, driven through the public functions only."""
|
|
|
|
def __init__(self, tmp_path, initial):
|
|
self.settings = tmp_path / "claude" / "settings.json"
|
|
self.state = tmp_path / "state" / "claude_configure_state.json"
|
|
if initial is not None:
|
|
self.settings.parent.mkdir(parents=True)
|
|
self.settings.write_text(json.dumps(initial))
|
|
|
|
def read(self):
|
|
return json.loads(self.settings.read_text()) if self.settings.exists() else None
|
|
|
|
def configure(self, credential=StaticToken("sk-virtual-key"), model=StartOn("claude-auto"), **kwargs):
|
|
configure_claude_settings(PROXY, credential, model, self.settings, self.state, (), **kwargs)
|
|
|
|
def edit(self, *edits):
|
|
settings = self.read()
|
|
for apply in edits:
|
|
settings = apply(settings)
|
|
self.settings.write_text(json.dumps(settings))
|
|
|
|
def unconfigure(self):
|
|
return unconfigure_claude_settings(self.settings, self.state, ())
|
|
|
|
|
|
# Each row: initial file, steps (configure kwargs dicts or edit callables) between the first configure
|
|
# and unconfigure, the expected file afterwards, and the expected outcome fields. Sequences that used
|
|
# to be one test each; the receipt's rules are what make them all come out right.
|
|
UNDO_SCENARIOS = {
|
|
"plain round trip": (ORIGINAL, [], ORIGINAL, {"kept": ()}),
|
|
"helper round trip": (ORIGINAL, [], ORIGINAL, {"kept": ()}, {"credential": HELPER, "model": KeepModel()}),
|
|
"helper with no file before": (None, [], None, {"file_removed": True}, {"credential": HELPER}),
|
|
"re-logins switching between the token and the helper keep the first snapshot": (
|
|
ORIGINAL,
|
|
[{"credential": HELPER, "model": KeepModel()}, {"credential": RELOGIN, "model": KeepModel()}],
|
|
ORIGINAL,
|
|
{"kept": ()},
|
|
{"credential": HELPER, "model": KeepModel()},
|
|
),
|
|
"no file before": (None, [], None, {"file_removed": True}),
|
|
"no env before": ({"theme": "dark"}, [], {"theme": "dark"}, {}),
|
|
"null env before": ({"theme": "dark", "env": None}, [], {"theme": "dark", "env": None}, {}),
|
|
"empty env before": ({"theme": "dark", "env": {}}, [], {"theme": "dark", "env": {}}, {}),
|
|
"user edits stay and are named": (
|
|
ORIGINAL,
|
|
[_set("env.ENABLE_TOOL_SEARCH", "false"), _set("model", "claude-sonnet-4-6")],
|
|
{**ORIGINAL, "env": {**ORIGINAL["env"], "ENABLE_TOOL_SEARCH": "false"}, "model": "claude-sonnet-4-6"},
|
|
{"kept": {"env.ENABLE_TOOL_SEARCH", "model"}, "withheld": ()},
|
|
),
|
|
"user filled an env configure created": (None, [_set("env.MY_VAR", "mine")], {"env": {"MY_VAR": "mine"}}, {}),
|
|
"user deleted the file": (None, [lambda s: None], None, {"file_removed": True, "restored": (), "kept": ()}),
|
|
"user removed our key: neither restored nor kept": (
|
|
ORIGINAL,
|
|
[_set("env.ANTHROPIC_AUTH_TOKEN", _ABSENT)],
|
|
ORIGINAL,
|
|
{"not_restored": {"env.ANTHROPIC_AUTH_TOKEN"}, "kept": ()},
|
|
),
|
|
"restored names only what changed": (
|
|
{"model": "claude-opus-5"},
|
|
[],
|
|
{"model": "claude-opus-5"},
|
|
{
|
|
"restored": {
|
|
"env.ANTHROPIC_BASE_URL",
|
|
"env.ANTHROPIC_AUTH_TOKEN",
|
|
"env.ENABLE_TOOL_SEARCH",
|
|
"env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY",
|
|
"statusLine",
|
|
},
|
|
"kept": (),
|
|
},
|
|
{"credential": RELOGIN, "model": KeepModel()},
|
|
),
|
|
"repeat across credential kinds keeps the first snapshot": (
|
|
ORIGINAL,
|
|
[
|
|
{"credential": RELOGIN, "model": UnpinModel()},
|
|
{"credential": StaticToken("sk-rotated"), "model": StartOn("claude-sonnet-4-6")},
|
|
],
|
|
ORIGINAL,
|
|
{},
|
|
),
|
|
"repeat without a model lets go of our pin, user had none": ({}, [{"model": UnpinModel()}], {}, {}),
|
|
"repeat without a model lets go of our pin, user had one": (
|
|
{"model": "claude-opus-5"},
|
|
[{"model": UnpinModel()}],
|
|
{"model": "claude-opus-5"},
|
|
{},
|
|
),
|
|
"re-login keeps our pin": (None, [{"credential": RELOGIN, "model": KeepModel()}], None, {"file_removed": True}),
|
|
"edit between configures survives an unpin repeat": (
|
|
ORIGINAL,
|
|
[
|
|
_set("model", "my-favourite"),
|
|
_set("env.ENABLE_TOOL_SEARCH", "false"),
|
|
{"credential": RELOGIN, "model": UnpinModel()},
|
|
],
|
|
{**ORIGINAL, "env": {**ORIGINAL["env"], "ENABLE_TOOL_SEARCH": "false"}, "model": "my-favourite"},
|
|
{"kept": {"env.ENABLE_TOOL_SEARCH", "model"}},
|
|
),
|
|
"edit between configures survives a re-login": (
|
|
ORIGINAL,
|
|
[
|
|
_set("model", "my-favourite"),
|
|
_set("env.ENABLE_TOOL_SEARCH", "false"),
|
|
{"credential": RELOGIN, "model": KeepModel()},
|
|
],
|
|
{**ORIGINAL, "env": {**ORIGINAL["env"], "ENABLE_TOOL_SEARCH": "false"}, "model": "my-favourite"},
|
|
{"kept": {"env.ENABLE_TOOL_SEARCH", "model"}},
|
|
),
|
|
"edit between configures: a same-model repeat displaces it, so it is what comes back": (
|
|
ORIGINAL,
|
|
[_set("model", "my-favourite"), _set("env.ENABLE_TOOL_SEARCH", "false"), {"credential": RELOGIN}],
|
|
{**ORIGINAL, "env": {**ORIGINAL["env"], "ENABLE_TOOL_SEARCH": "false"}, "model": "my-favourite"},
|
|
{"kept": {"env.ENABLE_TOOL_SEARCH"}, "restored_includes": {"model"}},
|
|
),
|
|
"base URL changed since: credentials withheld, receipt kept": (
|
|
ORIGINAL,
|
|
[_set("env.ANTHROPIC_BASE_URL", "http://other-proxy:4000")],
|
|
{**ORIGINAL, "env": {"KEEP_ME": "1", "ANTHROPIC_BASE_URL": "http://other-proxy:4000"}, "apiKeyHelper": _ABSENT},
|
|
{
|
|
"withheld": {("env.ANTHROPIC_API_KEY", ANTHROPIC), ("apiKeyHelper", ANTHROPIC)},
|
|
"kept": {"env.ANTHROPIC_BASE_URL"},
|
|
"receipt_kept": True,
|
|
},
|
|
),
|
|
"base URL changed and back: judged against the URL the restored file holds": (
|
|
ORIGINAL,
|
|
[_set("env.ANTHROPIC_BASE_URL", ANTHROPIC)],
|
|
ORIGINAL,
|
|
{"withheld": ()},
|
|
),
|
|
"credential captured beside no URL goes back only beside no URL": (
|
|
{"env": {"ANTHROPIC_API_KEY": "sk-default-endpoint"}},
|
|
[_set("env.ANTHROPIC_BASE_URL", "http://other-proxy:4000")],
|
|
{"env": {"ANTHROPIC_BASE_URL": "http://other-proxy:4000"}},
|
|
{
|
|
"withheld": {("env.ANTHROPIC_API_KEY", "no ANTHROPIC_BASE_URL (Anthropic's default endpoint)")},
|
|
"receipt_kept": True,
|
|
},
|
|
),
|
|
"restored document empty while a credential is withheld: file goes, receipt stays": (
|
|
None,
|
|
[
|
|
_set("env.ANTHROPIC_API_KEY", "sk-user"),
|
|
{"credential": RELOGIN, "model": KeepModel()},
|
|
_set("env.ANTHROPIC_BASE_URL", _ABSENT),
|
|
],
|
|
None,
|
|
{"withheld": {("env.ANTHROPIC_API_KEY", PROXY)}, "file_removed": True, "receipt_kept": True},
|
|
{"credential": RELOGIN, "model": KeepModel()},
|
|
),
|
|
"a credential the user changed is kept, never also withheld": (
|
|
ORIGINAL,
|
|
[_set("env.ANTHROPIC_BASE_URL", "http://other-proxy:4000"), _set("apiKeyHelper", "/opt/mine/helper")],
|
|
{
|
|
**ORIGINAL,
|
|
"env": {"KEEP_ME": "1", "ANTHROPIC_BASE_URL": "http://other-proxy:4000"},
|
|
"apiKeyHelper": "/opt/mine/helper",
|
|
},
|
|
{
|
|
"withheld": {("env.ANTHROPIC_API_KEY", ANTHROPIC)},
|
|
"kept": {"env.ANTHROPIC_BASE_URL", "apiKeyHelper"},
|
|
"receipt_kept": True,
|
|
},
|
|
),
|
|
}
|
|
|
|
|
|
def _expected_file(expected):
|
|
if expected is None:
|
|
return None
|
|
return {k: v for k, v in expected.items() if v is not _ABSENT}
|
|
|
|
|
|
class TestConfigureAndUnconfigure:
|
|
"""`configure_claude_settings` records how to undo itself; `unconfigure_claude_settings` undoes only that."""
|
|
|
|
@pytest.mark.parametrize("scenario", UNDO_SCENARIOS.values(), ids=UNDO_SCENARIOS.keys())
|
|
def test_undo_matrix(self, tmp_path, scenario):
|
|
initial, steps, expected, outcome_expectations, *first = scenario
|
|
rig = _Rig(tmp_path, initial)
|
|
rig.configure(**(first[0] if first else {}))
|
|
for step in steps:
|
|
if isinstance(step, dict):
|
|
rig.configure(**step)
|
|
elif rig.settings.exists() and step(json.loads(rig.settings.read_text())) is None:
|
|
rig.settings.unlink()
|
|
else:
|
|
rig.edit(step)
|
|
|
|
outcome = rig.unconfigure()
|
|
|
|
assert rig.read() == _expected_file(expected)
|
|
assert rig.state.exists() == outcome_expectations.get("receipt_kept", False)
|
|
for field, want in outcome_expectations.items():
|
|
if field == "withheld":
|
|
assert {(item.key, item.endpoint) for item in outcome.withheld} == set(want)
|
|
elif field == "not_restored":
|
|
assert not set(want) & set(outcome.restored) and not set(want) & set(outcome.kept)
|
|
elif field == "restored_includes":
|
|
assert set(want) <= set(outcome.restored)
|
|
elif field in ("restored", "kept"):
|
|
assert set(getattr(outcome, field)) == set(want)
|
|
elif field != "receipt_kept":
|
|
assert getattr(outcome, field) == want
|
|
assert not {item.key for item in outcome.withheld} & set(outcome.kept)
|
|
|
|
def test_configure_writes_owner_only_and_the_receipt_never_holds_the_key(self, tmp_path):
|
|
rig = _Rig(tmp_path, ORIGINAL)
|
|
rig.configure(credential=StaticToken("sk-virtual-key-never-on-disk-twice"))
|
|
configured = rig.read()
|
|
assert configured["env"]["ANTHROPIC_AUTH_TOKEN"] == "sk-virtual-key-never-on-disk-twice"
|
|
assert configured["env"]["ANTHROPIC_BASE_URL"] == PROXY and configured["model"] == "claude-auto"
|
|
assert "ANTHROPIC_API_KEY" not in configured["env"] and "apiKeyHelper" not in configured
|
|
assert stat.S_IMODE(rig.settings.stat().st_mode) == 0o600 == stat.S_IMODE(rig.state.stat().st_mode)
|
|
assert "sk-virtual-key-never-on-disk-twice" not in rig.state.read_text()
|
|
|
|
def test_withheld_credentials_come_back_once_the_url_points_at_their_server_again(self, tmp_path):
|
|
# The kept receipt owns only the withheld slots: the second unconfigure restores exactly those.
|
|
rig = _Rig(tmp_path, ORIGINAL)
|
|
rig.configure()
|
|
rig.edit(_set("env.ANTHROPIC_BASE_URL", "http://other-proxy:4000"))
|
|
rig.unconfigure()
|
|
rig.edit(_set("env.ANTHROPIC_BASE_URL", ANTHROPIC), _set("theme", "light"))
|
|
outcome = rig.unconfigure()
|
|
assert rig.read() == {**ORIGINAL, "theme": "light"}
|
|
assert set(outcome.restored) == {"env.ANTHROPIC_API_KEY", "apiKeyHelper"}
|
|
assert outcome.kept == () and outcome.withheld == () and not rig.state.exists()
|
|
|
|
@pytest.mark.parametrize(
|
|
("path", "value", "repeat_credential"),
|
|
[
|
|
("env.ANTHROPIC_API_KEY", "sk-user-added-later", RELOGIN),
|
|
("apiKeyHelper", "/opt/mine/helper", StaticToken("sk-rotated")),
|
|
],
|
|
ids=["user-adds-api-key", "user-sets-own-helper"],
|
|
)
|
|
def test_a_credential_the_user_set_between_two_configures_is_what_comes_back(
|
|
self, tmp_path, path, value, repeat_credential
|
|
):
|
|
# The repeat's merge clears the slot, so the displaced value is snapshotted and is what returns;
|
|
# it was set while the file pointed at the proxy, so it returns once the file points there again.
|
|
rig = _Rig(tmp_path, {"theme": "dark"})
|
|
rig.configure(credential=RELOGIN, model=KeepModel())
|
|
rig.edit(_set(path, value))
|
|
rig.configure(credential=repeat_credential, model=KeepModel())
|
|
assert not _lookup(rig.read(), path)
|
|
|
|
outcome = rig.unconfigure()
|
|
assert [(item.key, item.endpoint) for item in outcome.withheld] == [(path, PROXY)]
|
|
assert rig.read() == {"theme": "dark"} and rig.state.exists()
|
|
rig.settings.write_text(json.dumps({"theme": "dark", "env": {"ANTHROPIC_BASE_URL": PROXY}}))
|
|
outcome = rig.unconfigure()
|
|
assert _lookup(rig.read(), path) == value
|
|
assert outcome.restored == (path,) and outcome.withheld == () and not rig.state.exists()
|
|
|
|
def test_a_receipt_commit_that_fails_leaves_no_staged_token_behind(self, tmp_path):
|
|
rig = _Rig(tmp_path, {})
|
|
|
|
def commit_receipt_fails(staged, path):
|
|
if path == str(rig.state):
|
|
os.unlink(staged)
|
|
raise OSError("receipt rename failed")
|
|
commit_staged_json(staged, path)
|
|
|
|
with pytest.raises(ClaudeSettingsError, match=r"Could not write .*receipt rename failed"):
|
|
rig.configure(credential=StaticToken("sk-never-left-in-a-temp-file"), commit=commit_receipt_fails)
|
|
assert not list(rig.settings.parent.glob(".tmp-*")) and not list(rig.state.parent.glob(".tmp-*"))
|
|
assert rig.read() == {} and not rig.state.exists()
|
|
|
|
@pytest.mark.parametrize("configured_before", [False, True], ids=["first-configure", "repeat-configure"])
|
|
def test_a_settings_commit_that_fails_after_the_receipt_landed_puts_the_receipt_back(
|
|
self, tmp_path, configured_before
|
|
):
|
|
# The two renames are not atomic: a settings rename that fails after the receipt landed must
|
|
# not leave a receipt describing settings that were never written.
|
|
rig = _Rig(tmp_path, ORIGINAL)
|
|
if configured_before:
|
|
rig.configure()
|
|
receipt_before = rig.state.read_text() if configured_before else None
|
|
settings_before = rig.settings.read_text()
|
|
|
|
def commit_settings_fails(staged, path):
|
|
if path == str(rig.settings):
|
|
os.unlink(staged)
|
|
raise OSError("rename failed")
|
|
commit_staged_json(staged, path)
|
|
|
|
with pytest.raises(ClaudeSettingsError, match="rename failed"):
|
|
rig.configure(credential=StaticToken("sk-rotated"), commit=commit_settings_fails)
|
|
assert rig.settings.read_text() == settings_before
|
|
assert (rig.state.read_text() if rig.state.exists() else None) == receipt_before
|
|
if configured_before:
|
|
rig.unconfigure()
|
|
assert rig.read() == ORIGINAL
|
|
|
|
def test_a_failed_repeat_configure_leaves_the_earlier_undo_intact(self, tmp_path):
|
|
rig = _Rig(tmp_path, ORIGINAL)
|
|
rig.configure()
|
|
receipt_before = rig.state.read_text()
|
|
rig.settings.parent.chmod(0o500)
|
|
try:
|
|
with pytest.raises(ClaudeSettingsError, match="Could not write"):
|
|
rig.configure(credential=StaticToken("sk-rotated"))
|
|
finally:
|
|
rig.settings.parent.chmod(0o700)
|
|
assert rig.state.read_text() == receipt_before and not list(rig.state.parent.glob(".tmp-*"))
|
|
assert rig.read()["env"]["ANTHROPIC_AUTH_TOKEN"] == "sk-virtual-key"
|
|
rig.unconfigure()
|
|
assert rig.read() == ORIGINAL
|
|
|
|
def test_unconfigure_reports_a_receipt_it_cannot_remove_as_a_settings_error(self, tmp_path):
|
|
rig = _Rig(tmp_path, ORIGINAL)
|
|
rig.configure()
|
|
rig.state.parent.chmod(0o500)
|
|
try:
|
|
with pytest.raises(ClaudeSettingsError, match="Could not remove"):
|
|
rig.unconfigure()
|
|
finally:
|
|
rig.state.parent.chmod(0o700)
|
|
|
|
def test_configure_writes_through_a_symlinked_settings_file(self, tmp_path):
|
|
target = tmp_path / "dotfiles" / "settings.json"
|
|
target.parent.mkdir()
|
|
target.write_text(json.dumps({"theme": "dark"}))
|
|
link = tmp_path / "settings.json"
|
|
link.symlink_to(target)
|
|
configure_claude_settings(PROXY, StaticToken("sk-virtual-key"), UnpinModel(), link, tmp_path / "state.json", ())
|
|
assert link.is_symlink()
|
|
assert json.loads(target.read_text())["env"]["ANTHROPIC_AUTH_TOKEN"] == "sk-virtual-key"
|
|
|
|
@pytest.mark.parametrize("operation", ["configure", "unconfigure"])
|
|
def test_refuses_while_a_temporary_owner_holds_a_backup(self, paths, tmp_path, operation):
|
|
settings_path, backup_path = paths
|
|
backup_path.write_text("{}")
|
|
owners = _owners(backup_path)
|
|
state = tmp_path / "state.json"
|
|
attempt = (
|
|
(lambda: configure_claude_settings(PROXY, StaticToken("k"), UnpinModel(), settings_path, state, owners))
|
|
if operation == "configure"
|
|
else (lambda: unconfigure_claude_settings(settings_path, state, owners))
|
|
)
|
|
with pytest.raises(ClaudeSettingsError, match="lite down"):
|
|
attempt()
|
|
assert not settings_path.exists()
|
|
|
|
def test_unconfigure_without_a_receipt_is_an_error_not_a_silent_no_op(self, tmp_path):
|
|
with pytest.raises(ClaudeSettingsError, match="nothing to undo"):
|
|
_Rig(tmp_path, None).unconfigure()
|
|
|
|
|
|
def _lookup(settings, path):
|
|
section, _, key = path.rpartition(".")
|
|
return (settings.get(section) or {}).get(key) if section else settings.get(key)
|
|
|
|
|
|
class TestStatusLine:
|
|
"""Every configure registers the status line, and only while the slot is empty or already ours."""
|
|
|
|
COMMAND = "/opt/lite/bin/python /Users/me/.litellm/statusline.py"
|
|
|
|
def test_an_empty_slot_gets_our_status_line(self):
|
|
assert with_status_line({}, self.COMMAND)["statusLine"] == {"type": "command", "command": self.COMMAND}
|
|
|
|
def test_a_users_own_status_line_is_never_replaced(self):
|
|
theirs = {"type": "command", "command": "~/.claude/my-statusline.sh"}
|
|
assert with_status_line({"statusLine": theirs}, self.COMMAND)["statusLine"] == theirs
|
|
|
|
def test_ours_under_an_older_interpreter_is_refreshed(self):
|
|
stale = {"type": "command", "command": "/old/python /Users/me/.litellm/statusline.py"}
|
|
assert with_status_line({"statusLine": stale}, self.COMMAND)["statusLine"]["command"] == self.COMMAND
|
|
|
|
def test_the_merge_carries_it(self):
|
|
merged = merge_claude_settings({}, PROXY, StaticToken("tok"), status_line=self.COMMAND)
|
|
assert merged["statusLine"] == {"type": "command", "command": self.COMMAND}
|
|
|
|
def test_the_installed_script_is_the_bundled_one_and_the_command_runs_this_interpreter(self, tmp_path):
|
|
from litellm.proxy.client.cli.commands import statusline_script
|
|
|
|
script = tmp_path / "lite" / "statusline.py"
|
|
command = install_statusline_script(script)
|
|
assert script.read_bytes().split(b"\n", 1)[1] == pathlib.Path(statusline_script.__file__).read_bytes()
|
|
assert shlex.split(command) == [sys.executable, str(script)]
|
|
assert command == statusline_command(script)
|
|
assert stat.S_IMODE(script.stat().st_mode) == 0o600
|
|
assert stat.S_IMODE(script.parent.stat().st_mode) == 0o700
|
|
assert install_statusline_script(script) == command
|
|
|
|
def test_a_reinstall_replaces_the_script_in_one_step_and_a_refused_one_leaves_the_old_script_whole(self, tmp_path):
|
|
# Claude Code may be running the script at the moment `lite` reinstalls it; the file it has open
|
|
# must stay complete, and a reinstall that cannot land must not leave a truncated script behind.
|
|
script = tmp_path / "lite" / "statusline.py"
|
|
install_statusline_script(script)
|
|
bundled = script.read_bytes()
|
|
with script.open("rb") as running:
|
|
install_statusline_script(script)
|
|
assert running.read() == bundled
|
|
assert {child.name for child in script.parent.iterdir()} <= {"statusline.py", "statusline.py.lock"}
|
|
|
|
if os.geteuid() != 0:
|
|
script.parent.chmod(0o500)
|
|
try:
|
|
with pytest.raises(ClaudeSettingsError, match="Could not install the status line script"):
|
|
install_statusline_script(script)
|
|
finally:
|
|
script.parent.chmod(0o700)
|
|
assert script.read_bytes() == bundled
|
|
|
|
@pytest.mark.parametrize(
|
|
("installed_version", "older_version"),
|
|
(("2.10.0", "2.9.0"), ("2.1.0", "2.1.0rc1"), ("2.1.0rc1", "2.1.0.dev2"), ("2.1.0.post1", "2.1.0")),
|
|
)
|
|
def test_an_older_cli_preserves_the_newer_footer(
|
|
self, tmp_path: Path, capsys: pytest.CaptureFixture[str], installed_version: str, older_version: str
|
|
) -> None:
|
|
script: Final = tmp_path / "statusline.py"
|
|
command: Final = install_statusline_script(script, package_version=installed_version)
|
|
installed: Final = script.read_bytes()
|
|
modified: Final = script.stat().st_mtime_ns
|
|
|
|
assert install_statusline_script(script, package_version=older_version) == command
|
|
|
|
assert script.read_bytes() == installed
|
|
assert script.stat().st_mtime_ns == modified
|
|
assert f"Keeping the status line from LiteLLM {installed_version}" in capsys.readouterr().err
|
|
|
|
@pytest.mark.parametrize(
|
|
"old_header", (b"", b"# litellm-statusline-version: invalid\n", b"# litellm-statusline-version: \xff\n")
|
|
)
|
|
def test_a_legacy_or_damaged_version_marker_is_repaired(self, tmp_path: Path, old_header: bytes) -> None:
|
|
from litellm.proxy.client.cli.commands import statusline_script
|
|
|
|
script: Final = tmp_path / "statusline.py"
|
|
script.write_bytes(old_header + b"print('old footer')\n")
|
|
|
|
install_statusline_script(script, package_version="2.1.0")
|
|
|
|
assert script.read_bytes() == (
|
|
b"# litellm-statusline-version: 2.1.0\n" + Path(statusline_script.__file__).read_bytes()
|
|
)
|
|
|
|
@pytest.mark.parametrize("next_version", ("2.1.0", "2.2.0"))
|
|
def test_an_equal_or_newer_cli_refreshes_the_footer(self, tmp_path: Path, next_version: str) -> None:
|
|
from litellm.proxy.client.cli.commands import statusline_script
|
|
|
|
script: Final = tmp_path / "statusline.py"
|
|
script.write_bytes(b"# litellm-statusline-version: 2.1.0\nprint('old footer')\n")
|
|
|
|
install_statusline_script(script, package_version=next_version)
|
|
|
|
assert script.read_bytes() == (
|
|
f"# litellm-statusline-version: {next_version}\n".encode() + Path(statusline_script.__file__).read_bytes()
|
|
)
|
|
|
|
def test_configure_keeps_a_newer_footer_while_updating_settings(
|
|
self, tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
|
) -> None:
|
|
script: Final = tmp_path / "statusline.py"
|
|
script.write_bytes(b"# litellm-statusline-version: 999999.0.0\nprint('newer footer')\n")
|
|
installed: Final = script.read_bytes()
|
|
rig: Final = _Rig(tmp_path, {"theme": "dark"})
|
|
|
|
rig.configure(script_path=script)
|
|
|
|
assert script.read_bytes() == installed
|
|
assert rig.read()["statusLine"]["command"] == statusline_command(script)
|
|
assert rig.read()["env"]["ANTHROPIC_BASE_URL"] == PROXY
|
|
assert "Keeping the status line" in capsys.readouterr().err
|
|
|
|
@pytest.mark.parametrize("package_version", ("unknown", "", "invalid-version"))
|
|
@pytest.mark.parametrize("existing", (None, b"print('legacy footer')\n", b"# litellm-statusline-version: invalid\n"))
|
|
def test_an_unknown_cli_version_can_install_and_refresh_an_unversioned_footer(
|
|
self, tmp_path: Path, package_version: str, existing: bytes | None
|
|
) -> None:
|
|
from litellm.proxy.client.cli.commands import statusline_script
|
|
|
|
script: Final = tmp_path / "statusline.py"
|
|
if existing is not None:
|
|
script.write_bytes(existing)
|
|
|
|
assert install_statusline_script(script, package_version=package_version) == statusline_command(script)
|
|
assert script.read_bytes() == Path(statusline_script.__file__).read_bytes()
|
|
|
|
def test_an_unknown_cli_version_preserves_a_versioned_footer(
|
|
self, tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
|
) -> None:
|
|
script: Final = tmp_path / "statusline.py"
|
|
command: Final = install_statusline_script(script, package_version="2.1.0")
|
|
installed: Final = script.read_bytes()
|
|
|
|
assert install_statusline_script(script, package_version="unknown") == command
|
|
assert script.read_bytes() == installed
|
|
assert "Keeping the status line from LiteLLM 2.1.0" in capsys.readouterr().err
|
|
|
|
@pytest.mark.parametrize(("first_version", "second_version"), (("2.0", "3.0"), ("3.0", "2.0")))
|
|
def test_overlapping_installs_keep_the_newest_footer(
|
|
self, tmp_path: Path, first_version: str, second_version: str
|
|
) -> None:
|
|
from litellm.proxy.client.cli.commands import statusline_script
|
|
|
|
script: Final = tmp_path / "statusline.py"
|
|
first_writing: Final = Event()
|
|
release_first: Final = Event()
|
|
second_started: Final = Event()
|
|
|
|
def paused_write(path: str, data: bytes) -> None:
|
|
first_writing.set()
|
|
assert release_first.wait(5), "First installer was never released"
|
|
write_private_bytes(path, data)
|
|
|
|
def second_install() -> str:
|
|
second_started.set()
|
|
return install_statusline_script(script, package_version=second_version)
|
|
|
|
with ThreadPoolExecutor(max_workers=2) as pool:
|
|
first: Final = pool.submit(install_statusline_script, script, package_version=first_version, write=paused_write)
|
|
try:
|
|
assert first_writing.wait(5), "First installer did not reach the write"
|
|
second: Final = pool.submit(second_install)
|
|
assert second_started.wait(5), "Second installer did not start"
|
|
with pytest.raises(FutureTimeoutError):
|
|
second.result(timeout=0.5)
|
|
finally:
|
|
release_first.set()
|
|
assert first.result(timeout=5) == statusline_command(script)
|
|
assert second.result(timeout=5) == statusline_command(script)
|
|
|
|
assert script.read_bytes() == b"# litellm-statusline-version: 3.0\n" + Path(statusline_script.__file__).read_bytes()
|
|
|
|
def test_a_failed_install_keeps_the_footer_and_releases_the_lock(self, tmp_path: Path) -> None:
|
|
script: Final = tmp_path / "statusline.py"
|
|
install_statusline_script(script, package_version="2.0")
|
|
installed: Final = script.read_bytes()
|
|
|
|
def failed_write(path: str, data: bytes) -> None:
|
|
raise OSError("disk full")
|
|
|
|
with pytest.raises(ClaudeSettingsError, match="disk full"):
|
|
install_statusline_script(script, package_version="3.0", write=failed_write)
|
|
assert script.read_bytes() == installed
|
|
assert install_statusline_script(script, package_version="3.0") == statusline_command(script)
|
|
assert script.read_bytes().startswith(b"# litellm-statusline-version: 3.0\n")
|
|
|
|
def test_configure_installs_it_and_unconfigure_removes_only_ours(self, tmp_path):
|
|
rig = _Rig(tmp_path, {"theme": "dark"})
|
|
script = tmp_path / "statusline.py"
|
|
rig.configure(script_path=script)
|
|
assert rig.read()["statusLine"]["command"] == statusline_command(script)
|
|
assert script.exists()
|
|
|
|
outcome = rig.unconfigure()
|
|
assert rig.read() == {"theme": "dark"}
|
|
assert "statusLine" in outcome.restored
|
|
|
|
def test_a_status_line_the_user_replaced_after_configure_survives_unconfigure(self, tmp_path):
|
|
rig = _Rig(tmp_path, None)
|
|
rig.configure(model=KeepModel(), script_path=tmp_path / "statusline.py")
|
|
theirs = {"type": "command", "command": "~/.claude/my-statusline.sh"}
|
|
rig.edit(lambda settings: {**settings, "statusLine": theirs})
|
|
|
|
outcome = rig.unconfigure()
|
|
assert rig.read()["statusLine"] == theirs
|
|
assert "statusLine" in outcome.kept
|
|
|
|
def test_a_receipt_from_before_the_status_line_existed_still_unconfigures(self, tmp_path):
|
|
# Older receipts never claimed statusLine; a key no configure wrote is never ours, so it stays.
|
|
rig = _Rig(tmp_path, None)
|
|
script = tmp_path / "statusline.py"
|
|
rig.configure(model=KeepModel(), script_path=script)
|
|
receipt = json.loads(rig.state.read_text())
|
|
receipt["written"].pop("statusLine")
|
|
receipt["previous"].pop("statusLine")
|
|
rig.state.write_text(json.dumps(receipt))
|
|
|
|
outcome = rig.unconfigure()
|
|
restored = rig.read()
|
|
assert "ANTHROPIC_AUTH_TOKEN" not in restored.get("env", {})
|
|
assert restored["statusLine"]["command"] == statusline_command(script)
|
|
assert "statusLine" not in outcome.restored
|
|
|
|
|
|
@pytest.mark.skipif(os.name != "posix" or os.geteuid() == 0, reason="needs a directory its owner cannot write")
|
|
def test_a_key_file_that_cannot_be_removed_is_named_so_the_user_can_delete_it(tmp_path, capsys):
|
|
config_dir = tmp_path / "cfg"
|
|
config_dir.mkdir()
|
|
stuck = config_dir / f"{LAUNCH_KEY_OVERLAY_PREFIX}0123456789abcdef.json"
|
|
stuck.write_text("{}")
|
|
config_dir.chmod(0o500)
|
|
try:
|
|
remove_launch_settings_files(config_dir)
|
|
finally:
|
|
config_dir.chmod(0o700)
|
|
|
|
output = capsys.readouterr()
|
|
assert stuck.exists()
|
|
assert str(stuck) in output.err
|
|
assert "Removed" not in output.out
|