Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(studio): use managed root key for trusted Feishu connections (#5500)
Lusen Dong9179d5bab0ae
diff --git a/bot/tests/test_studio.py b/bot/tests/test_studio.pyindex 3cdf7f676..0fff7cb84 100644--- a/bot/tests/test_studio.py+++ b/bot/tests/test_studio.py@@ -1,6 +1,7 @@"""Studio channel persistence, isolation and real delivery boundaries."""import asyncio+import hashlibimport timefrom types import SimpleNamespacefrom unittest.mock import AsyncMock@@ -9,7 +10,8 @@ import pytestfrom fastapi import HTTPExceptionfrom vikingbot.bus.events import OutboundMessagefrom vikingbot.bus.queue import MessageBus-from vikingbot.config.schema import FeishuChannelConfig, SessionKey+from vikingbot.channels.manager import ChannelManager+from vikingbot.config.schema import Config, FeishuChannelConfig, OpenVikingConfig, SessionKeyfrom vikingbot.studio.providers.feishu.channel import StudioFeishuChannelfrom vikingbot.studio.providers.registry import get_providerfrom vikingbot.studio.service import StudioService@@ -80,6 +82,7 @@ def channel(tmp_path):FeishuChannelConfig(app_id="cli_test", bot_name="Old name"),MessageBus(),record=record(),+ openviking_connection=record()["identity"],store=StudioStore(tmp_path / "s.db"),)result._running = True@@ -131,6 +134,88 @@ async def test_group_identity_and_peer_are_separate_from_installer(channel):assert channel.store.history("connection")[0]["sender"] == "Alice"+ "auth_mode,legacy_key", [("trusted", False), ("trusted", True), ("api_key", True)]+)+async def test_trusted_identity_uses_server_root_key_only_at_runtime(+ tmp_path, auth_mode, legacy_key+):+ item = record()+ item["identity"] = {+ "account_id": "a",+ "user_id": "group-user",+ "role": "user",+ }+ if legacy_key:+ item["identity"].update(api_key_type="user", api_key="private")+ config = Config(storage_workspace=str(tmp_path))+ config.ov_server.set_effective_auth_mode(auth_mode)+ config.ov_server.api_key = "runtime-root-key"+ service = StudioService(config, ChannelManager(MessageBus()))+ service.store.save(item)++ # Restart through the production installation path, including old saved connections.+ service = StudioService(config, ChannelManager(MessageBus()))+ runtime = service.runtime(item)+ runtime._running = True+ await runtime._handle_message("sender", "group", "hello", metadata={"message_id": "m1"})+ event = await runtime.bus.consume_inbound()++ connection = event.openviking_connection+ assert connection["account_id"] == "a"+ assert connection["user_id"] == "group-user"+ assert connection["role"] == "user"+ assert connection["api_key_type"] == ("root" if auth_mode == "trusted" else "user")+ assert connection["api_key"] == ("runtime-root-key" if auth_mode == "trusted" else "private")+ assert runtime.record["identity"] == item["identity"]+ assert service.store.connections("a")[0]["identity"] == item["identity"]+ assert b"runtime-root-key" not in (config.bot_data_path / "studio.sqlite3").read_bytes()+++async def test_trusted_image_read_uses_runtime_root_key_and_chat_peer(tmp_path, monkeypatch):+ from vikingbot.openviking_mount.ov_server import VikingClient++ item = record()+ item["identity"] = {+ "account_id": "a",+ "user_id": "group-user",+ "role": "user",+ "api_key_type": "root",+ }+ config = Config(storage_workspace=str(tmp_path))+ config.ov_server.set_effective_auth_mode("trusted")+ config.ov_server.api_key = "runtime-root-key"+ service = StudioService(config, ChannelManager(MessageBus()))+ runtime = service.install(item)+ image = b"\x89PNG\r\n\x1a\nfake-png"+ client = SimpleNamespace(+ stat=AsyncMock(return_value={"size": len(image)}),+ download_bytes=AsyncMock(return_value=image),+ close=AsyncMock(),+ )+ create = AsyncMock(return_value=client)+ monkeypatch.setattr(VikingClient, "create", create)+ message = OutboundMessage(+ SessionKey(type="feishu", channel_id="cli_test", chat_id="group"),+ "answer",+ )++ assert await runtime._download_viking_image("viking://resources/image.png", message) == image+ create.assert_awaited_once_with(+ connection={+ "account_id": "a",+ "user_id": "group-user",+ "role": "user",+ "api_key_type": "root",+ "api_key": "runtime-root-key",+ },+ actor_peer_id="feishu-" + hashlib.sha256(b"group").hexdigest()[:24],+ config=runtime._bot_config,+ )+ client.close.assert_awaited_once()+ assert "api_key" not in item["identity"]++async def test_pause_drops_new_inbound_messages(channel):await channel.stop()await channel._handle_message("sender", "group", "hello")@@ -283,7 +368,9 @@ async def test_reply_settings_persist_apply_immediately_and_keep_revision_guard(provider = get_provider({"type": "feishu"})service = StudioService(SimpleNamespace(- bot_data_path=tmp_path, channels=[{"type": "feishu", "app_id": "cli_test"}]+ bot_data_path=tmp_path,+ channels=[{"type": "feishu", "app_id": "cli_test"}],+ ov_server=OpenVikingConfig(),),SimpleNamespace(channels={provider.runtime_key(record()): channel}),)@@ -321,7 +408,7 @@ async def test_reply_settings_persist_apply_immediately_and_keep_revision_guard(service.manager.bus = Noneservice.manager.add_channel = lambda channel: Noneservice.config.workspace_path = tmp_path- provider.install(service, persisted)+ service.install(persisted)assert captured == [False]@@ -342,7 +429,12 @@ async def test_recreated_connection_isolates_sessions_and_rejects_old_replies(monkeypatch.setattr(FeishuChannel, "send", delivery)bus = MessageBus()service = StudioService(- SimpleNamespace(bot_data_path=tmp_path, workspace_path=tmp_path, channels=[]),+ SimpleNamespace(+ bot_data_path=tmp_path,+ workspace_path=tmp_path,+ channels=[],+ ov_server=OpenVikingConfig(),+ ),ChannelManager(bus),)diff --git a/bot/vikingbot/studio/providers/feishu/channel.py b/bot/vikingbot/studio/providers/feishu/channel.pyindex a7b7ed880..76b8ce133 100644--- a/bot/vikingbot/studio/providers/feishu/channel.py+++ b/bot/vikingbot/studio/providers/feishu/channel.py@@ -17,9 +17,10 @@ def now():class StudioFeishuChannel(FeishuChannel):- def __init__(self, config, bus, *, record, store, **kwargs):+ def __init__(self, config, bus, *, record, store, openviking_connection, **kwargs):super().__init__(config, bus, **kwargs)self.record = record+ self.openviking_connection = openviking_connectionself._session_prefix = f"studio:{record['id']}:"self.store = storeself.verification = None@@ -100,7 +101,6 @@ class StudioFeishuChannel(FeishuChannel):)if not inserted:return- connection = dict(self.record["identity"])# Partition peer memory by group/topic, never by the installing administrator.peer = "feishu-" + hashlib.sha256(chat_id.encode()).hexdigest()[:24]await self.bus.publish_inbound(@@ -113,7 +113,7 @@ class StudioFeishuChannel(FeishuChannel):need_reply=need_reply,media=media or [],metadata=metadata,- openviking_connection=connection,+ openviking_connection=self.openviking_connection,))@@ -163,7 +163,7 @@ class StudioFeishuChannel(FeishuChannel):raise ValueError("Missing message scope")peer = "feishu-" + hashlib.sha256(msg.session_key.chat_id.encode()).hexdigest()[:24]client = await VikingClient.create(- connection=self.record["identity"],+ connection=self.openviking_connection,actor_peer_id=peer,config=self._bot_config,)diff --git a/bot/vikingbot/studio/providers/feishu/provider.py b/bot/vikingbot/studio/providers/feishu/provider.pyindex 4fd3f42e2..282c41544 100644--- a/bot/vikingbot/studio/providers/feishu/provider.py+++ b/bot/vikingbot/studio/providers/feishu/provider.py@@ -71,7 +71,7 @@ class FeishuProvider:key: record.get(key) for key in ("app_id", "step", "setup_mode", "onboarding_id")} | {"settings": self.validate_settings(record.get("settings", {}))}- def install(self, service, record):+ def install(self, service, record, *, openviking_connection):from vikingbot.studio.providers.feishu.channel import StudioFeishuChannelchannel_config = FeishuChannelConfig(@@ -88,6 +88,7 @@ class FeishuProvider:channel_config,service.manager.bus,record=record,+ openviking_connection=openviking_connection,store=service.store,workspace_path=service.config.workspace_path,bot_config=service.config,diff --git a/bot/vikingbot/studio/service.py b/bot/vikingbot/studio/service.pyindex fcede4d34..2359f1efe 100644--- a/bot/vikingbot/studio/service.py+++ b/bot/vikingbot/studio/service.py@@ -50,7 +50,13 @@ class StudioService:)def install(self, record):- return get_provider(record).install(self, record)+ connection = dict(record["identity"])+ server = self.config.ov_server+ if server.effective_auth_mode == "trusted":+ # Credentials belong to the runtime, not the persisted connection.+ connection["api_key_type"] = "root"+ connection["api_key"] = server.api_key+ return get_provider(record).install(self, record, openviking_connection=connection)async def create(self, account, body, identity):provider = get_provider(body)diff --git a/openviking/server/account_user_keys.py b/openviking/server/account_user_keys.pyindex 01f4c2f1f..a91d4c09a 100644--- a/openviking/server/account_user_keys.py+++ b/openviking/server/account_user_keys.py@@ -1,21 +1,21 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""Server-side lookup of a selected user's stored key; Studio only ever sends the user ID."""+"""Server-side user selection with optional stored-key requirements."""from fastapi import HTTPException-async def list_users_with_keys(registry, account_id, role=None):- """Users of the account, refreshed from the key store, with readable keys exposed."""+async def list_account_users(registry, account_id, role=None, *, expose_key=True):+ """Refresh account users, exposing readable keys only when requested."""await registry.refresh_account_users_from_store(account_id)- return registry.get_users(account_id, limit=None, role_filter=role, expose_key=True)+ return registry.get_users(account_id, limit=None, role_filter=role, expose_key=expose_key)-def pick_user_with_key(rows, user_id, *, missing, unreadable):- """The row of `user_id`. With key hashing only a hash is stored, so there is no key to use."""+def pick_account_user(rows, user_id, *, missing, unreadable, require_key=True):+ """Select a user, requiring a readable key unless trusted transport supplies its own."""row = next((row for row in rows if row["user_id"] == user_id), None)if row is None:raise HTTPException(400, missing)- if not row.get("api_key"):+ if require_key and not row.get("api_key"):raise HTTPException(409, unreadable)return rowdiff --git a/openviking/server/routers/bot_studio.py b/openviking/server/routers/bot_studio.pyindex fee8a3844..656394df4 100644--- a/openviking/server/routers/bot_studio.py+++ b/openviking/server/routers/bot_studio.py@@ -8,8 +8,8 @@ import httpxfrom fastapi import APIRouter, Depends, HTTPException, Query, Requestfrom pydantic import BaseModel, ConfigDict, Field, model_validator-from openviking.server.account_user_keys import list_users_with_keys, pick_user_with_key-from openviking.server.auth import get_api_key_manager_or_raise, get_request_context+from openviking.server.account_user_keys import list_account_users, pick_account_user+from openviking.server.auth import _auth_mode, get_api_key_manager_or_raise, get_request_contextfrom openviking.server.config import get_server_url_from_server_datafrom openviking.server.identity import RequestContext, Rolefrom openviking.server.routers import bot@@ -119,27 +119,31 @@ async def connections(ctx: RequestContext = Depends(manager)):return await dispatch(ctx, "list")-async def account_users(request, ctx):+async def account_users(request, ctx, *, expose_key=True):registry = get_api_key_manager_or_raise(request)- return await list_users_with_keys(registry, ctx.account_id, role="user")+ return await list_account_users(registry, ctx.account_id, role="user", expose_key=expose_key)async def selected_identity(request, ctx, user_id):- row = pick_user_with_key(- await account_users(request, ctx),+ trusted = _auth_mode(request) == "trusted"+ row = pick_account_user(+ await account_users(request, ctx, expose_key=not trusted),user_id,missing="Select an ordinary user in the current account",unreadable="This user's credential cannot be bound automatically",+ require_key=not trusted,)- return {+ identity = {"account_id": ctx.account_id,"user_id": row["user_id"],"role": "user",- "api_key_type": "user",- "api_key": row["api_key"],+ "api_key_type": "root" if trusted else "user","agent_id": "vikingbot","server_url": get_server_url_from_server_data(getattr(request.app.state, "config", None)),}+ if not trusted:+ identity["api_key"] = row["api_key"]+ return identity@router.post(ACCOUNT_BOT + "/connections")diff --git a/openviking/server/routers/gateway.py b/openviking/server/routers/gateway.pyindex 504fb70b8..b7574672b 100644--- a/openviking/server/routers/gateway.py+++ b/openviking/server/routers/gateway.py@@ -9,7 +9,7 @@ import httpxfrom fastapi import APIRouter, Depends, HTTPException, Requestfrom fastapi.responses import Response-from openviking.server.account_user_keys import list_users_with_keys, pick_user_with_key+from openviking.server.account_user_keys import list_account_users, pick_account_userfrom openviking.server.auth import (get_api_key_manager_or_raise,get_request_context,@@ -40,8 +40,8 @@ async def bind_selected_user(request: Request, ctx: RequestContext, body: bytes)raise HTTPException(400, "Root cannot choose a user; paste the user's OpenViking key instead")- rows = await list_users_with_keys(get_api_key_manager_or_raise(request), ctx.account_id)- row = pick_user_with_key(+ rows = await list_account_users(get_api_key_manager_or_raise(request), ctx.account_id)+ row = pick_account_user([row for row in rows if row["role"] in KEY_USER_ROLES],value.pop("user_id"),missing="Unknown OpenViking user in this account",diff --git a/tests/server/test_bot_studio.py b/tests/server/test_bot_studio.pyindex 90c27b131..f270dd8f4 100644--- a/tests/server/test_bot_studio.py+++ b/tests/server/test_bot_studio.py@@ -1,7 +1,7 @@"""The browser cannot elevate or cross accounts through Studio management."""from types import SimpleNamespace-from unittest.mock import AsyncMock+from unittest.mock import AsyncMock, Mockimport httpximport pytest@@ -115,8 +115,9 @@ async def test_reused_admin_users_support_safe_credential_status(][email protected]("auth_mode", ["api_key", "trusted"])@pytest.mark.parametrize("user_id,accepted", [("missing", False), ("root", False), ("bot", True)])-async def test_selection_uses_current_account_registry(monkeypatch, user_id, accepted):+async def test_selection_uses_current_account_registry(monkeypatch, user_id, accepted, auth_mode):from fastapi import HTTPExceptionregistry = SimpleNamespace(@@ -127,11 +128,17 @@ async def test_selection_uses_current_account_registry(monkeypatch, user_id, accmonkeypatch.setattr(bot_studio, "get_server_url_from_server_data", lambda config: "http://localhost")- request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=None)))+ config = SimpleNamespace(get_effective_auth_mode=lambda: auth_mode)+ request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=config)))ctx = SimpleNamespace(account_id="a")if accepted:result = await bot_studio.selected_identity(request, ctx, user_id)- assert result["api_key"] == "internal-key"+ if auth_mode == "trusted":+ assert "api_key" not in result+ assert result["api_key_type"] == "root"+ else:+ assert result["api_key"] == "internal-key"+ assert result["api_key_type"] == "user"assert result["role"] == "user"assert result["account_id"] == "a"else:@@ -150,10 +157,39 @@ async def test_hashed_key_is_not_treated_as_a_usable_credential(monkeypatch):AsyncMock(return_value=[{"user_id": "bot", "key_prefix": "prefix"}]),)with pytest.raises(HTTPException) as exc:- await bot_studio.selected_identity(None, SimpleNamespace(account_id="a"), "bot")+ request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=None)))+ await bot_studio.selected_identity(request, SimpleNamespace(account_id="a"), "bot")assert exc.value.status_code == 409+async def test_trusted_selection_uses_keyless_root_identity(monkeypatch):+ registry = SimpleNamespace(+ refresh_account_users_from_store=AsyncMock(),+ get_users=Mock(return_value=[{"user_id": "bot", "key_prefix": "prefix"}]),+ )+ monkeypatch.setattr(bot_studio, "get_api_key_manager_or_raise", lambda request: registry)+ monkeypatch.setattr(+ bot_studio, "get_server_url_from_server_data", lambda config: "http://localhost"+ )+ config = SimpleNamespace(get_effective_auth_mode=lambda: "trusted")+ request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=config)))+ ctx = SimpleNamespace(account_id="a")++ identity = await bot_studio.selected_identity(request, ctx, "bot")++ registry.get_users.assert_called_once_with(+ "a", limit=None, role_filter="user", expose_key=False+ )+ assert identity == {+ "account_id": "a",+ "user_id": "bot",+ "role": "user",+ "api_key_type": "root",+ "agent_id": "vikingbot",+ "server_url": "http://localhost",+ }++async def test_onboarding_identity_is_selected_server_side(app, monkeypatch):app.dependency_overrides[get_request_context] = lambda: RequestContext(user=UserIdentifier("a", "root"), role=Role.ROOT