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): keep the claude.ai login with `lite claude --subscription` and save pkce in config (#47385)

Yassin Kortam1525e4bce50c
diff --git a/litellm/proxy/client/cli/commands/agents.py b/litellm/proxy/client/cli/commands/agents.py
index 03540a7395e..52e36964bc1 100644
--- a/litellm/proxy/client/cli/commands/agents.py
+++ b/litellm/proxy/client/cli/commands/agents.py
@@ -7,13 +7,14 @@ import sys
import tempfile
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
+from itertools import chain
from pathlib import Path
from types import MappingProxyType
-from typing import Final, TypeAlias
+from typing import Final, TypeAlias, TypeVar
import click
import requests
-from pydantic import TypeAdapter, ValidationError
+from pydantic import JsonValue, TypeAdapter, ValidationError
from litellm.proxy.common_utils.codex_model_catalog import (
CODEX_BASE_INSTRUCTIONS_PATH,
@@ -25,8 +26,15 @@ from litellm.proxy.common_utils.codex_model_catalog import (
from litellm.types.llms.base_model import LiteLLMBaseModel
from .auth import cli_context_obj, context_secret_vault, get_stored_api_key, login
-from .claude_settings import ClaudeSettingsError, install_statusline_script
+from .claude_settings import (
+ ENV_KEY,
+ ClaudeSettingsError,
+ claude_settings_path,
+ install_statusline_script,
+ load_json_or_empty,
+)
from .cmd_quoting import quote_for_cmd
+from .config import claude_subscription_default
from .pi import (
LITELLM_PROXY_API_KEY_ENV,
PI_PROVIDER_NAME,
@@ -41,6 +49,8 @@ from .pi import (
ANTHROPIC_BASE_URL_ENV: Final = "ANTHROPIC_BASE_URL"
ANTHROPIC_AUTH_TOKEN_ENV: Final = "ANTHROPIC_AUTH_TOKEN"
ANTHROPIC_API_KEY_ENV: Final = "ANTHROPIC_API_KEY"
+ANTHROPIC_CUSTOM_HEADERS_ENV: Final = "ANTHROPIC_CUSTOM_HEADERS"
+LITELLM_KEY_HEADER: Final = "x-litellm-api-key"
ENABLE_TOOL_SEARCH_ENV: Final = "ENABLE_TOOL_SEARCH"
ENABLE_TOOL_SEARCH_VALUE: Final = "true"
ENABLE_GATEWAY_MODEL_DISCOVERY_ENV: Final = "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"
@@ -73,6 +83,7 @@ _INSTALL_DOCS: Final[dict[str, str]] = {
}
_HIDDEN_AGENTS: Final = frozenset({"pi"})
+_SUBSCRIPTION_AGENTS: Final = frozenset({"claude"})
CODEX_PROXY_PROVIDER: Final = "litellm"
CODEX_HOME_ENV: Final = "CODEX_HOME"
@@ -96,11 +107,24 @@ def agent_profile(command: str) -> tuple[str, frozenset[str]]:
return base, frozenset({PROFILE_ANTHROPIC, PROFILE_OPENAI})
+def _custom_headers_with_litellm_key(existing: str, api_key: str) -> str:
+ kept: Final = tuple(
+ line for line in existing.splitlines() if line.strip() and not _is_header_line(line, LITELLM_KEY_HEADER)
+ )
+ return "\n".join((*kept, f"{LITELLM_KEY_HEADER}: Bearer {api_key}"))
+
+
+def _is_header_line(line: str, name: str) -> bool:
+ return line.partition(":")[0].strip().lower() == name
+
+
def build_agent_env(
base_env: Mapping[str, str],
base_url: str,
api_key: str,
profiles: frozenset[str],
+ *,
+ subscription: bool = False,
) -> dict[str, str]:
"""Return a copy of base_env wired to route the agent through the proxy.
@@ -115,12 +139,22 @@ def build_agent_env(
proxy's /v1/models; likewise left alone when already set.
pi ignores both base URL variables and instead resolves $LITELLM_PROXY_API_KEY
from its synced models.json provider entry.
+ With subscription=True the Anthropic profile keeps Claude Code on its claude.ai login: the key
+ travels in the x-litellm-api-key header through ANTHROPIC_CUSTOM_HEADERS, and no
+ ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY is left in the environment, since either one makes
+ Claude Code stop using the subscription (and its connectors).
"""
env: Final = dict(base_env)
root: Final = base_url.rstrip("/")
if PROFILE_ANTHROPIC in profiles:
env[ANTHROPIC_BASE_URL_ENV] = root
- env[ANTHROPIC_AUTH_TOKEN_ENV] = api_key
+ if subscription:
+ env[ANTHROPIC_CUSTOM_HEADERS_ENV] = _custom_headers_with_litellm_key(
+ env.get(ANTHROPIC_CUSTOM_HEADERS_ENV, ""), api_key
+ )
+ env.pop(ANTHROPIC_AUTH_TOKEN_ENV, None)
+ else:
+ env[ANTHROPIC_AUTH_TOKEN_ENV] = api_key
env.pop(ANTHROPIC_API_KEY_ENV, None)
if ENABLE_TOOL_SEARCH_ENV not in env:
env[ENABLE_TOOL_SEARCH_ENV] = ENABLE_TOOL_SEARCH_VALUE
@@ -146,6 +180,130 @@ def codex_proxy_provider(base_url: str) -> Mapping[str, str | bool]:
)
+_SETTINGS_FLAG: Final = "--settings"
+_SUBSCRIPTION_SETTINGS_ENV: Final = MappingProxyType({ANTHROPIC_AUTH_TOKEN_ENV: "", ANTHROPIC_API_KEY_ENV: ""})
+_SETTINGS_OVERRIDE_ADAPTER: Final = TypeAdapter(dict[str, JsonValue])
+
+
+def _settings_flag_spans(args: Sequence[str]) -> tuple[tuple[int, int, str], ...]:
+ """(start, end, value) of every `--settings X` or `--settings=X` in args, in order."""
+ return tuple(
+ (i, i + 1, arg.partition("=")[2]) if arg != _SETTINGS_FLAG else (i, i + 2, "".join(args[i + 1 : i + 2]))
+ for i, arg in enumerate(args)
+ if arg == _SETTINGS_FLAG or arg.startswith(_SETTINGS_FLAG + "=")
+ )
+
+
+def _split_settings_flags(args: Sequence[str]) -> tuple[str | None, tuple[str, ...]]:
+ """The value of the last `--settings` the user passed (the one Claude Code would keep), and args without any."""
+ spans: Final = _settings_flag_spans(args)
+ covered: Final = frozenset(chain.from_iterable(range(start, end) for start, end, _ in spans))
+ rest: Final = tuple(arg for i, arg in enumerate(args) if i not in covered)
+ return (spans[-1][2] if spans else None), rest
+
+
+def _load_settings_override(value: str) -> Mapping[str, JsonValue]:
+ """The user's `--settings` value: inline JSON when it starts with `{`, else a settings file that must exist."""
+ if value.lstrip().startswith("{"):
+ try:
+ return _SETTINGS_OVERRIDE_ADAPTER.validate_json(value)
+ except ValidationError as e:
+ raise AgentRunError(f"`{_SETTINGS_FLAG}` is not a JSON object: {value}") from e
+ path: Final = Path(value).expanduser()
+ try:
+ return load_json_or_empty(path) if path.is_file() else _missing_settings_file(path)
+ except ClaudeSettingsError as e:
+ raise AgentRunError(str(e)) from e
+ except OSError as e:
+ raise AgentRunError(f"`{_SETTINGS_FLAG}` must be a settings file or a JSON object, got: {value}") from e
+
+
+def _missing_settings_file(path: Path) -> Mapping[str, JsonValue]:
+ raise AgentRunError(f"`{_SETTINGS_FLAG}` file not found: {path}")
+
+
+def _settings_env(settings: Mapping[str, JsonValue]) -> Mapping[str, JsonValue]:
+ env: Final = settings.get(ENV_KEY)
+ return env if isinstance(env, dict) else {}
+
+
+def _settings_json(base: Mapping[str, JsonValue], api_key: str, inherited_headers: str) -> str:
+ base_env: Final = _settings_env(base)
+ own_headers: Final = base_env.get(ANTHROPIC_CUSTOM_HEADERS_ENV)
+ headers: Final = _custom_headers_with_litellm_key(
+ own_headers if isinstance(own_headers, str) else inherited_headers, api_key
+ )
+ overlay: Final = {**base_env, **_SUBSCRIPTION_SETTINGS_ENV, ANTHROPIC_CUSTOM_HEADERS_ENV: headers}
+ return json.dumps({**base, ENV_KEY: overlay}, separators=(",", ":"))
+
+
+def _inherited_custom_headers(settings_files: Sequence[Mapping[str, JsonValue]], environ: Mapping[str, str]) -> str:
+ """The ANTHROPIC_CUSTOM_HEADERS Claude Code would apply without the overlay: the first settings file in
+ precedence order that sets it, else the process environment."""
+ from_files: Final = (_settings_env(settings).get(ANTHROPIC_CUSTOM_HEADERS_ENV) for settings in settings_files)
+ return next(
+ (value for value in from_files if isinstance(value, str)), environ.get(ANTHROPIC_CUSTOM_HEADERS_ENV, "")
+ )
+
+
+def claude_settings_files(
+ read_settings: Callable[[Path], Mapping[str, JsonValue]], environ: Mapping[str, str], project_dir: Path
+) -> tuple[Mapping[str, JsonValue], ...]:
+ """The settings files Claude Code merges below `--settings`, highest precedence first: project local, project,
+ then user. A missing file reads as empty, a malformed one is a clean CLI error."""
+ paths: Final = (
+ project_dir / ".claude" / "settings.local.json",
+ project_dir / ".claude" / "settings.json",
+ claude_settings_path(environ),
+ )
+ try:
+ return tuple(read_settings(path) for path in paths)
+ except ClaudeSettingsError as e:
+ raise AgentRunError(str(e)) from e
+
+
+OVERLAY_FILE_NAME: Final = "litellm-subscription-overlay.json"
+
+
+def write_settings_overlay(text: str, environ: Mapping[str, str]) -> Path:
+ """Write the overlay next to Claude Code's own settings.json (so under CLAUDE_CONFIG_DIR when set) and return
+ its path. One file per user, rewritten on every launch, mode 0600 whether or not it already existed. It carries
+ the LiteLLM key, which is why it is a private file and not an inline `--settings` argument that every local
+ user could read from the process list, and why it does not pile up in the temp dir."""
+ path: Final = claude_settings_path(environ).parent / OVERLAY_FILE_NAME
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd: Final = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ if os.name == "posix":
+ os.fchmod(fd, 0o600)
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(text)
+ return path
+
+
+def subscription_launch_args(
+ command: Sequence[str],
+ api_key: str,
+ environ: Mapping[str, str],
+ settings_files: Sequence[Mapping[str, JsonValue]],
+ write_overlay: Callable[[str, Mapping[str, str]], Path],
+) -> tuple[tuple[str, ...], tuple[str, ...]]:
+ """The `--settings` that keeps Claude Code on its claude.ai login, plus the user's remaining args.
+
+ Claude Code applies `env` from its settings files over the process environment, so a key that `lite up` or
+ `lite configure claude` left in ANTHROPIC_AUTH_TOKEN would land back in `Authorization`, and an
+ ANTHROPIC_CUSTOM_HEADERS there would drop the x-litellm-api-key header. The overlay blanks both credential
+ keys (read as unset for this session only) and carries the custom headers with the LiteLLM key appended,
+ taking the headers from the user's `--settings`, else the settings files in Claude Code's precedence order,
+ else the process environment. Any `--settings` the user passed is stripped and the last one (inline JSON or a
+ file, the one Claude Code would keep) is merged in, since Claude Code keeps only the last `--settings`.
+ """
+ inherited: Final = _inherited_custom_headers(settings_files, environ)
+ user_value, rest = _split_settings_flags(tuple(command[1:]))
+ base: Final[Mapping[str, JsonValue]] = _load_settings_override(user_value) if user_value is not None else {}
+ overlay: Final = write_overlay(_settings_json(base, api_key, inherited), environ)
+ return (_SETTINGS_FLAG, str(overlay)), rest
+
+
def _codex_proxy_args(base_url: str) -> list[str]:
"""Codex `-c` overrides that point it at the proxy.
@@ -570,6 +728,7 @@ def verify_proxy_key(
api_key: str,
*,
get: Callable[..., requests.Response] = requests.get,
+ key_header: str = "Authorization",
) -> None:
"""Probe the proxy with the key so bad creds fail here, not inside the agent.
@@ -578,7 +737,7 @@ def verify_proxy_key(
"""
url: Final = base_url.rstrip("/") + "/v1/models"
try:
- resp: Final = get(url, headers={"Authorization": f"Bearer {api_key}"}, timeout=10)
+ resp: Final = get(url, headers={key_header: f"Bearer {api_key}"}, timeout=10)
except requests.RequestException as e:
raise AgentRunError(
f"Could not reach the LiteLLM proxy at {base_url.rstrip('/')}: {e}. "
@@ -591,6 +750,15 @@ def verify_proxy_key(
)
+def verify_subscription_key(
+ base_url: str,
+ api_key: str,
+ *,
+ get: Callable[..., requests.Response] = requests.get,
+) -> None:
+ verify_proxy_key(base_url, api_key, get=get, key_header=LITELLM_KEY_HEADER)
+
+
_WINDOWS_SHIM_SUFFIXES: Final[frozenset[str]] = frozenset({".cmd", ".bat"})
_CMD_LINE_BREAKS: Final = ("\r", "\n")
@@ -686,14 +854,19 @@ def run_agent(
command: Sequence[str],
*,
skip_verify: bool = False,
+ subscription: bool = False,
base_env: Mapping[str, str] | None = None,
which: Callable[[str], str | None] = shutil.which,
verify: Callable[[str, str], None] = verify_proxy_key,
+ verify_subscription: Callable[[str, str], None] = verify_subscription_key,
sync_models: Callable[[str, Mapping[str, str], str, str, bool], ModelSyncResult] = agent_model_sync_env,
warn: Callable[[str], None] = _warn,
launcher: Callable[[str, Sequence[str], Mapping[str, str]], None] = _hand_off,
reattach_terminal: Callable[[], None] | None = None,
preparers: Mapping[str, _Preparer] = MappingProxyType(_PREPARERS),
+ read_settings: Callable[[Path], Mapping[str, JsonValue]] = load_json_or_empty,
+ write_overlay: Callable[[str, Mapping[str, str]], Path] = write_settings_overlay,
+ project_dir: Path | None = None,
) -> None:
"""Validate, wire the environment, and hand off to the agent.
@@ -713,7 +886,7 @@ def run_agent(
raise AgentRunError(f"Could not find `{command[0]}` on your PATH.{hint}")
if not skip_verify:
- verify(base_url, api_key)
+ (verify_subscription if subscription else verify)(base_url, api_key)
env_before_sync: Final = base_env if base_env is not None else os.environ
synced: Final = sync_models(binary, env_before_sync, base_url, api_key, skip_verify)
@@ -725,15 +898,28 @@ def run_agent(
env: Final = MappingProxyType(
{
- **build_agent_env(env_before_sync, base_url, api_key, profiles),
+ **build_agent_env(env_before_sync, base_url, api_key, profiles, subscription=subscription),
**(synced if isinstance(synced, Mapping) else _NO_EXTRA_ENV),
}
)
synced_args: Final = synced.args if isinstance(synced, ModelSyncArgs) else ()
extra_args: Final = (*agent_launch_args(command[0], base_url), *synced_args, *prepared_args)
+ settings_args, forwarded = (
+ subscription_launch_args(
+ command,
+ api_key,
+ env_before_sync,
+ claude_settings_files(
+ read_settings, env_before_sync, project_dir if project_dir is not None else Path.cwd()
+ ),
+ write_overlay,
+ )
+ if subscription and os.path.basename(command[0]) in _SUBSCRIPTION_AGENTS
+ else ((), tuple(command[1:]))
+ )
if reattach_terminal is not None:
reattach_terminal()
- launcher(binary, [command[0], *extra_args, *command[1:]], env)
+ launcher(binary, [command[0], *extra_args, *settings_args, *forwarded], env)
def _is_interactive() -> bool:
@@ -762,16 +948,27 @@ def resolve_api_key(ctx: click.Context) -> str:
_SKIP_VERIFY_HELP: Final = "Skip the pre-launch key check against the proxy."
+_SUBSCRIPTION_HELP: Final = (
+ "Keep using your claude.ai login (and its connectors). The LiteLLM key is sent in the "
+ "x-litellm-api-key header instead of replacing Claude Code's own credential. "
+ "Make it the default with `lite config set claude_subscription true`."
+)
-def _launch(ctx: click.Context, binary: str, args: Sequence[str], *, skip_verify: bool) -> None:
+def _launch(
+ ctx: click.Context, binary: str, args: Sequence[str], *, skip_verify: bool, subscription: bool | None = None
+) -> None:
ctx_obj: Final = cli_context_obj(ctx)
base_url: Final = ctx_obj["base_url"]
started_interactive: Final = _is_interactive()
api_key: Final = resolve_api_key(ctx)
display_name, _profiles = agent_profile(binary)
- click.echo(f"litellm: routing {display_name} through proxy at {base_url.rstrip('/')}")
+ use_subscription: Final = (
+ subscription if subscription is not None else binary in _SUBSCRIPTION_AGENTS and claude_subscription_default()
+ )
+ login_note: Final = " (keeping your claude.ai login)" if use_subscription else ""
+ click.echo(f"litellm: routing {display_name} through proxy at {base_url.rstrip('/')}{login_note}")
try:
run_agent(
@@ -779,12 +976,22 @@ def _launch(ctx: click.Context, binary: str, args: Sequence[str], *, skip_verify
api_key,
[binary, *args],
skip_verify=skip_verify,
+ subscription=use_subscription,
reattach_terminal=(_restore_controlling_terminal if started_interactive else None),
)
except AgentRunError as e:
raise click.ClickException(str(e))
+_Decorated: Final = TypeVar("_Decorated", bound=Callable[..., object] | click.Command)
+
+
+def _subscription_option(binary: str) -> Callable[[_Decorated], _Decorated]:
+ if binary not in _SUBSCRIPTION_AGENTS:
+ return lambda func: func
+ return click.option("--subscription/--no-subscription", default=None, help=_SUBSCRIPTION_HELP)
+
+
def _make_agent_command(binary: str, display_name: str) -> click.Command:
@click.command(
name=binary,
@@ -793,10 +1000,11 @@ def _make_agent_command(binary: str, display_name: str) -> click.Command:
hidden=binary in _HIDDEN_AGENTS,
)
@click.option("--skip-verify", is_flag=True, default=False, help=_SKIP_VERIFY_HELP)
+ @_subscription_option(binary)
@click.argument("args", nargs=-1, type=click.UNPROCESSED)
@click.pass_context
- def _command(ctx: click.Context, skip_verify: bool, args: Sequence[str]) -> None:
- _launch(ctx, binary, list(args), skip_verify=skip_verify)
+ def _command(ctx: click.Context, skip_verify: bool, args: Sequence[str], subscription: bool | None = None) -> None:
+ _launch(ctx, binary, list(args), skip_verify=skip_verify, subscription=subscription)
_command.help = (
f"Run {display_name} routed through your LiteLLM proxy.\n\n"
@@ -813,6 +1021,7 @@ def agent_commands() -> tuple[click.Command, ...]:
__all__ = [
+ "OVERLAY_FILE_NAME",
"AgentRunError",
"ListedModel",
"ModelSyncSkipped",
@@ -821,10 +1030,14 @@ __all__ = [
"agent_model_sync_env",
"agent_profile",
"build_agent_env",
+ "claude_settings_files",
"opencode_model_sync_env",
"opencode_provider_config",
"prepare_pi",
"resolve_api_key",
"run_agent",
+ "subscription_launch_args",
"verify_proxy_key",
+ "verify_subscription_key",
+ "write_settings_overlay",
]
diff --git a/litellm/proxy/client/cli/commands/auth.py b/litellm/proxy/client/cli/commands/auth.py
index ad54cab6460..b5302d1f561 100644
--- a/litellm/proxy/client/cli/commands/auth.py
+++ b/litellm/proxy/client/cli/commands/auth.py
@@ -52,6 +52,7 @@ from .claude_settings import (
refuse_while_owned,
settings_file_owners,
)
+from .config import pkce_default
from .pkce_login import (
Http,
PkceFailure,
@@ -884,17 +885,16 @@ def _pkce_login(base_url: str, config_claude: bool, vault: SecretVault) -> None:
),
)
@click.option(
- "--pkce",
- is_flag=True,
- default=False,
+ "--pkce/--no-pkce",
+ default=None,
help=(
"Sign in with OAuth authorization code + PKCE through your system browser (loopback redirect), "
"with a refresh token that renews the key automatically. Requires a proxy that serves "
- "/.well-known/litellm-cli-auth."
+ "/.well-known/litellm-cli-auth. Make it the default with `lite config set pkce true`."
),
)
@click.pass_context
-def login(ctx: click.Context, config_claude: bool, pkce: bool) -> None:
+def login(ctx: click.Context, config_claude: bool, pkce: bool | None) -> None:
"""Login to LiteLLM proxy using SSO authentication"""
from litellm.constants import LITELLM_CLI_SOURCE_IDENTIFIER
@@ -908,7 +908,7 @@ def login(ctx: click.Context, config_claude: bool, pkce: bool) -> None:
raise click.ClickException(f"Cannot configure Claude Code, so not logging in: {e}")
try:
- if pkce:
+ if pkce if pkce is not None else pkce_default():
_pkce_login(base_url, config_claude, context_secret_vault(ctx))
return
cli_sso_flow: Final = _start_cli_sso_flow(base_url=base_url)
diff --git a/litellm/proxy/client/cli/commands/config.py b/litellm/proxy/client/cli/commands/config.py
index de22251ea8c..539d88dce4a 100644
--- a/litellm/proxy/client/cli/commands/config.py
+++ b/litellm/proxy/client/cli/commands/config.py
@@ -13,6 +13,8 @@ from pydantic import TypeAdapter
from litellm.litellm_core_utils.private_json import ensure_private_dir, write_private_json
HIDDEN_COMMANDS_KEY: Final = "hidden_commands"
+CLAUDE_SUBSCRIPTION_KEY: Final = "claude_subscription"
+PKCE_KEY: Final = "pkce"
_config_adapter: Final[TypeAdapter[Mapping[str, str]]] = TypeAdapter(Mapping[str, str])
@@ -88,10 +90,46 @@ def _normalize_hidden_commands(value: str) -> str:
return ",".join(sorted(names))
+_BOOLEAN_WORDS: Final[Mapping[str, str]] = MappingProxyType(
+ {
+ "true": "true",
+ "on": "true",
+ "1": "true",
+ "yes": "true",
+ "false": "false",
+ "off": "false",
+ "0": "false",
+ "no": "false",
+ }
+)
+
+
+def _normalize_boolean(key: str) -> Callable[[str], str]:
+ def normalize(value: str) -> str:
+ normalized: Final = _BOOLEAN_WORDS.get(value.strip().lower())
+ if normalized is None:
+ raise click.UsageError(f"{key} must be true or false, e.g. `lite config set {key} true`")
+ return normalized
+
+ return normalize
+
+
+def claude_subscription_default() -> bool:
+ """Whether `lite claude` keeps the claude.ai login unless told otherwise."""
+ return get_config_value(CLAUDE_SUBSCRIPTION_KEY) == "true"
+
+
+def pkce_default() -> bool:
+ """Whether `lite login` signs in with browser PKCE unless told otherwise."""
+ return get_config_value(PKCE_KEY) == "true"
+
+
_NORMALIZERS: Final[Mapping[str, Callable[[str], str]]] = MappingProxyType(
{
"base_url": normalize_base_url,
HIDDEN_COMMANDS_KEY: _normalize_hidden_commands,
+ CLAUDE_SUBSCRIPTION_KEY: _normalize_boolean(CLAUDE_SUBSCRIPTION_KEY),
+ PKCE_KEY: _normalize_boolean(PKCE_KEY),
}
)
diff --git a/litellm/proxy/client/cli/commands/up.py b/litellm/proxy/client/cli/commands/up.py
index d1e966d6eae..4043761f255 100644
--- a/litellm/proxy/client/cli/commands/up.py
+++ b/litellm/proxy/client/cli/commands/up.py
@@ -30,6 +30,7 @@ from .claude_settings import (
merge_claude_settings,
write_claude_settings,
)
+from .config import pkce_default
class UpError(ClaudeSettingsError):
@@ -131,7 +132,7 @@ def ensure_fresh_login(ctx: click.Context) -> None:
if _usable_login(_key_resolved_on_the_way_in(ctx_obj, base_url, vault), vault):
return
- pkce: Final = _stored_login_is_pkce(vault)
+ pkce: Final = _stored_login_is_pkce(vault) or pkce_default()
login_command: Final = "lite login --pkce" if pkce else "lite login"
if not sys.stdin.isatty():
raise UpError(f"No fresh LiteLLM login found for this proxy. Run `{login_command}` first.")
diff --git a/tests/unit/proxy/client/cli/test_agents.py b/tests/unit/proxy/client/cli/test_agents.py
index 7be98521f8e..3481346076f 100644
--- a/tests/unit/proxy/client/cli/test_agents.py
+++ b/tests/unit/proxy/client/cli/test_agents.py
@@ -1,6 +1,7 @@
import inspect
import json
import os
+import stat
import subprocess
import sys
from pathlib import Path
@@ -27,7 +28,9 @@ from litellm.proxy.client.cli.commands.agents import (
opencode_model_sync_env,
run_agent,
verify_proxy_key,
+ verify_subscription_key,
)
+from litellm.proxy.client.cli.commands.claude_settings import ClaudeSettingsError
from litellm.proxy.client.cli.main import cli as lite
AGENTS_MODULE = "litellm.proxy.client.cli.commands.agents"
@@ -173,6 +176,19 @@ class _FakeJsonResponse:
return self._payload
+def _overlay_writer(tmp_path):
+ def write(text, environ):
+ target = tmp_path / "overlay.json"
+ target.write_text(text)
+ return target
+
+ return write
+
+
+def _overlay(args):
+ return json.loads(Path(args[2]).read_text())
+
+
class TestAgentProfile:
def test_claude_is_anthropic(self):
name, profiles = agent_profile("claude")
@@ -263,6 +279,55 @@ class TestBuildAgentEnv:
assert env["PATH"] == "/usr/bin"
assert base == {"PATH": "/usr/bin", "ANTHROPIC_API_KEY": "real-key"}
+ def test_subscription_sends_the_key_in_a_header_and_sets_no_credential(self):
+ env = build_agent_env({}, "http://localhost:4000/", "sk-key", frozenset({"anthropic"}), subscription=True)
+ assert env["ANTHROPIC_BASE_URL"] == "http://localhost:4000"
+ assert env["ANTHROPIC_CUSTOM_HEADERS"] == "x-litellm-api-key: Bearer sk-key"
+ assert "ANTHROPIC_AUTH_TOKEN" not in env
+ assert "ANTHROPIC_API_KEY" not in env
+
+ def test_subscription_clears_inherited_credentials(self):
+ base = {"ANTHROPIC_AUTH_TOKEN": "stale-token", "ANTHROPIC_API_KEY": "real-key"}
+ env = build_agent_env(base, "http://localhost:4000", "sk-key", frozenset({"anthropic"}), subscription=True)
+ assert "ANTHROPIC_AUTH_TOKEN" not in env
+ assert "ANTHROPIC_API_KEY" not in env
+ assert base == {"ANTHROPIC_AUTH_TOKEN": "stale-token", "ANTHROPIC_API_KEY": "real-key"}
+
+ def test_subscription_keeps_the_users_other_custom_headers(self):
+ env = build_agent_env(
+ {"ANTHROPIC_CUSTOM_HEADERS": "x-team: blue\n\nx-trace: 1\n"},
+ "http://localhost:4000",
+ "sk-key",
+ frozenset({"anthropic"}),
+ subscription=True,
+ )
+ assert env["ANTHROPIC_CUSTOM_HEADERS"].splitlines() == [
+ "x-team: blue",
+ "x-trace: 1",
+ "x-litellm-api-key: Bearer sk-key",
+ ]
+
+ def test_subscription_replaces_a_stale_litellm_key_header_whatever_its_case(self):
+ env = build_agent_env(
+ {"ANTHROPIC_CUSTOM_HEADERS": "X-LiteLLM-Api-Key: Bearer old\nx-team: blue"},
+ "http://localhost:4000",
+ "sk-new",
+ frozenset({"anthropic"}),
+ subscription=True,
+ )
+ assert env["ANTHROPIC_CUSTOM_HEADERS"].splitlines() == ["x-team: blue", "x-litellm-api-key: Bearer sk-new"]
+
+ def test_subscription_leaves_openai_agents_on_the_bearer_key(self):
+ env = build_agent_env({}, "http://localhost:4000", "sk-key", frozenset({"openai"}), subscription=True)
+ assert env["OPENAI_API_KEY"] == "sk-key"
+ assert "ANTHROPIC_CUSTOM_HEADERS" not in env
+
+ def test_default_mode_does_not_touch_custom_headers(self):
+ env = build_agent_env(
+ {"ANTHROPIC_CUSTOM_HEADERS": "x-team: blue"}, "http://localhost:4000", "sk-key", frozenset({"anthropic"})
+ )
+ assert env["ANTHROPIC_CUSTOM_HEADERS"] == "x-team: blue"
+
class TestAgentLaunchArgs:
def test_claude_and_opencode_get_no_extra_args(self):
@@ -330,6 +395,32 @@ class TestVerifyProxyKey:
get=lambda *a, **k: _FakeResponse(500),
)
+ def test_key_header_moves_the_bearer_off_authorization(self):
+ captured = {}
+
+ def fake_get(url, headers, timeout):
+ captured["headers"] = headers
+ return _FakeResponse(200)
+
+ verify_proxy_key("http://localhost:4000", "sk-key", get=fake_get, key_header="x-litellm-api-key")
+
+ assert captured["headers"] == {"x-litellm-api-key": "Bearer sk-key"}
+
+ def test_subscription_probe_sends_the_key_only_in_the_litellm_header(self):
+ captured = {}
+
+ def fake_get(url, headers, timeout):
+ captured["headers"] = headers
+ return _FakeResponse(200)
+
+ verify_subscription_key("http://localhost:4000", "sk-key", get=fake_get)
+
+ assert captured["headers"] == {"x-litellm-api-key": "Bearer sk-key"}
+
+ def test_subscription_probe_reports_a_rejected_key(self):
+ with pytest.raises(AgentRunError, match="rejected your key"):
+ verify_subscription_key("http://localhost:4000", "sk-key", get=lambda *a, **k: _FakeResponse(401))
+
class TestOpencodeModelSync:
@staticmethod
@@ -1195,6 +1286,327 @@ class TestRunAgent:
with pytest.raises(AgentRunError):
run_agent("http://localhost:4000", "sk-key", [])
+ def test_subscription_launch_probes_with_the_header_and_exports_it(self):
+ probed = []
+ launched = {}
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ ["claude"],
+ subscription=True,
+ base_env={"ANTHROPIC_AUTH_TOKEN": "stale"},
+ which=lambda name: "/usr/local/bin/claude",
+ verify=lambda *a: probed.append(("bearer", a)),
+ verify_subscription=lambda *a: probed.append(("header", a)),
+ launcher=lambda p, a, e: launched.update(env=dict(e)),
+ read_settings=lambda path: {},
+ )
+ assert probed == [("header", ("http://localhost:4000", "sk-key"))]
+ assert launched["env"]["ANTHROPIC_CUSTOM_HEADERS"] == "x-litellm-api-key: Bearer sk-key"
+ assert "ANTHROPIC_AUTH_TOKEN" not in launched["env"]
+
+ def test_subscription_launch_blanks_the_credentials_claude_code_would_load_from_settings_json(self, tmp_path):
+ launched = {}
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ ["claude", "--resume"],
+ subscription=True,
+ base_env={},
+ which=lambda name: "/usr/local/bin/claude",
+ verify_subscription=lambda *a: None,
+ launcher=lambda p, a, e: launched.update(args=tuple(a)),
+ read_settings=lambda path: {},
+ write_overlay=_overlay_writer(tmp_path),
+ )
+ assert launched["args"][:2] == ("claude", "--settings")
+ assert _overlay(launched["args"]) == {
+ "env": {
+ "ANTHROPIC_AUTH_TOKEN": "",
+ "ANTHROPIC_API_KEY": "",
+ "ANTHROPIC_CUSTOM_HEADERS": "x-litellm-api-key: Bearer sk-key",
+ }
+ }
+ assert launched["args"][3:] == ("--resume",)
+
+ def test_subscription_launch_keeps_the_key_out_of_argv_and_in_one_private_file_next_to_settings_json(
+ self, tmp_path
+ ):
+ config_dir = tmp_path / "cfg"
+ config_dir.mkdir()
+ stale = config_dir / "litellm-subscription-overlay.json"
+ stale.write_text('{"env": {"ANTHROPIC_CUSTOM_HEADERS": "x-litellm-api-key: Bearer old-key"}}')
+ stale.chmod(0o644)
+ launched = {}
+ for _ in range(2):
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ ["claude"],
+ subscription=True,
+ base_env={"CLAUDE_CONFIG_DIR": str(config_dir)},
+ which=lambda name: "/usr/local/bin/claude",
+ verify_subscription=lambda *a: None,
+ launcher=lambda p, a, e: launched.update(args=list(a)),
+ read_settings=lambda path: {},
+ )
+ assert "sk-key" not in " ".join(launched["args"])
+ assert Path(launched["args"][2]) == stale
+ assert sorted(path.name for path in config_dir.iterdir()) == ["litellm-subscription-overlay.json"]
+ assert json.loads(stale.read_text())["env"]["ANTHROPIC_CUSTOM_HEADERS"] == "x-litellm-api-key: Bearer sk-key"
+ if os.name == "posix":
+ assert stat.S_IMODE(stale.stat().st_mode) == 0o600
+
+ def test_subscription_launch_accepts_inline_settings_json_longer_than_a_file_name(self, tmp_path):
+ long_value = "a" * 400
+ launched = {}
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ ["claude", "--settings", json.dumps({"env": {"FOO": long_value}})],
+ subscription=True,
+ base_env={},
+ which=lambda name: "/usr/local/bin/claude",
+ verify_subscription=lambda *a: None,
+ launcher=lambda p, a, e: launched.update(args=list(a)),
+ read_settings=lambda path: {},
+ write_overlay=_overlay_writer(tmp_path),
+ )
+ assert _overlay(launched["args"])["env"]["FOO"] == long_value
+
+ def test_subscription_launch_reports_a_missing_settings_file_as_a_clean_cli_error(self, tmp_path):
+ with pytest.raises(AgentRunError, match="file not found"):
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ ["claude", "--settings", str(tmp_path / "nope.json")],
+ subscription=True,
+ base_env={},
+ which=lambda name: "/usr/local/bin/claude",
+ verify_subscription=lambda *a: None,
+ launcher=lambda *a: None,
+ read_settings=lambda path: {},
+ write_overlay=_overlay_writer(tmp_path),
+ )
+
+ def test_subscription_launch_reads_the_settings_files_claude_code_merges_below_the_flag(self, tmp_path):
+ seen = []
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ ["claude"],
+ subscription=True,
+ base_env={"CLAUDE_CONFIG_DIR": str(tmp_path / "cfg")},
+ which=lambda name: "/usr/local/bin/claude",
+ verify_subscription=lambda *a: None,
+ launcher=lambda *a: None,
+ read_settings=lambda path: seen.append(path) or {},
+ write_overlay=_overlay_writer(tmp_path),
+ project_dir=tmp_path / "repo",
+ )
+ assert seen == [
+ tmp_path / "repo" / ".claude" / "settings.local.json",
+ tmp_path / "repo" / ".claude" / "settings.json",
+ tmp_path / "cfg" / "settings.json",
+ ]
+
+ @pytest.mark.parametrize("separate_flag", [True, False])
+ def test_subscription_launch_merges_the_blanks_into_the_users_settings_flag(self, tmp_path, separate_flag):
+ settings_file = tmp_path / "mine.json"
+ settings_file.write_text('{"model": "opus", "env": {"ANTHROPIC_AUTH_TOKEN": "mine", "FOO": "bar"}}')
+ user_flag = ["--settings", str(settings_file)] if separate_flag else [f"--settings={settings_file}"]
+ launched = {}
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ ["claude", "--resume", *user_flag, "-p", "hi"],
+ subscription=True,
+ base_env={},
+ which=lambda name: "/usr/local/bin/claude",
+ verify_subscription=lambda *a: None,
+ launcher=lambda p, a, e: launched.update(args=list(a)),
+ read_settings=lambda path: {},
+ write_overlay=_overlay_writer(tmp_path),
+ )
+ assert launched["args"][:2] == ["claude", "--settings"]
+ assert _overlay(launched["args"]) == {
+ "model": "opus",
+ "env": {
+ "ANTHROPIC_AUTH_TOKEN": "",
+ "FOO": "bar",
+ "ANTHROPIC_API_KEY": "",
+ "ANTHROPIC_CUSTOM_HEADERS": "x-litellm-api-key: Bearer sk-key",
+ },
+ }
+ assert launched["args"][3:] == ["--resume", "-p", "hi"]
+
+ def test_subscription_launch_merges_the_blanks_into_inline_settings_json(self, tmp_path):
+ launched = {}
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ ["claude", "--settings", '{"env": {"ANTHROPIC_API_KEY": "mine"}, "theme": "dark"}'],
+ subscription=True,
+ base_env={},
+ which=lambda name: "/usr/local/bin/claude",
+ verify_subscription=lambda *a: None,
+ launcher=lambda p, a, e: launched.update(args=list(a)),
+ read_settings=lambda path: {},
+ write_overlay=_overlay_writer(tmp_path),
+ )
+ assert launched["args"][:2] == ["claude", "--settings"]
+ assert _overlay(launched["args"]) == {
+ "theme": "dark",
+ "env": {
+ "ANTHROPIC_API_KEY": "",
+ "ANTHROPIC_AUTH_TOKEN": "",
+ "ANTHROPIC_CUSTOM_HEADERS": "x-litellm-api-key: Bearer sk-key",
+ },
+ }
+ assert launched["args"][3:] == []
+
+ @pytest.mark.parametrize(
+ ("flag_headers", "local_headers", "project_headers", "user_headers", "expected"),
+ [
+ ("X-Flag: f", "X-Local: l", "X-Proj: p", "X-User: u", "X-Flag: f\nx-litellm-api-key: Bearer sk-key"),
+ (None, "X-Local: l", "X-Proj: p", "X-User: u", "X-Local: l\nx-litellm-api-key: Bearer sk-key"),
+ (
+ None,
+ None,
+ "X-Proj: p\nx-litellm-api-key: Bearer stale",
+ "X-User: u",
+ "X-Proj: p\nx-litellm-api-key: Bearer sk-key",
+ ),
+ (None, None, None, "X-User: u", "X-User: u\nx-litellm-api-key: Bearer sk-key"),
+ (None, None, None, None, "X-Proc: h\nx-litellm-api-key: Bearer sk-key"),
+ ],
+ )
+ def test_subscription_overlay_keeps_the_custom_headers_claude_code_would_apply_and_adds_the_key(
+ self, tmp_path, flag_headers, local_headers, project_headers, user_headers, expected
+ ):
+ """Claude Code applies settings `env` over the process env, in precedence order, so the overlay must too."""
+ user_flag = (
+ ["--settings", json.dumps({"env": {"ANTHROPIC_CUSTOM_HEADERS": flag_headers}})] if flag_headers else []
+ )
+ files = {
+ tmp_path / "repo" / ".claude" / "settings.local.json": local_headers,
+ tmp_path / "repo" / ".claude" / "settings.json": project_headers,
+ tmp_path / "cfg" / "settings.json": user_headers,
+ }
+ launched = {}
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ ["claude", *user_flag],
+ subscription=True,
+ base_env={"ANTHROPIC_CUSTOM_HEADERS": "X-Proc: h", "CLAUDE_CONFIG_DIR": str(tmp_path / "cfg")},
+ which=lambda name: "/usr/local/bin/claude",
+ verify_subscription=lambda *a: None,
+ launcher=lambda p, a, e: launched.update(args=list(a), env=dict(e)),
+ read_settings=lambda path: {"env": {"ANTHROPIC_CUSTOM_HEADERS": files[path]}} if files[path] else {},
+ write_overlay=_overlay_writer(tmp_path),
+ project_dir=tmp_path / "repo",
+ )
+ assert _overlay(launched["args"])["env"]["ANTHROPIC_CUSTOM_HEADERS"] == expected
+ assert launched["env"]["ANTHROPIC_CUSTOM_HEADERS"] == "X-Proc: h\nx-litellm-api-key: Bearer sk-key"
+
+ def test_subscription_launch_strips_every_settings_flag_and_merges_the_last_one_claude_code_would_keep(
+ self, tmp_path
+ ):
+ launched = {}
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ [
+ "claude",
+ "--settings",
+ '{"env": {"ANTHROPIC_AUTH_TOKEN": "first"}, "theme": "light"}',
+ "--resume",
+ '--settings={"theme": "dark"}',
+ ],
+ subscription=True,
+ base_env={},
+ which=lambda name: "/usr/local/bin/claude",
+ verify_subscription=lambda *a: None,
+ launcher=lambda p, a, e: launched.update(args=list(a)),
+ read_settings=lambda path: {},
+ write_overlay=_overlay_writer(tmp_path),
+ )
+ assert launched["args"][:2] == ["claude", "--settings"]
+ assert _overlay(launched["args"]) == {
+ "theme": "dark",
+ "env": {
+ "ANTHROPIC_AUTH_TOKEN": "",
+ "ANTHROPIC_API_KEY": "",
+ "ANTHROPIC_CUSTOM_HEADERS": "x-litellm-api-key: Bearer sk-key",
+ },
+ }
+ assert launched["args"][3:] == ["--resume"]
+
+ def test_subscription_launch_reports_a_malformed_settings_file_as_a_clean_cli_error(self):
+ def broken(path):
+ raise ClaudeSettingsError(f"{path} contains invalid JSON")
+
+ with pytest.raises(AgentRunError, match="contains invalid JSON"):
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ ["claude"],
+ subscription=True,
+ base_env={},
+ which=lambda name: "/usr/local/bin/claude",
+ verify_subscription=lambda *a: None,
+ launcher=lambda *a: None,
+ read_settings=broken,
+ )
+
+ def test_subscription_launch_rejects_a_settings_flag_that_is_not_a_json_object(self):
+ with pytest.raises(AgentRunError, match="is not a JSON object"):
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ ["claude", "--settings", '{"env": 1, '],
+ subscription=True,
+ base_env={},
+ which=lambda name: "/usr/local/bin/claude",
+ verify_subscription=lambda *a: None,
+ launcher=lambda *a: None,
+ read_settings=lambda path: {},
+ )
+
+ def test_default_launch_still_probes_with_the_bearer(self):
+ probed = []
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ ["claude"],
+ base_env={},
+ which=lambda name: "/usr/local/bin/claude",
+ verify=lambda *a: probed.append(("bearer", a)),
+ verify_subscription=lambda *a: probed.append(("header", a)),
+ launcher=lambda *a: None,
+ )
+ assert probed == [("bearer", ("http://localhost:4000", "sk-key"))]
+
+ def test_subscription_rejection_aborts_before_launch(self):
+ launched = []
+
+ def boom(*a):
+ raise AgentRunError("rejected")
+
+ with pytest.raises(AgentRunError):
+ run_agent(
+ "http://localhost:4000",
+ "sk-key",
+ ["claude"],
+ subscription=True,
+ base_env={},
+ which=lambda name: "/usr/local/bin/claude",
+ verify_subscription=boom,
+ launcher=lambda *a: launched.append(a),
+ )
+ assert launched == []
+
def test_reattach_terminal_runs_just_before_launch(self):
order = []
run_agent(
@@ -1552,6 +1964,71 @@ class TestAgentCommands:
assert captured["command"] == ["opencode"]
assert "routing OpenCode through proxy at http://localhost:4000" in result.output
+ def test_claude_subscription_flag_reaches_run_agent_and_is_not_forwarded(self):
+ captured = {}
+
+ def fake_run_agent(base_url, api_key, command, **kwargs):
+ captured["command"] = list(command)
+ captured["subscription"] = kwargs.get("subscription")
+
+ with patch(f"{AGENTS_MODULE}.run_agent", side_effect=fake_run_agent):
+ result = self.runner.invoke(
+ _agent_command("claude"),
+ ["--subscription", "--resume"],
+ obj={"base_url": "http://localhost:4000", "api_key": "sk-key"},
+ )
+
+ assert result.exit_code == 0, result.output
+ assert captured["subscription"] is True
+ assert captured["command"] == ["claude", "--resume"]
+ assert "keeping your claude.ai login" in result.output
+
+ @pytest.mark.parametrize(
+ ("configured", "args", "expected"),
+ [
+ (False, [], False),
+ (True, [], True),
+ (True, ["--no-subscription"], False),
+ (False, ["--subscription"], True),
+ ],
+ )
+ def test_subscription_comes_from_the_flag_else_the_saved_setting(self, configured, args, expected):
+ captured = {}
+ with (
+ patch(f"{AGENTS_MODULE}.claude_subscription_default", return_value=configured),
+ patch(
+ f"{AGENTS_MODULE}.run_agent",
+ side_effect=lambda b, k, c, **kw: captured.update(sub=kw.get("subscription"), command=list(c)),
+ ),
+ ):
+ result = self.runner.invoke(
+ _agent_command("claude"), args, obj={"base_url": "http://localhost:4000", "api_key": "sk-key"}
+ )
+ assert result.exit_code == 0, result.output
+ assert captured["sub"] is expected
+ assert captured["command"] == ["claude"]
+ assert ("keeping your claude.ai login" in result.output) is expected
+
+ @pytest.mark.parametrize("agent", ["codex", "opencode"])
+ def test_the_saved_claude_setting_does_not_change_other_agents(self, agent):
+ captured = {}
+ with (
+ patch(f"{AGENTS_MODULE}.claude_subscription_default", return_value=True),
+ patch(
+ f"{AGENTS_MODULE}.run_agent",
+ side_effect=lambda b, k, c, **kw: captured.update(sub=kw.get("subscription")),
+ ),
+ ):
+ result = self.runner.invoke(
+ _agent_command(agent), [], obj={"base_url": "http://localhost:4000", "api_key": "sk-key"}
+ )
+ assert result.exit_code == 0, result.output
+ assert captured["sub"] is False
+
+ @pytest.mark.parametrize("agent", ["codex", "opencode", "pi"])
+ def test_only_claude_offers_the_subscription_flag(self, agent):
+ assert "--subscription" not in {opt for param in _agent_command(agent).params for opt in param.opts}
+
def test_skip_verify_is_consumed_not_forwarded(self):
captured = {}
@@ -1676,7 +2153,9 @@ class TestPrepareCodex:
def test_registers_the_installed_script_as_a_session_scoped_stop_hook(self):
from litellm.proxy.client.cli.commands.agents import prepare_codex
- args = prepare_codex("http://localhost:4000", "sk-key", {}, install=lambda: "/py /home/me/.litellm/statusline.py")
+ args = prepare_codex(
+ "http://localhost:4000", "sk-key", {}, install=lambda: "/py /home/me/.litellm/statusline.py"
+ )
assert args == (
"-c",
'hooks.Stop=[{hooks=[{type="command",command="/py /home/me/.litellm/statusline.py"}]}]',
@@ -1697,11 +2176,20 @@ class TestPrepareCodex:
warnings = []
env = {"CODEX_HOME": str(tmp_path)}
- for body in ('[[hooks.Stop]]\nhooks = [{ type = "command", command = "mine" }]\n', 'hooks.Stop = []\n', "[hooks]\n"):
+ for body in (
+ '[[hooks.Stop]]\nhooks = [{ type = "command", command = "mine" }]\n',
+ "hooks.Stop = []\n",
+ "[hooks]\n",
+ ):
(tmp_path / "config.toml").write_text(body)
- assert prepare_codex("http://localhost:4000", "sk", env, install=lambda: "/py /s.py", warn=warnings.append) == ()
+ assert (
+ prepare_codex("http://localhost:4000", "sk", env, install=lambda: "/py /s.py", warn=warnings.append)
+ == ()
+ )
(tmp_path / "config.toml").write_text('model = "gpt-5.6-sol"\n[projects."/x"]\ntrust_level = "trusted"\n')
- assert prepare_codex("http://localhost:4000", "sk", env, install=lambda: "/py /s.py", warn=warnings.append) != ()
+ assert (
+ prepare_codex("http://localhost:4000", "sk", env, install=lambda: "/py /s.py", warn=warnings.append) != ()
+ )
assert len(warnings) == 3 and "already declares hooks" in warnings[0]
def test_a_config_that_cannot_be_read_or_decoded_still_lets_codex_launch(self, tmp_path):
diff --git a/tests/unit/proxy/client/cli/test_auth_commands.py b/tests/unit/proxy/client/cli/test_auth_commands.py
index 27edf9f3eb3..cb1fcba9df7 100644
--- a/tests/unit/proxy/client/cli/test_auth_commands.py
+++ b/tests/unit/proxy/client/cli/test_auth_commands.py
@@ -5,7 +5,6 @@ import time
from pathlib import Path
from unittest.mock import Mock, patch
-
import pytest
import responses
from click.testing import CliRunner
@@ -26,7 +25,6 @@ from litellm.litellm_core_utils.cli_token_utils import (
)
from litellm.proxy.client.cli import cli
from litellm.proxy.client.cli.commands import claude_settings as claude_settings_module
-from litellm.proxy.client.cli.commands.claude_settings import SettingsFileOwner
from litellm.proxy.client.cli.commands.auth import (
get_stored_api_key,
login,
@@ -34,6 +32,7 @@ from litellm.proxy.client.cli.commands.auth import (
print_token,
whoami,
)
+from litellm.proxy.client.cli.commands.claude_settings import SettingsFileOwner
@pytest.fixture
@@ -1718,6 +1717,35 @@ class TestPkceLoginCommand:
save.assert_called_once()
assert _FakeSession.instances[0].posts == []
+ @pytest.mark.parametrize(
+ ("saved", "args", "uses_pkce"),
+ [
+ ("true", [], True),
+ ("false", [], False),
+ (None, [], False),
+ ("true", ["--no-pkce"], False),
+ ("false", ["--pkce"], True),
+ ],
+ )
+ def test_login_uses_pkce_when_the_flag_or_the_saved_setting_says_so(self, saved, args, uses_pkce):
+ from litellm.proxy.client.cli.commands.config import save_config
+
+ if saved is not None:
+ save_config({"pkce": saved})
+ with (
+ patch("litellm.proxy.client.cli.commands.auth.run_pkce_login", return_value=_pkce_credential()),
+ patch(
+ "litellm.proxy.client.cli.commands.auth._start_cli_sso_flow",
+ side_effect=RuntimeError("classic sso flow"),
+ ),
+ patch("litellm.proxy.client.cli.commands.auth.save_token", return_value=SecretStored()),
+ patch("litellm.proxy.client.cli.interface.show_commands"),
+ ):
+ result = self.runner.invoke(login, args, obj={"base_url": PKCE_BASE_URL})
+
+ assert ("Login successful!" in result.output) is uses_pkce
+ assert ("Authentication failed: classic sso flow" in result.output) is (not uses_pkce)
+
def test_pkce_login_saves_the_refreshable_record_and_skips_the_sso_poll(self):
with (
patch("litellm.proxy.client.cli.commands.auth.run_pkce_login", return_value=_pkce_credential()) as run,
@@ -2050,7 +2078,10 @@ class TestGetStoredApiKeyRefresh:
@pytest.mark.parametrize(
"body, expected_detail",
[
- ('{"detail": "Too many CLI login attempts.", "retry": {"after": [30, null]}}', ": Too many CLI login attempts."),
+ (
+ '{"detail": "Too many CLI login attempts.", "retry": {"after": [30, null]}}',
+ ": Too many CLI login attempts.",
+ ),
('{"detail": 5}', ""),
('{"detail": ""}', ""),
('{"detail": {"message": "nested"}}', ""),
diff --git a/tests/unit/proxy/client/cli/test_config_commands.py b/tests/unit/proxy/client/cli/test_config_commands.py
index 611307635e0..2cd7a76ab95 100644
--- a/tests/unit/proxy/client/cli/test_config_commands.py
+++ b/tests/unit/proxy/client/cli/test_config_commands.py
@@ -6,16 +6,16 @@ from unittest.mock import patch
import pytest
from click.testing import CliRunner
-
-
+from litellm.litellm_core_utils.private_json import write_private_json
from litellm.proxy.client.cli import cli
from litellm.proxy.client.cli.commands.config import (
+ claude_subscription_default,
get_config_file_path,
get_config_value,
load_config,
+ pkce_default,
save_config,
)
-from litellm.litellm_core_utils.private_json import write_private_json
from litellm.proxy.client.cli.interface import show_commands
@@ -360,3 +360,51 @@ class TestWritePrivateJson:
assert not target.exists()
assert list(tmp_path.glob(".tmp-*")) == []
+
+
+class TestClaudeSubscriptionSetting:
+ @pytest.mark.parametrize("word", ["true", "TRUE", "on", "1", "yes"])
+ def test_truthy_words_are_stored_as_true(self, cli_runner, isolated_home, word):
+ result = cli_runner.invoke(cli, ["config", "set", "claude_subscription", word])
+
+ assert result.exit_code == 0, result.output
+ assert load_config()["claude_subscription"] == "true"
+ assert claude_subscription_default() is True
+
+ @pytest.mark.parametrize("word", ["false", "Off", "0", "no"])
+ def test_falsy_words_are_stored_as_false(self, cli_runner, isolated_home, word):
+ cli_runner.invoke(cli, ["config", "set", "claude_subscription", "true"])
+ result = cli_runner.invoke(cli, ["config", "set", "claude_subscription", word])
+
+ assert result.exit_code == 0, result.output
+ assert load_config()["claude_subscription"] == "false"
+ assert claude_subscription_default() is False
+
+ def test_anything_else_is_rejected_and_nothing_is_saved(self, cli_runner, isolated_home):
+ result = cli_runner.invoke(cli, ["config", "set", "claude_subscription", "maybe"])
+
+ assert result.exit_code != 0
+ assert "true or false" in result.output
+ assert "claude_subscription" not in load_config()
+
+ def test_unset_means_off(self, isolated_home):
+ assert claude_subscription_default() is False
+
+
+class TestPkceSetting:
+ @pytest.mark.parametrize(("word", "expected"), [("true", True), ("on", True), ("false", False), ("off", False)])
+ def test_the_saved_value_drives_the_default(self, cli_runner, isolated_home, word, expected):
+ result = cli_runner.invoke(cli, ["config", "set", "pkce", word])
+
+ assert result.exit_code == 0, result.output
+ assert pkce_default() is expected
+
+ def test_a_non_boolean_is_rejected_and_nothing_is_saved(self, cli_runner, isolated_home):
+ result = cli_runner.invoke(cli, ["config", "set", "pkce", "sometimes"])
+
+ assert result.exit_code != 0
+ assert "true or false" in result.output
+ assert "pkce" not in load_config()
+
+ def test_unset_means_off(self, isolated_home):
+ assert pkce_default() is False
diff --git a/tests/unit/proxy/client/cli/test_up_commands.py b/tests/unit/proxy/client/cli/test_up_commands.py
index ddd54dd1374..5c2e726315b 100644
--- a/tests/unit/proxy/client/cli/test_up_commands.py
+++ b/tests/unit/proxy/client/cli/test_up_commands.py
@@ -15,8 +15,8 @@ from litellm.proxy.client.cli.commands.claude_settings import ClaudeSettingsErro
from litellm.proxy.client.cli.commands.up import (
BackupRecord,
UpError,
- ensure_fresh_login,
down,
+ ensure_fresh_login,
load_json_or_empty,
merge_claude_settings,
read_backup,
@@ -372,6 +372,30 @@ class TestEnsureFreshLogin:
assert login_calls == [("http://proxy-a:4000", True)]
+ def test_logs_in_with_pkce_when_the_saved_pkce_default_is_on(self, monkeypatch):
+ """`lite config set pkce true` is honoured by the login `lite up` starts, not only by `lite login`."""
+ monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: True)
+ store = _FakeTokenStore(monkeypatch, {"key": "sk-a", "base_url": "http://proxy-a:4000"}, {})
+ monkeypatch.setattr(up_module, "is_cli_token_fresh", lambda token_data: True)
+ monkeypatch.setattr(up_module, "pkce_default", lambda: True)
+ login_calls = _capture_login(
+ monkeypatch,
+ on_login=lambda: store.log_in(_pkce_record("http://proxy-b:4000", seconds_left=86_400), "sk-pkce-fresh"),
+ )
+
+ ensure_fresh_login(_make_ctx("http://proxy-b:4000"))
+
+ assert login_calls == [("http://proxy-b:4000", True)]
+
+ def test_names_the_pkce_login_in_the_non_interactive_error_when_the_saved_pkce_default_is_on(self, monkeypatch):
+ monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: False)
+ _FakeTokenStore(monkeypatch, {"key": "sk-a", "base_url": "http://proxy-a:4000"}, {})
+ monkeypatch.setattr(up_module, "is_cli_token_fresh", lambda token_data: True)
+ monkeypatch.setattr(up_module, "pkce_default", lambda: True)
+
+ with pytest.raises(UpError, match="Run `lite login --pkce` first"):
+ ensure_fresh_login(_make_ctx("http://proxy-b:4000"))
+
def test_names_the_pkce_login_in_the_non_interactive_error_for_a_pkce_credential(self, monkeypatch):
monkeypatch.setattr(up_module.sys.stdin, "isatty", lambda: False)
_FakeTokenStore(monkeypatch, _pkce_record("http://proxy-a:4000", seconds_left=-10), {})