Skip to content

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

feat(cli): add `lite login --config-claude` to wire Claude Code at login (#37507)

Yassin Kortam6ca48efc8bdc
diff --git a/litellm/proxy/client/cli/README.md b/litellm/proxy/client/cli/README.md
index 72ed67728d8..9fe52b7a27d 100644
--- a/litellm/proxy/client/cli/README.md
+++ b/litellm/proxy/client/cli/README.md
@@ -521,6 +521,20 @@ This is a one-time file patch and restore, not a live traffic interceptor. A Cla
Cursor is not supported: it has no equivalent file-based config to hot-patch this way, since its model routing lives in its own app storage and is configured through its GUI.
+#### Making It Permanent at Login
+
+`lite up` holds the patch only for as long as it runs. To wire Claude Code up once and leave it that way, pass `--config-claude` to `lite login`:
+
+```bash
+lite --base-url https://your-proxy.example.com login --config-claude
+```
+
+It writes the same two settings `lite up` does, `env.ANTHROPIC_BASE_URL` and `apiKeyHelper`, but persistently: there is no backup, nothing to restore, and no foreground process to keep alive. Every other key in `~/.claude/settings.json` is preserved, the file is created if it does not exist, and it is written atomically with owner-only permissions. Plain `lite login` is unchanged; nothing happens to your Claude Code config unless you pass the flag.
+
+Because the credential is reached through `apiKeyHelper` rather than copied into the file, a later `lite login` refreshes it with no further action: Claude Code re-runs the helper on every request and picks up whatever token the most recent login stored. Nothing secret is written to `settings.json`.
+
+Run it again to point Claude Code at a different proxy; the base URL and the helper are both rewritten. `lite up` and `--config-claude` manage the same file, so the flag refuses to run while a `lite up` session holds a backup, and tells you to run `lite down` first, rather than writing settings that `lite up` would silently revert when it stops.
+
### QA Complexity-Based Auto-Routing Against Your Real Proxy
`lite autoroute` lets you try LiteLLM's complexity-based auto-routing -- picking a cheaper or more expensive model depending on how complex a prompt looks -- against models your key already has access to on your real, running proxy, without editing that proxy's `config.yaml` and without any real request ever bypassing it. It builds a second, throwaway proxy locally that forwards every request back to your real proxy, and points Claude Code at that local proxy for the duration of the session.
diff --git a/litellm/proxy/client/cli/commands/auth.py b/litellm/proxy/client/cli/commands/auth.py
index 1cac515f9f2..0a0bcf80ee5 100644
--- a/litellm/proxy/client/cli/commands/auth.py
+++ b/litellm/proxy/client/cli/commands/auth.py
@@ -16,6 +16,12 @@ from typing_extensions import NotRequired, TypedDict
from litellm.constants import CLI_JWT_EXPIRATION_HOURS
from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh
+from .claude_settings import (
+ CLAUDE_SETTINGS_PATH,
+ SETTINGS_FILE_OWNERS,
+ ClaudeSettingsError,
+ write_claude_settings,
+)
from .private_json import write_private_json
@@ -629,9 +635,28 @@ def _render_and_prompt_for_team_selection(teams: list[CliTeam]) -> str | None:
return None
+def _configure_claude_code(base_url: str) -> None:
+ """Point Claude Code at base_url by patching ~/.claude/settings.json."""
+ try:
+ write_claude_settings(base_url, CLAUDE_SETTINGS_PATH, SETTINGS_FILE_OWNERS)
+ except ClaudeSettingsError as e:
+ raise click.ClickException(f"Logged in, but could not configure Claude Code: {e}")
+ click.echo(f"\nConfigured Claude Code: {CLAUDE_SETTINGS_PATH} now routes through {base_url.rstrip('/')}.")
+ click.echo("Your other Claude Code settings were left untouched. Restart Claude Code to pick this up.")
+
+
@click.command(name="login")
+ "--config-claude",
+ is_flag=True,
+ default=False,
+ help=(
+ "After logging in, update ~/.claude/settings.json so Claude Code routes through this proxy. "
+ "Unrelated settings are preserved."
+ ),
+)
@click.pass_context
-def login(ctx: click.Context):
+def login(ctx: click.Context, config_claude: bool):
"""Login to LiteLLM proxy using SSO authentication"""
from litellm.constants import LITELLM_CLI_SOURCE_IDENTIFIER
from litellm.proxy.client.cli.interface import show_commands
@@ -683,6 +708,9 @@ def login(ctx: click.Context):
click.echo(f"JWT Token: {api_key[:20]}...")
click.echo("You can now use the CLI without specifying --api-key")
+ if config_claude:
+ _configure_claude_code(base_url)
+
# Show available commands after successful login
click.echo("\n" + "=" * 60)
show_commands()
@@ -698,6 +726,10 @@ def login(ctx: click.Context):
except KeyboardInterrupt:
click.echo("\nAuthentication cancelled by user.")
return
+ except click.ClickException:
+ # Login itself already succeeded; only the post-login step failed, so this
+ # must not be relabelled as an authentication failure by the handler below.
+ raise
except Exception as e:
click.echo(f"Authentication failed: {e}")
return
diff --git a/litellm/proxy/client/cli/commands/autoroute/commands.py b/litellm/proxy/client/cli/commands/autoroute/commands.py
index 09e5a53b92f..26d45138a27 100644
--- a/litellm/proxy/client/cli/commands/autoroute/commands.py
+++ b/litellm/proxy/client/cli/commands/autoroute/commands.py
@@ -10,11 +10,16 @@ import click
import yaml
from pydantic import JsonValue, TypeAdapter, ValidationError
-from ..up import CLAUDE_SETTINGS_PATH, UpError, load_json_or_empty, restore_claude_settings, write_backup
+from ..claude_settings import (
+ AUTOROUTE_BACKUP_PATH,
+ CLAUDE_SETTINGS_PATH,
+ ClaudeSettingsError,
+ load_json_or_empty,
+)
from ..up import BackupRecord as ClaudeBackupRecord
+from ..up import restore_claude_settings, write_backup
from .config import master_key_from_config
from .process import (
- AUTOROUTE_DIR,
CONFIG_PATH,
DEFAULT_AUTOROUTE_PORT,
LOG_PATH,
@@ -35,8 +40,6 @@ from .process import (
from .settings import merge_claude_settings_static_token
from .wizard import run_configure_wizard
-AUTOROUTE_BACKUP_PATH: Final = AUTOROUTE_DIR / "claude_settings_backup.json"
-
_GENERATED_CONFIG_ADAPTER: Final = TypeAdapter(dict[str, JsonValue])
@@ -108,7 +111,7 @@ def up(port: int) -> None:
try:
existing_pid: Final = read_pid_record()
- except UpError as e:
+ except ClaudeSettingsError as e:
raise click.ClickException(str(e))
if existing_pid is not None and is_running(existing_pid.pid):
raise click.ClickException(
@@ -157,7 +160,7 @@ def up(port: int) -> None:
CLAUDE_SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True)
with secure_create(CLAUDE_SETTINGS_PATH) as f:
json.dump(merged, f, indent=2)
- except UpError as e:
+ except ClaudeSettingsError as e:
terminate(process.pid)
clear_pid_record()
raise click.ClickException(str(e))
@@ -175,7 +178,7 @@ def up(port: int) -> None:
clear_pid_record()
try:
restore_claude_settings(CLAUDE_SETTINGS_PATH, AUTOROUTE_BACKUP_PATH)
- except UpError as e:
+ except ClaudeSettingsError as e:
# Runs from atexit/a signal handler too, outside Click's own exception
# handling -- raising here would only produce an unhandled-exception
# warning on stderr, not a clean message.
@@ -207,7 +210,7 @@ def down() -> None:
"""Restore Claude Code settings and stop a leftover ephemeral proxy, if any"""
try:
record: PidRecord | None = read_pid_record()
- except UpError as e:
+ except ClaudeSettingsError as e:
# down is the crash-recovery path -- a corrupt pid record must not block it; clear the
# unusable record and keep going rather than leaving the user with no way to clean up.
click.echo(f"{e} Clearing it and continuing cleanup.", err=True)
@@ -219,7 +222,7 @@ def down() -> None:
try:
restored: Final = restore_claude_settings(CLAUDE_SETTINGS_PATH, AUTOROUTE_BACKUP_PATH)
- except UpError as e:
+ except ClaudeSettingsError as e:
raise click.ClickException(str(e))
if restored is None:
click.echo("Nothing to restore.")
diff --git a/litellm/proxy/client/cli/commands/claude_settings.py b/litellm/proxy/client/cli/commands/claude_settings.py
new file mode 100644
index 00000000000..e9a6a25a064
--- /dev/null
+++ b/litellm/proxy/client/cli/commands/claude_settings.py
@@ -0,0 +1,155 @@
+"""Shared handling of Claude Code's ~/.claude/settings.json.
+
+`lite up` patches this file temporarily and restores it on exit; `lite login
+--config-claude` patches it persistently. Both need the same merge and the same
+apiKeyHelper command, and `up` already imports from `auth`, so the shared parts
+live here rather than in either command module.
+"""
+
+import shlex
+import shutil
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Final
+
+from pydantic import JsonValue, TypeAdapter, ValidationError
+
+from .private_json import write_private_json
+
+ENV_KEY: Final = "env"
+API_KEY_HELPER_KEY: Final = "apiKeyHelper"
+ANTHROPIC_BASE_URL_KEY: Final = "ANTHROPIC_BASE_URL"
+ANTHROPIC_API_KEY_KEY: Final = "ANTHROPIC_API_KEY"
+
+CLAUDE_SETTINGS_PATH: Final = Path.home() / ".claude" / "settings.json"
+BACKUP_PATH: Final = Path.home() / ".litellm" / "claude_settings_backup.json"
+AUTOROUTE_BACKUP_PATH: Final = Path.home() / ".litellm" / "autorouter" / "claude_settings_backup.json"
+
+
+@dataclass(frozen=True, slots=True)
+class SettingsFileOwner:
+ """A command that takes temporary ownership of CLAUDE_SETTINGS_PATH and restores it later."""
+
+ backup_path: Path
+ start_command: str
+ stop_command: str
+
+
+SETTINGS_FILE_OWNERS: Final = (
+ SettingsFileOwner(BACKUP_PATH, "lite up", "lite down"),
+ SettingsFileOwner(AUTOROUTE_BACKUP_PATH, "lite autoroute up", "lite autoroute down"),
+)
+
+_SETTINGS_ADAPTER: Final = TypeAdapter(dict[str, JsonValue])
+
+
+class ClaudeSettingsError(Exception):
+ """Raised for any user-actionable failure while reading or writing Claude Code settings."""
+
+
+def load_json_or_empty(path: Path) -> dict[str, JsonValue]:
+ try:
+ content: Final = path.read_bytes() if path.exists() else b""
+ except OSError as e:
+ raise ClaudeSettingsError(f"Could not read {path}: {e}") from e
+ if not content.strip():
+ return {}
+ try:
+ return _SETTINGS_ADAPTER.validate_json(content)
+ except ValidationError:
+ raise ClaudeSettingsError(
+ f"{path} contains invalid JSON (or its root is not an object); cannot proceed safely."
+ )
+
+
+def merge_claude_settings(
+ settings: Mapping[str, JsonValue], base_url: str, api_key_helper: str
+) -> dict[str, JsonValue]:
+ """Return a new settings dict wired to route Claude Code through the proxy.
+
+ Only env.ANTHROPIC_BASE_URL and the top-level apiKeyHelper are overridden; a
+ stray env.ANTHROPIC_API_KEY is dropped so it cannot outrank the helper-issued
+ token (same reasoning as build_agent_env in agents.py). Every other key is
+ preserved untouched.
+ """
+ raw_env: Final = settings.get(ENV_KEY, {})
+ base_env: Final = raw_env if isinstance(raw_env, dict) else {}
+ env: Final = {
+ **{key: value for key, value in base_env.items() if key != ANTHROPIC_API_KEY_KEY},
+ ANTHROPIC_BASE_URL_KEY: base_url.rstrip("/"),
+ }
+ return {**settings, ENV_KEY: env, API_KEY_HELPER_KEY: api_key_helper}
+
+
+def resolve_api_key_helper(base_url: str) -> str:
+ """Build the shell command Claude Code should run for its apiKeyHelper.
+
+ Resolves `lite` to an absolute path so the helper works regardless of the
+ PATH visible to whatever subprocess Claude Code spawns it from. Passing
+ --base-url explicitly (rather than relying on the bare invocation Claude
+ Code would otherwise use) makes `print-token` enforce that the cached
+ token was actually issued for this proxy -- without it, a token minted
+ for a different, previously-logged-into proxy would be handed to
+ whichever server the settings currently point at.
+
+ --base-url belongs to the top-level `lite` group, so it has to precede the
+ subcommand; click rejects it outright after `print-token`.
+ """
+ lite_path: Final = shutil.which("lite")
+ if lite_path is None:
+ raise ClaudeSettingsError(
+ "Could not find `lite` on your PATH. Claude Code's apiKeyHelper needs an absolute path to it."
+ )
+ return f"{shlex.quote(lite_path)} --base-url {shlex.quote(base_url)} auth print-token"
+
+
+def write_claude_settings(base_url: str, settings_path: Path, owners: Sequence[SettingsFileOwner]) -> None:
+ """Persistently point Claude Code at base_url, preserving every unrelated setting.
+
+ Refuses while any owner holds a backup: each restores its backup when it
+ stops, which would silently undo this write.
+ """
+ for owner in owners:
+ if owner.backup_path.exists():
+ raise ClaudeSettingsError(
+ f"`{owner.start_command}` is currently managing {settings_path} (backup at "
+ f"{owner.backup_path}) and will restore it when it stops. "
+ f"Run `{owner.stop_command}` first, then retry."
+ )
+ normalized_base_url: Final = base_url.rstrip("/")
+ api_key_helper: Final = resolve_api_key_helper(normalized_base_url)
+ existing: Final = load_json_or_empty(settings_path)
+ raw_env: Final = existing.get(ENV_KEY)
+ if raw_env is not None and not isinstance(raw_env, dict):
+ raise ClaudeSettingsError(
+ f'{settings_path} has a non-object "{ENV_KEY}" value, which this would discard. '
+ "Fix or remove it, then retry."
+ )
+ merged: Final = merge_claude_settings(existing, normalized_base_url, api_key_helper)
+ # os.replace() swaps the symlink itself for a regular file, silently detaching a
+ # settings.json that is symlinked into a dotfiles repo. There is no backup to undo
+ # that here, unlike `lite up`, so write through to the link's target instead.
+ target: Final = settings_path.resolve() if settings_path.is_symlink() else settings_path
+ try:
+ write_private_json(str(target), merged)
+ except OSError as e:
+ raise ClaudeSettingsError(f"Could not write {target}: {e}") from e
+
+
+__all__ = (
+ "ANTHROPIC_API_KEY_KEY",
+ "ANTHROPIC_BASE_URL_KEY",
+ "API_KEY_HELPER_KEY",
+ "AUTOROUTE_BACKUP_PATH",
+ "BACKUP_PATH",
+ "CLAUDE_SETTINGS_PATH",
+ "ENV_KEY",
+ "SETTINGS_FILE_OWNERS",
+ "ClaudeSettingsError",
+ "SettingsFileOwner",
+ "load_json_or_empty",
+ "merge_claude_settings",
+ "resolve_api_key_helper",
+ "write_claude_settings",
+)
diff --git a/litellm/proxy/client/cli/commands/up.py b/litellm/proxy/client/cli/commands/up.py
index 7023241cf06..dd266b4afa1 100644
--- a/litellm/proxy/client/cli/commands/up.py
+++ b/litellm/proxy/client/cli/commands/up.py
@@ -2,12 +2,10 @@ import atexit
import contextlib
import json
import os
-import shlex
-import shutil
import signal
import sys
import threading
-from collections.abc import Iterator, Mapping
+from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from types import FrameType
@@ -20,17 +18,17 @@ from litellm.litellm_core_utils.cli_token_utils import is_cli_token_fresh
from .agents import AgentRunError, resolve_api_key, verify_proxy_key
from .auth import load_token, login
+from .claude_settings import (
+ BACKUP_PATH,
+ CLAUDE_SETTINGS_PATH,
+ ClaudeSettingsError,
+ load_json_or_empty,
+ merge_claude_settings,
+ resolve_api_key_helper,
+)
-ENV_KEY: Final = "env"
-API_KEY_HELPER_KEY: Final = "apiKeyHelper"
-ANTHROPIC_BASE_URL_KEY: Final = "ANTHROPIC_BASE_URL"
-ANTHROPIC_API_KEY_KEY: Final = "ANTHROPIC_API_KEY"
-CLAUDE_SETTINGS_PATH: Final = Path.home() / ".claude" / "settings.json"
-BACKUP_PATH: Final = Path.home() / ".litellm" / "claude_settings_backup.json"
-
-
-class UpError(Exception):
+class UpError(ClaudeSettingsError):
"""Raised for any user-actionable failure while starting/stopping interception."""
@@ -42,40 +40,9 @@ class BackupRecord:
content: dict[str, JsonValue] | None
-_SETTINGS_ADAPTER: Final = TypeAdapter(dict[str, JsonValue])
_BACKUP_RECORD_ADAPTER: Final = TypeAdapter(BackupRecord)
-def load_json_or_empty(path: Path) -> dict[str, JsonValue]:
- if not path.exists():
- return {}
- with open(path, "r") as f:
- content: Final = f.read()
- if not content.strip():
- return {}
- try:
- return _SETTINGS_ADAPTER.validate_json(content)
- except ValidationError:
- raise UpError(f"{path} contains invalid JSON (or its root is not an object); cannot proceed safely.")
-
-
-def merge_claude_settings(
- settings: Mapping[str, JsonValue], base_url: str, api_key_helper: str
-) -> dict[str, JsonValue]:
- """Return a new settings dict wired to route Claude Code through the proxy.
-
- Only env.ANTHROPIC_BASE_URL and the top-level apiKeyHelper are overridden; a
- stray env.ANTHROPIC_API_KEY is dropped so it cannot outrank the helper-issued
- token (same reasoning as build_agent_env in agents.py). Every other key is
- preserved untouched.
- """
- raw_env: Final = settings.get(ENV_KEY, {})
- base_env: Final = raw_env if isinstance(raw_env, dict) else {}
- env: Final = {**base_env, ANTHROPIC_BASE_URL_KEY: base_url.rstrip("/")}
- env.pop(ANTHROPIC_API_KEY_KEY, None)
- return {**settings, ENV_KEY: env, API_KEY_HELPER_KEY: api_key_helper}
-
-
@contextlib.contextmanager
def secure_create(path: Path) -> Iterator[IO[str]]:
"""Open path for writing with mode 0600 fixed up before any content is written.
@@ -136,26 +103,6 @@ def restore_claude_settings(settings_path: Path | None = None, backup_path: Path
return record
-def resolve_api_key_helper(base_url: str) -> str:
- """Build the shell command Claude Code should run for its apiKeyHelper.
-
- Resolves `lite` to an absolute path so the helper works regardless of the
- PATH visible to whatever subprocess Claude Code spawns it from. Passing
- --base-url explicitly (rather than relying on the bare invocation Claude
- Code would otherwise use) makes `print-token` enforce that the cached
- token was actually issued for this proxy -- without it, a token minted
- for a different, previously-logged-into proxy would be handed to
- whichever server `up` currently points at.
- """
- lite_path: Final = shutil.which("lite")
- if lite_path is None:
- raise UpError(
- "Could not find `lite` on your PATH. Claude Code's apiKeyHelper needs "
- "an absolute path to it, so `lite up` cannot continue."
- )
- return f"{shlex.quote(lite_path)} auth print-token --base-url {shlex.quote(base_url)}"
-
-
def _ensure_fresh_login(ctx: click.Context) -> None:
base_url: Final = ctx.obj["base_url"].rstrip("/")
token_data = load_token()
@@ -224,7 +171,7 @@ def up(ctx: click.Context) -> None:
merged: Final = merge_claude_settings(original_settings, base_url, api_key_helper)
with open(CLAUDE_SETTINGS_PATH, "w") as f:
json.dump(merged, f, indent=2)
- except (AgentRunError, UpError) as e:
+ except (AgentRunError, ClaudeSettingsError) as e:
raise click.ClickException(str(e))
click.echo(f"litellm: routing Claude Code through proxy at {base_url.rstrip('/')}")
@@ -241,7 +188,7 @@ def up(ctx: click.Context) -> None:
return
try:
_restore_and_report()
- except UpError as e:
+ except ClaudeSettingsError as e:
# Runs from atexit/a signal handler, outside Click's own exception
# handling -- raising here would only produce an unhandled-exception
# warning on stderr, not a clean message.
@@ -264,7 +211,7 @@ def down() -> None:
"""
try:
_restore_and_report()
- except UpError as e:
+ except ClaudeSettingsError as e:
raise click.ClickException(str(e))
@@ -272,6 +219,7 @@ __all__ = [
"BACKUP_PATH",
"CLAUDE_SETTINGS_PATH",
"BackupRecord",
+ "ClaudeSettingsError",
"UpError",
"down",
"load_json_or_empty",
diff --git a/tests/test_litellm/proxy/client/cli/test_auth_commands.py b/tests/test_litellm/proxy/client/cli/test_auth_commands.py
index f0aa49ff123..59048067674 100644
--- a/tests/test_litellm/proxy/client/cli/test_auth_commands.py
+++ b/tests/test_litellm/proxy/client/cli/test_auth_commands.py
@@ -25,6 +25,7 @@ from litellm.proxy.client.cli.commands.auth import (
save_token,
whoami,
)
+from litellm.proxy.client.cli.commands.claude_settings import SettingsFileOwner
def _mock_cli_sso_start_response(
@@ -267,7 +268,7 @@ class TestTokenUtilities:
def test_load_token_io_error(self):
"""Test loading token with IO error"""
with (
- patch("builtins.open", side_effect=IOError("Permission denied")),
+ patch("builtins.open", side_effect=OSError("Permission denied")),
patch("litellm.proxy.client.cli.commands.auth.get_token_file_path") as mock_path,
patch("os.path.exists", return_value=True),
):
@@ -1029,3 +1030,83 @@ class TestSaveTokenPrivateWrite:
assert json.loads(token_file.read_text()) == {"key": "sk-original", "timestamp": 1234567890}
assert list(token_file.parent.glob(".tmp-*")) == []
+
+
+class TestLoginConfigClaude:
+ """`lite login --config-claude` wiring into ~/.claude/settings.json"""
+
+ def setup_method(self):
+ self.runner = CliRunner()
+
+ def _run_login(self, tmp_path, args, base_url="https://test.example.com"):
+ settings_path = tmp_path / "claude" / "settings.json"
+ backup_path = tmp_path / "claude_settings_backup.json"
+ poll_response = Mock()
+ poll_response.status_code = 200
+ poll_response.json.return_value = {
+ "status": "ready",
+ "key": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.test.jwt",
+ "user_id": "test-user-123",
+ "team_id": "team-1",
+ "teams": ["team-1"],
+ }
+ with (
+ patch("webbrowser.open"),
+ patch("requests.post", return_value=_mock_cli_sso_start_response()),
+ patch("requests.get", return_value=poll_response),
+ patch("litellm.proxy.client.cli.commands.auth.save_token"),
+ patch("litellm.proxy.client.cli.interface.show_commands"),
+ patch("litellm.proxy.client.cli.commands.auth.CLAUDE_SETTINGS_PATH", settings_path),
+ patch(
+ "litellm.proxy.client.cli.commands.auth.SETTINGS_FILE_OWNERS",
+ (SettingsFileOwner(backup_path, "lite up", "lite down"),),
+ ),
+ patch(
+ "litellm.proxy.client.cli.commands.claude_settings.shutil.which",
+ return_value="/usr/local/bin/lite",
+ ),
+ ):
+ result = self.runner.invoke(login, args, obj={"base_url": base_url})
+ return result, settings_path, backup_path
+
+ def test_default_login_does_not_touch_claude_settings(self, tmp_path):
+ result, settings_path, _backup_path = self._run_login(tmp_path, [])
+
+ assert result.exit_code == 0
+ assert "Login successful!" in result.output
+ assert not settings_path.exists()
+ assert "Configured Claude Code" not in result.output
+
+ def test_flag_writes_the_settings_file_and_reports_success(self, tmp_path):
+ result, settings_path, _backup_path = self._run_login(tmp_path, ["--config-claude"])
+
+ assert result.exit_code == 0
+ written = json.loads(settings_path.read_text())
+ assert written["env"]["ANTHROPIC_BASE_URL"] == "https://test.example.com"
+ assert written["apiKeyHelper"] == "/usr/local/bin/lite --base-url https://test.example.com auth print-token"
+ assert "Configured Claude Code" in result.output
+
+ def test_flag_preserves_unrelated_settings_on_an_existing_file(self, tmp_path):
+ settings_path = tmp_path / "claude" / "settings.json"
+ settings_path.parent.mkdir(parents=True)
+ settings_path.write_text(json.dumps({"theme": "dark", "env": {"KEEP": "me"}}))
+
+ result, _settings_path, _backup_path = self._run_login(tmp_path, ["--config-claude"])
+
+ assert result.exit_code == 0
+ written = json.loads(settings_path.read_text())
+ assert written["theme"] == "dark"
+ assert written["env"]["KEEP"] == "me"
+
+ def test_settings_failure_is_reported_without_claiming_login_failed(self, tmp_path):
+ settings_path = tmp_path / "claude" / "settings.json"
+ settings_path.parent.mkdir(parents=True)
+ settings_path.write_text("not json at all {{{")
+
+ result, _settings_path, _backup_path = self._run_login(tmp_path, ["--config-claude"])
+
+ assert result.exit_code != 0
+ assert "Login successful!" in result.output
+ assert "could not configure Claude Code" in result.output
+ assert "invalid JSON" in result.output
+ assert "Authentication failed" not in result.output
diff --git a/tests/test_litellm/proxy/client/cli/test_claude_settings.py b/tests/test_litellm/proxy/client/cli/test_claude_settings.py
new file mode 100644
index 00000000000..bc9744eb410
--- /dev/null
+++ b/tests/test_litellm/proxy/client/cli/test_claude_settings.py
@@ -0,0 +1,269 @@
+import json
+import shlex
+import stat
+import time
+from unittest.mock import patch
+
+import pytest
+from click.testing import CliRunner
+
+from litellm.proxy.client.cli import cli
+from litellm.proxy.client.cli.commands.claude_settings import (
+ AUTOROUTE_BACKUP_PATH,
+ BACKUP_PATH,
+ SETTINGS_FILE_OWNERS,
+ ClaudeSettingsError,
+ SettingsFileOwner,
+ resolve_api_key_helper,
+ write_claude_settings,
+)
+
+
+def _owners(*backup_paths):
+ """Stand-in owners for the real `lite up` / `lite autoroute up` 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"
+
+
+def paths(tmp_path):
+ return tmp_path / "claude" / "settings.json", tmp_path / "backup.json"
+
+
+def lite_on_path():
+ with patch(f"{CLAUDE_SETTINGS_MODULE}.shutil.which", return_value="/usr/local/bin/lite"):
+ yield
+
+
+class TestWriteClaudeSettings:
+ def test_creates_the_file_and_its_parent_when_missing(self, paths, lite_on_path):
+ settings_path, backup_path = paths
+ assert not settings_path.parent.exists()
+
+ write_claude_settings("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["apiKeyHelper"] == "/usr/local/bin/lite --base-url https://proxy.example.com auth print-token"
+
+ def test_updates_an_existing_file_preserving_unrelated_settings(self, paths, lite_on_path):
+ 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"},
+ "apiKeyHelper": "old-helper",
+ }
+ )
+ )
+
+ write_claude_settings("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"
+ assert written["apiKeyHelper"] != "old-helper"
+
+ def test_rerunning_against_a_new_proxy_refreshes_both_base_url_and_helper(self, paths, lite_on_path):
+ settings_path, backup_path = paths
+
+ write_claude_settings("https://first.example.com", settings_path, _owners(backup_path))
+ write_claude_settings("https://second.example.com", settings_path, _owners(backup_path))
+
+ written = json.loads(settings_path.read_text())
+ assert written["env"]["ANTHROPIC_BASE_URL"] == "https://second.example.com"
+ assert "second.example.com" in written["apiKeyHelper"]
+ assert "first.example.com" not in written["apiKeyHelper"]
+
+ def test_drops_a_stray_static_api_key_so_the_helper_token_wins(self, paths, lite_on_path):
+ settings_path, backup_path = paths
+ settings_path.parent.mkdir(parents=True)
+ settings_path.write_text(json.dumps({"env": {"ANTHROPIC_API_KEY": "sk-leaked"}}))
+
+ write_claude_settings("https://proxy.example.com", settings_path, _owners(backup_path))
+
+ assert "ANTHROPIC_API_KEY" not in json.loads(settings_path.read_text())["env"]
+
+ def test_written_file_is_owner_only(self, paths, lite_on_path):
+ settings_path, backup_path = paths
+ write_claude_settings("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, lite_on_path):
+ settings_path, backup_path = paths
+ backup_path.write_text("{}")
+
+ with pytest.raises(ClaudeSettingsError, match="lite down"):
+ write_claude_settings("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, lite_on_path):
+ 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"):
+ write_claude_settings("https://proxy.example.com", settings_path, _owners(backup_path))
+
+ assert settings_path.read_text() == "not json at all {{{"
+
+ def test_reports_an_actionable_error_when_lite_is_not_on_path(self, paths):
+ settings_path, backup_path = paths
+ with patch(f"{CLAUDE_SETTINGS_MODULE}.shutil.which", return_value=None):
+ with pytest.raises(ClaudeSettingsError, match="Could not find `lite`"):
+ write_claude_settings("https://proxy.example.com", settings_path, _owners(backup_path))
+
+ assert not settings_path.exists()
+
+ def test_reports_an_actionable_error_on_a_non_utf8_file(self, paths, lite_on_path):
+ """Bytes that are not valid UTF-8 must not escape as UnicodeDecodeError.
+
+ UnicodeDecodeError is a ValueError, not an OSError, so a decode-side catch
+ is easy to miss; login's broad `except Exception` would then relabel it as
+ an authentication failure and exit 0.
+ """
+ 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"):
+ write_claude_settings("https://proxy.example.com", settings_path, _owners(backup_path))
+
+ def test_reports_an_actionable_error_when_the_file_cannot_be_read(self, paths, lite_on_path):
+ """An unreadable settings file must not surface as "Authentication failed".
+
+ login wraps the whole flow in a broad `except Exception`, so any OSError
+ escaping this function gets relabelled as an auth failure and sends the
+ user looking at their SSO config instead of at file permissions.
+ """
+ settings_path, backup_path = paths
+ settings_path.parent.mkdir(parents=True)
+ settings_path.mkdir()
+
+ with pytest.raises(ClaudeSettingsError, match="Could not read"):
+ write_claude_settings("https://proxy.example.com", settings_path, _owners(backup_path))
+
+ def test_reports_an_actionable_error_when_the_file_cannot_be_written(self, paths, lite_on_path):
+ settings_path, backup_path = paths
+ with patch(
+ f"{CLAUDE_SETTINGS_MODULE}.write_private_json",
+ side_effect=OSError("Read-only file system"),
+ ):
+ with pytest.raises(ClaudeSettingsError, match="Read-only file system"):
+ write_claude_settings("https://proxy.example.com", settings_path, _owners(backup_path))
+
+
+class TestApiKeyHelperIsActuallyInvocable:
+ """The helper string is executed verbatim by Claude Code, so it has to parse.
+
+ Asserting only on its text is what let a malformed command (`--base-url`, a
+ top-level group option, placed after the `print-token` subcommand) ship: click
+ rejects it with "No such option" and every Claude Code request loses its token.
+ """
+
+ def _helper_args(self, base_url):
+ with patch(f"{CLAUDE_SETTINGS_MODULE}.shutil.which", return_value="/usr/local/bin/lite"):
+ return shlex.split(resolve_api_key_helper(base_url))[1:]
+
+ def test_the_generated_command_parses(self):
+ result = CliRunner().invoke(cli, self._helper_args("http://localhost:4000"))
+
+ assert "No such option" not in result.output
+ assert result.exit_code != 2
+
+ def test_the_generated_command_reaches_print_token(self):
+ with patch(f"{AUTH_MODULE}.load_token", return_value=None):
+ result = CliRunner().invoke(cli, self._helper_args("http://localhost:4000"))
+
+ assert "Not authenticated" in result.output
+
+ def test_the_generated_command_carries_the_base_url_through(self):
+ stale = {
+ "base_url": "http://other-proxy.example.com",
+ "key": "sk-stale",
+ "timestamp": time.time(),
+ }
+ with patch(f"{AUTH_MODULE}.load_token", return_value=stale):
+ result = CliRunner().invoke(cli, self._helper_args("http://localhost:4000"))
+
+ assert "Not authenticated for this server" in result.output
+
+
+class TestConflictingOwnersOfTheSettingsFile:
+ """Both `lite up` and `lite autoroute up` 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, lite_on_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"):
+ write_claude_settings("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, lite_on_path):
+ settings_path = tmp_path / "claude" / "settings.json"
+ backup = tmp_path / "auto.json"
+ backup.write_text("{}")
+ autoroute = SettingsFileOwner(backup, "lite autoroute up", "lite autoroute down")
+
+ with pytest.raises(ClaudeSettingsError, match="`lite autoroute up` is currently managing"):
+ write_claude_settings("https://proxy.example.com", settings_path, (autoroute,))
+ with pytest.raises(ClaudeSettingsError, match="Run `lite autoroute down` first"):
+ write_claude_settings("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."""
+ from litellm.proxy.client.cli.commands.autoroute.process import AUTOROUTE_DIR
+
+ 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 down"}
+
+
+class TestDoesNotDestroyUserOwnedStructure:
+ def test_writes_through_a_symlinked_settings_file(self, tmp_path, lite_on_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)
+
+ write_claude_settings("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, lite_on_path):
+ """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"):
+ write_claude_settings("https://proxy.example.com", settings_path, _owners(backup_path))
+
+ assert json.loads(settings_path.read_text())["env"] == "not-an-object"
diff --git a/tests/test_litellm/proxy/client/cli/test_up_commands.py b/tests/test_litellm/proxy/client/cli/test_up_commands.py
index 1b182553644..51de0dcf11d 100644
--- a/tests/test_litellm/proxy/client/cli/test_up_commands.py
+++ b/tests/test_litellm/proxy/client/cli/test_up_commands.py
@@ -10,6 +10,7 @@ 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
from litellm.proxy.client.cli.commands.up import (
BackupRecord,
UpError,
@@ -25,6 +26,7 @@ from litellm.proxy.client.cli.commands.up import (
)
UP_MODULE = "litellm.proxy.client.cli.commands.up"
+AUTH_MODULE = "litellm.proxy.client.cli.commands.auth"
def _patch_paths(monkeypatch, tmp_path):
@@ -92,13 +94,13 @@ class TestLoadJsonOrEmpty:
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(UpError, match="invalid JSON"):
+ 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(UpError, match="invalid JSON"):
+ with pytest.raises(ClaudeSettingsError, match="invalid JSON"):
load_json_or_empty(path)
@@ -201,16 +203,16 @@ class TestResolveApiKeyHelper:
def test_returns_helper_command_bound_to_the_selected_proxy(self, monkeypatch):
monkeypatch.setattr(shutil, "which", lambda name: "/usr/local/bin/lite")
helper = resolve_api_key_helper("http://localhost:4000")
- assert helper == "/usr/local/bin/lite auth print-token --base-url http://localhost:4000"
+ assert helper == "/usr/local/bin/lite --base-url http://localhost:4000 auth print-token"
def test_quotes_a_base_url_containing_shell_metacharacters(self, monkeypatch):
monkeypatch.setattr(shutil, "which", lambda name: "/usr/local/bin/lite")
helper = resolve_api_key_helper("http://example.com/path; rm -rf /")
- assert helper == "/usr/local/bin/lite auth print-token --base-url 'http://example.com/path; rm -rf /'"
+ assert helper == "/usr/local/bin/lite --base-url 'http://example.com/path; rm -rf /' auth print-token"
def test_raises_when_lite_not_on_path(self, monkeypatch):
monkeypatch.setattr(shutil, "which", lambda name: None)
- with pytest.raises(UpError, match="Could not find `lite`"):
+ with pytest.raises(ClaudeSettingsError, match="Could not find `lite`"):
resolve_api_key_helper("http://localhost:4000")
@@ -396,3 +398,50 @@ class TestDownCommand:
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)
+
+ 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)
+
+ with (
+ patch(f"{AUTH_MODULE}.CLAUDE_SETTINGS_PATH", settings_path),
+ patch(f"{AUTH_MODULE}._start_cli_sso_flow", side_effect=RuntimeError("stop")),
+ ):
+ CliRunner().invoke(driver, [], standalone_mode=False)
+
+ assert not settings_path.exists()