Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(claude): use bearer auth for relay keys (#1180)

Call White8ffc57e373a4
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index feaec7e8e..531b97140 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -104,7 +104,12 @@ def _pick_probe_response_excerpt(stdout_text: str) -> str:
return candidate
-def _classify_test_failure(stdout: str, stderr: str) -> str:
+def _classify_test_failure(
+ stdout: str,
+ stderr: str,
+ *,
+ auth_mode: str | None = None,
+) -> str:
"""Map a backend CLI's failure output to a specific UI error code.
The Settings → Backends "Test connection" panel routes the returned
@@ -122,7 +127,10 @@ def _classify_test_failure(stdout: str, stderr: str) -> str:
return "cli_failed"
if "not logged in" in text:
- return "not_logged_in"
+ # Gateways sometimes use this wording when an API credential was
+ # missing or arrived in the wrong header. In explicit API-key mode,
+ # sending the user through OAuth login is the wrong recovery path.
+ return "invalid_credentials" if auth_mode == "api_key" else "not_logged_in"
# Auth-side rejections (key wrong / revoked / rejected).
auth_needles = (
@@ -2242,6 +2250,7 @@ class AgentAuthService:
binary = self._get_cli_binary(backend)
prompt = "Hi"
probe_cwd = None
+ auth_mode = None
if backend == "claude":
probe_cwd = self._resolve_claude_probe_cwd()
# ``-p`` switches Claude Code into non-interactive print mode
@@ -2335,7 +2344,11 @@ class AgentAuthService:
pass
stdout_partial = (partial_stdout or b"").decode("utf-8", errors="replace").strip()
stderr_partial = (partial_stderr or b"").decode("utf-8", errors="replace").strip()
- classified = _classify_test_failure(stdout_partial, stderr_partial)
+ classified = _classify_test_failure(
+ stdout_partial,
+ stderr_partial,
+ auth_mode=auth_mode,
+ )
result = {
"ok": False,
"error": classified if classified != "cli_failed" else "timed_out",
@@ -2354,7 +2367,11 @@ class AgentAuthService:
stderr_text = (stderr or b"").decode("utf-8", errors="replace").strip()
if process.returncode != 0:
- classified = _classify_test_failure(stdout_text, stderr_text)
+ classified = _classify_test_failure(
+ stdout_text,
+ stderr_text,
+ auth_mode=auth_mode,
+ )
return {
"ok": False,
"error": classified,
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index dbaaede30..bc384d7a1 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -162,5 +162,12 @@ scenarios:
layer: scenario
backend: codex
test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_legacy_codex_thread_rebinds_once_after_api_key_endpoint_switch
+ - id: AUTH-SETUP-904
+ name: Claude relay key uses bearer auth after switching from OAuth
+ status: covered
+ kind: historical_regression
+ layer: scenario
+ backend: claude
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_claude_oauth_to_relay_key_reaches_next_turn_with_bearer_auth
next_priority:
- AUTH-SETUP-301
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index f1da014af..966b3aff5 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -1,24 +1,35 @@
import asyncio
+import json
+import os
import sys
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, patch
ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT))
from config.v2_config import (
+ AgentsConfig,
ModelHubModelConfig,
ModelHubSourceConfig,
ModelHubSourceStateConfig,
+ RuntimeConfig,
+ SlackConfig,
+ V2Config,
)
from core.handlers.model_hub.service import ModelHubError
from modules.agents.codex.agent import CodexAgent
from tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, FakeProcess
from tests.scenario_harness.core import ScenarioExpect, ScenarioRunner, ScenarioStep
from tests.scenario_harness.model_hub_native_oauth import NativeOAuthScenarioHarness
+from vibe.api import get_claude_auth, save_claude_auth
+from vibe.claude_config import (
+ build_claude_subprocess_env,
+ materialize_claude_subprocess_env,
+)
class _FakeNextTurnRuntime:
@@ -62,6 +73,122 @@ class _CodexProviderBindingSessions:
class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
+ async def test_claude_oauth_to_relay_key_reaches_next_turn_with_bearer_auth(self):
+ """Scenario: AUTH-SETUP-904"""
+ state_dir = tempfile.TemporaryDirectory()
+ self.addCleanup(state_dir.cleanup)
+ home = Path(state_dir.name)
+ claude_home = home / ".claude"
+ claude_home.mkdir()
+ credentials_path = claude_home / ".credentials.json"
+ credentials_path.write_text(
+ json.dumps(
+ {
+ "claudeAiOauth": {
+ "accessToken": "oauth-access",
+ "refreshToken": "oauth-refresh",
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ harness = AuthSetupScenarioHarness()
+ runner = ScenarioRunner(harness)
+ cleanup_calls = []
+ restart_calls = []
+
+ def clear_oauth(service=None):
+ cleanup_calls.append(service)
+ credentials_path.unlink()
+ return {"ok": True}
+
+ def restart_backend(name, *, metadata=None):
+ restart_calls.append((name, metadata))
+ return {"ok": True, "message": "refreshed"}
+
+ def capture_oauth_state(current):
+ current.before_switch = get_claude_auth()
+
+ def save_relay_key(current):
+ current.save_result = save_claude_auth(
+ {
+ "auth_mode": "api_key",
+ "api_key": "relay-secret",
+ "base_url": "https://relay.example/v1",
+ }
+ )
+
+ def capture_next_turn_env(current):
+ claude_config = V2Config.load().agents.claude
+ current.next_turn_env = materialize_claude_subprocess_env(
+ build_claude_subprocess_env(claude_config),
+ base_env={"PATH": "/usr/bin"},
+ )
+
+ with (
+ patch.dict(
+ os.environ,
+ {
+ "AVIBE_HOME": str(home / ".avibe"),
+ "CLAUDE_CONFIG_DIR": str(claude_home),
+ },
+ ),
+ patch("vibe.api._get_oauth_service", return_value=harness.service),
+ patch(
+ "vibe.api._clear_claude_oauth_credentials_after_api_key_save",
+ side_effect=clear_oauth,
+ ),
+ patch("vibe.api.restart_backend", side_effect=restart_backend),
+ patch("vibe.api._read_claude_cli_oauth_signed_in", return_value=None),
+ ):
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ )
+ config.agents.claude.auth_mode = "oauth"
+ config.agents.claude.auth_mode_set = True
+ config.save()
+
+ await runner.run(
+ ScenarioStep("confirm_oauth_is_active", capture_oauth_state),
+ ScenarioStep("save_relay_key", save_relay_key),
+ ScenarioStep("launch_next_turn", capture_next_turn_env),
+ )
+
+ self.assertEqual(harness.before_switch["active_auth_mode"], "oauth")
+ self.assertEqual(harness.save_result["active_auth_mode"], "api_key")
+ self.assertEqual(
+ harness.save_result["settings_env_key_var"],
+ "ANTHROPIC_AUTH_TOKEN",
+ )
+ self.assertNotIn("relay-secret", json.dumps(harness.save_result))
+ self.assertEqual(
+ harness.next_turn_env["ANTHROPIC_AUTH_TOKEN"],
+ "relay-secret",
+ )
+ self.assertEqual(
+ harness.next_turn_env["ANTHROPIC_BASE_URL"],
+ "https://relay.example/v1",
+ )
+ self.assertNotIn("ANTHROPIC_API_KEY", harness.next_turn_env)
+ self.assertEqual(cleanup_calls, [harness.service])
+ self.assertEqual(
+ restart_calls,
+ [
+ (
+ "claude",
+ {"reason": "save_claude_auth", "source": "ui_api"},
+ )
+ ],
+ )
+ ScenarioExpect.step_history(
+ runner,
+ ["confirm_oauth_is_active", "save_relay_key", "launch_next_turn"],
+ )
+
async def test_legacy_codex_thread_rebinds_once_after_api_key_endpoint_switch(self):
"""Scenario: AUTH-SETUP-903"""
agent = object.__new__(CodexAgent)
diff --git a/tests/test_settings_disk_fallback.py b/tests/test_settings_disk_fallback.py
index dd05c926f..88e3e666c 100644
--- a/tests/test_settings_disk_fallback.py
+++ b/tests/test_settings_disk_fallback.py
@@ -509,7 +509,7 @@ def test_claude_settings_json_takes_precedence_over_legacy_v2config(
assert state["settings_conflict"] is False
-def test_save_claude_auth_writes_settings_json_and_clears_v2_secret(
+def test_save_claude_relay_auth_writes_bearer_token_and_clears_v2_secret(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
claude_restart_calls: list[dict],
@@ -548,8 +548,10 @@ def test_save_claude_auth_writes_settings_json_and_clears_v2_secret(
)
assert result["ok"] is True
+ assert result["settings_env_key_var"] == "ANTHROPIC_AUTH_TOKEN"
settings = json.loads((tmp_path / ".claude" / "settings.json").read_text())
- assert settings["env"]["ANTHROPIC_API_KEY"] == "sk-ant-new-settings-key"
+ assert settings["env"]["ANTHROPIC_AUTH_TOKEN"] == "sk-ant-new-settings-key"
+ assert "ANTHROPIC_API_KEY" not in settings["env"]
assert settings["env"]["ANTHROPIC_BASE_URL"] == "https://relay.example.invalid"
_assert_claude_managed_env(settings["env"])
@@ -616,7 +618,8 @@ def test_save_claude_auth_reports_partial_when_oauth_cleanup_fails(
assert result["warning"] == "oauth_cleanup_failed"
assert "logout" in result["detail"]
settings = json.loads((tmp_path / ".claude" / "settings.json").read_text())
- assert settings["env"]["ANTHROPIC_API_KEY"] == "sk-ant-new-settings-key"
+ assert settings["env"]["ANTHROPIC_AUTH_TOKEN"] == "sk-ant-new-settings-key"
+ assert "ANTHROPIC_API_KEY" not in settings["env"]
assert settings["env"]["ANTHROPIC_BASE_URL"] == "https://relay.example.invalid"
@@ -669,11 +672,119 @@ def test_save_claude_auth_restores_pending_oauth_backup_before_writing_new_key(
assert result["ok"] is True
assert cleanup_calls and cleanup_calls[0] is not None
assert read_claude_settings_env() == {
- "ANTHROPIC_API_KEY": "sk-new-key",
+ "ANTHROPIC_AUTH_TOKEN": "sk-new-key",
"ANTHROPIC_BASE_URL": "https://new-relay.example.invalid",
}
+ "base_url",
+ [None, "https://api.anthropic.com", "https://api.anthropic.com/"],
+)
+def test_save_claude_direct_auth_writes_anthropic_api_key(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ claude_restart_calls: list[dict],
+ base_url: str | None,
+) -> None:
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
+ monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
+ monkeypatch.setattr(
+ "vibe.api._clear_claude_oauth_credentials_after_api_key_save",
+ lambda _service=None: {"ok": True},
+ )
+
+ from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config
+ from vibe.api import save_claude_auth
+
+ V2Config(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ ).save()
+
+ result = save_claude_auth(
+ {
+ "auth_mode": "api_key",
+ "api_key": "sk-ant-direct-key",
+ "base_url": base_url,
+ }
+ )
+
+ assert result["ok"] is True
+ assert result["settings_env_key_var"] == "ANTHROPIC_API_KEY"
+ settings = json.loads((tmp_path / ".claude" / "settings.json").read_text())
+ assert settings["env"]["ANTHROPIC_API_KEY"] == "sk-ant-direct-key"
+ assert "ANTHROPIC_AUTH_TOKEN" not in settings["env"]
+ if base_url:
+ assert settings["env"]["ANTHROPIC_BASE_URL"] == base_url
+ else:
+ assert "ANTHROPIC_BASE_URL" not in settings["env"]
+ assert claude_restart_calls == [
+ {
+ "name": "claude",
+ "metadata": {"reason": "save_claude_auth", "source": "ui_api"},
+ }
+ ]
+
+
+def test_save_claude_base_url_update_switches_header_without_retyping_key(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ claude_restart_calls: list[dict],
+) -> None:
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
+ monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
+ monkeypatch.setattr(
+ "vibe.api._clear_claude_oauth_credentials_after_api_key_save",
+ lambda _service=None: {"ok": True},
+ )
+ _write_claude_settings(tmp_path, {"ANTHROPIC_API_KEY": "sk-ant-preserved"})
+
+ from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config
+ from vibe.api import save_claude_auth
+ from vibe.claude_config import read_claude_settings_env
+
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ )
+ config.agents.claude.auth_mode = "api_key"
+ config.agents.claude.auth_mode_set = True
+ config.save()
+
+ relay_result = save_claude_auth(
+ {
+ "auth_mode": "api_key",
+ "base_url": "https://relay.example.invalid",
+ }
+ )
+
+ assert relay_result["settings_env_key_var"] == "ANTHROPIC_AUTH_TOKEN"
+ assert read_claude_settings_env() == {
+ "ANTHROPIC_AUTH_TOKEN": "sk-ant-preserved",
+ "ANTHROPIC_BASE_URL": "https://relay.example.invalid",
+ }
+
+ direct_result = save_claude_auth(
+ {
+ "auth_mode": "api_key",
+ "base_url": None,
+ }
+ )
+
+ assert direct_result["settings_env_key_var"] == "ANTHROPIC_API_KEY"
+ assert read_claude_settings_env() == {"ANTHROPIC_API_KEY": "sk-ant-preserved"}
+ assert len(claude_restart_calls) == 2
+
+
def test_save_claude_auth_keeps_settings_token_over_legacy_v2_key(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/test_test_failure_classifier.py b/tests/test_test_failure_classifier.py
index 3a98cd9b8..675562bc9 100644
--- a/tests/test_test_failure_classifier.py
+++ b/tests/test_test_failure_classifier.py
@@ -49,6 +49,10 @@ def test_classifier_combines_stdout_and_stderr() -> None:
assert _classify_test_failure("Error: invalid api key", "") == "invalid_credentials"
+def test_classifier_treats_not_logged_in_as_api_key_failure_in_api_key_mode() -> None:
+ assert _classify_test_failure("Not logged in - Please run /login", "", auth_mode="api_key") == "invalid_credentials"
+
+
def test_classifier_is_case_insensitive() -> None:
assert _classify_test_failure("", "401 UNAUTHORIZED") == "invalid_credentials"
assert _classify_test_failure("", "Connection Refused") == "endpoint_unreachable"
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index f708b9b77..9118a3297 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -1550,6 +1550,7 @@ def test_test_web_auth_not_logged_in_has_specific_error_code(
return _FakeProcess()
monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
+ monkeypatch.setattr(_Backend, "auth_mode", "oauth", raising=False)
result = _run(service.test_web_auth("claude"))
@@ -1557,3 +1558,26 @@ def test_test_web_auth_not_logged_in_has_specific_error_code(
assert result["error"] == "not_logged_in"
assert result["exit_code"] == 1
assert "Not logged in" in (result.get("detail") or "")
+
+
+def test_test_web_auth_api_key_mode_does_not_prompt_for_oauth_login(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ class _FakeProcess:
+ returncode = 1
+
+ async def communicate(self):
+ return (b"Not logged in \xc2\xb7 Please run /login", b"")
+
+ async def _spawn(*_args, **_kwargs):
+ return _FakeProcess()
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
+ monkeypatch.setattr(_Backend, "auth_mode", "api_key", raising=False)
+ monkeypatch.setattr(_Backend, "auth_mode_set", True, raising=False)
+
+ result = _run(service.test_web_auth("claude"))
+
+ assert result["ok"] is False
+ assert result["error"] == "invalid_credentials"
+ assert result["exit_code"] == 1
diff --git a/vibe/api.py b/vibe/api.py
index 26ab1deec..7c620bac1 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -8359,6 +8359,18 @@ def restart_backend(name: str, *, metadata: Optional[dict[str, Any]] = None) ->
_VALID_AUTH_MODES = {"oauth", "api_key"}
+_ANTHROPIC_API_HOST = "api.anthropic.com"
+
+
+def _claude_uses_bearer_auth(base_url: str | None) -> bool:
+ """Return whether Claude should send the credential as a bearer token."""
+ if not base_url:
+ return False
+ try:
+ hostname = urllib.parse.urlsplit(base_url).hostname
+ except ValueError:
+ return True
+ return (hostname or "").lower() != _ANTHROPIC_API_HOST
def _mask_api_key(api_key: str | None) -> str | None:
@@ -9199,6 +9211,11 @@ def save_claude_auth(payload: dict) -> dict:
stored key" — same UX promise as Codex — so callers can PATCH the
base URL without re-typing the secret. An empty key with no stored
fallback is rejected.
+
+ Claude Code uses different headers for direct Anthropic API keys and
+ gateway credentials. Direct keys are stored as ``ANTHROPIC_API_KEY``
+ (``x-api-key``), while a non-Anthropic Base URL stores the same user-facing
+ credential as ``ANTHROPIC_AUTH_TOKEN`` (``Authorization: Bearer``).
"""
if not isinstance(payload, dict):
return {"ok": False, "message": "Payload must be an object"}
@@ -9280,11 +9297,21 @@ def save_claude_auth(payload: dict) -> dict:
from vibe.claude_config import apply_claude_auth
try:
+ credential = api_key or settings_auth_token
+ use_auth_token = _claude_uses_bearer_auth(effective_base_url)
apply_claude_auth(
auth_mode=auth_mode,
- api_key=api_key if auth_mode == "api_key" else None,
+ api_key=(
+ credential
+ if auth_mode == "api_key" and not use_auth_token
+ else None
+ ),
base_url=effective_base_url if auth_mode == "api_key" else None,
- auth_token=settings_auth_token if auth_mode == "api_key" else None,
+ auth_token=(
+ credential
+ if auth_mode == "api_key" and use_auth_token
+ else None
+ ),
)
except ValueError as exc:
return {"ok": False, "message": str(exc)}
diff --git a/vibe/claude_config.py b/vibe/claude_config.py
index 5b4d67f9b..466c53fc5 100644
--- a/vibe/claude_config.py
+++ b/vibe/claude_config.py
@@ -292,11 +292,12 @@ def apply_claude_auth(
) -> Dict[str, Any]:
"""Persist Claude auth into ``settings.json``.
- ``api_key`` mode writes ``env.ANTHROPIC_API_KEY`` and removes
- ``ANTHROPIC_AUTH_TOKEN`` so header semantics cannot conflict. ``oauth``
- mode removes all Anthropic credential/base-url overrides from the env
- block and leaves Claude's OAuth credentials untouched. Both modes upsert
- Avibe's non-secret Claude Code env defaults.
+ In ``api_key`` mode the caller selects exactly one credential variable:
+ ``ANTHROPIC_API_KEY`` for Anthropic's direct ``x-api-key`` header or
+ ``ANTHROPIC_AUTH_TOKEN`` for a gateway's ``Authorization: Bearer`` header.
+ ``oauth`` mode removes all Anthropic credential/base-url overrides from the
+ env block and leaves Claude's OAuth credentials untouched. Both modes
+ upsert Avibe's non-secret Claude Code env defaults.
"""
if auth_mode not in {"oauth", "api_key"}:
raise ValueError(f"Unsupported claude auth_mode: {auth_mode!r}")
@@ -423,13 +424,10 @@ def read_claude_api_key_from_settings(home: Path | None = None) -> Optional[str]
blanking the live key.
Restricted to ``ANTHROPIC_API_KEY`` on purpose. ``ANTHROPIC_AUTH_TOKEN``
- is the bearer-token relay variant — Claude Code applies it from
- ``settings.json`` directly, and our ``api_key`` field always injects
- ``ANTHROPIC_API_KEY`` at launch (see ``session_handler``). Pulling an
- auth-token value into V2Config.api_key would silently switch the
- header semantics on the next save and break bearer-token gateways.
- Bearer-token users should rely on the existing settings.json path or
- re-enter their key into the form.
+ is the bearer-token relay variant and must not be returned through a helper
+ whose callers assume ``x-api-key`` semantics. ``save_claude_auth`` reads
+ the bearer token separately, preserves the credential, and chooses the
+ header from the effective Base URL.
"""
env_block = read_claude_settings_env(home)
return env_block.get("ANTHROPIC_API_KEY")