Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(bot): Simplify the bot auth check, support ov's trusted auth_mode. (#2769)

DuTao027e21bb7e22
diff --git a/bot/README.md b/bot/README.md
index 9a5cb2aac..3676de79b 100644
--- a/bot/README.md
+++ b/bot/README.md
@@ -145,18 +145,19 @@ Config file: `~/.openviking/ov.conf` (custom path can be set via environment var
### OpenViking Server Configuration
The bot will connect to the remote OpenViking server. Please start the OpenViking Server before use. By default, the OpenViking server information configured in `ov.conf` is used
- OpenViking default startup address is 127.0.0.1:1933
-- New bot deployments should use an OpenViking User API key. `root_api_key` is kept only as a deprecated compatibility field for legacy root-key setups.
+- Vikingbot follows OpenViking `server.auth_mode`: `api_key` mode uses an OpenViking User API key; `trusted` mode uses `server.root_api_key` plus trusted identity headers; `dev` mode is local-only.
- OpenViking Server configuration example
```json
{
"server": {
+ "auth_mode": "api_key",
"host": "127.0.0.1",
- "port": 1933
+ "port": 1933,
+ "root_api_key": "<your-openviking-root-api-key>"
},
"bot": {
"ov_server": {
- "api_key": "<your-openviking-user-api-key>",
- "api_key_type": "user"
+ "api_key": "<your-openviking-user-api-key>"
}
}
}
@@ -183,11 +184,11 @@ All configurations are under the `bot` field in `ov.conf`, with default values f
- If not configured, the OpenViking server information configured in `ov.conf` is used by default
- If you use a remote OpenViking Server, configure the target service URL and API key here
- `server_url`: OpenViking server base URL, for example `https://api.vikingdb.cn-beijing.volces.com/openviking` or `http://localhost:1933`.
- - `api_key`: API key used by the bot when calling the OpenViking server. New configs should set this to an OpenViking User key.
- - `root_api_key`: Deprecated compatibility field for legacy root-key deployments; do not use it for new configs.
+ - `api_key`: API key used by the bot when calling the OpenViking server. In `api_key` mode, this must be an OpenViking User key; in trusted mode with `api_key_type: "root"`, this is the OpenViking root key.
+ - `root_api_key`: Deprecated compatibility field. Do not use it for new configs; use `api_key` with `api_key_type: "root"` for trusted mode.
- `account_id`: Defaults to `default`, which is the OpenViking account ID. All users under the same OpenViking account share resources.
- - `api_key_type`: Optional `root` or `user`, default `user`. `user` uses the OpenViking User-key flow and maps the bot sender to a peer under that User. `root` is only for legacy root-key fanout behavior and should be configured explicitly if still needed.
- Legacy configs that put a root key in `api_key` must add `api_key_type: "root"` or move the key to `root_api_key`; otherwise `api_key` is interpreted as a User key.
+ - `api_key_type`: Defaults from the OpenViking `server.auth_mode` in the same `ov.conf`: `user` for `api_key`/`dev`, `root` for `trusted`. Manual configuration is usually unnecessary.
+ If `bot.ov_server` points to another OpenViking server and that server uses trusted auth, set `api_key_type: "root"` and provide its root key in `api_key`.
- exp_write_tools: Optional list of tool names that trigger experience-memory injection before the call (self-evolving agent memory loop, see #2007). Defaults to `["write_file", "edit_file"]`. This only controls the bot-side injection trigger; stored experience generation is governed by OpenViking memory extraction and the active session `memory_policy.memory_types` whitelist.
- `recall_exp_first_round_only`: Optional. When `true`, `ContextBuilder._build_user_memory` skips per-turn user/agent experience recall and injects experiences only once on the first user turn. Defaults to `false`.
- Per-turn user/peer memory recall uses type-quota search by default. `profile.md` is injected through the profile path and does not occupy auto-search candidates.
@@ -221,8 +222,7 @@ All configurations are under the `bot` field in `ov.conf`, with default values f
"ov_server": {
"server_url": "https://api.vikingdb.cn-beijing.volces.com/openviking",
"api_key": "<your-openviking-user-api-key>",
- "account_id": "default",
- "api_key_type": "user"
+ "account_id": "default"
},
"channels": [
{
diff --git a/bot/README_CN.md b/bot/README_CN.md
index c7843311b..79641870b 100644
--- a/bot/README_CN.md
+++ b/bot/README_CN.md
@@ -147,18 +147,19 @@ ov chat --no-format
### OpenViking Server 配置
bot 将连接到远程 OpenViking Server,使用前请先启动 OpenViking Server。默认使用 `ov.conf` 中配置的 OpenViking Server 信息。
- OpenViking 默认启动地址为 `127.0.0.1:1933`
-- 新部署的 bot 默认应使用 OpenViking User API key。`root_api_key` 仅作为旧 root-key 部署的废弃兼容字段保留。
+- Vikingbot 会跟随 OpenViking 的 `server.auth_mode`:`api_key` 模式使用 OpenViking User API key;`trusted` 模式使用 `server.root_api_key` 加 trusted identity headers;`dev` 模式仅用于本地。
- OpenViking Server 配置示例
```json
{
"server": {
+ "auth_mode": "api_key",
"host": "127.0.0.1",
- "port": 1933
+ "port": 1933,
+ "root_api_key": "<your-openviking-root-api-key>"
},
"bot": {
"ov_server": {
- "api_key": "<your-openviking-user-api-key>",
- "api_key_type": "user"
+ "api_key": "<your-openviking-user-api-key>"
}
}
}
@@ -185,11 +186,11 @@ bot 将连接到远程 OpenViking Server,使用前请先启动 OpenViking Serv
- 若不配置,默认使用 `ov.conf` 中配置的 OpenViking Server 信息。
- 如果你使用远端 OpenViking Server,可以在这里配置目标服务地址和 API Key。
- `server_url`:OpenViking Server 基础地址,例如 `https://api.vikingdb.cn-beijing.volces.com/openviking` 或 `http://localhost:1933`。
- - `api_key`:bot 调用 OpenViking Server 时使用的 API Key。新配置应填写 OpenViking User key。
- - `root_api_key`:旧 root-key 部署的废弃兼容字段;新配置不要再使用。
+ - `api_key`:bot 调用 OpenViking Server 使用的 API Key。`api_key` 模式下必须是 OpenViking User key;trusted 模式且 `api_key_type: "root"` 时,该字段就是 OpenViking root key。
+ - `root_api_key`:废弃兼容字段。新配置不要使用;trusted 模式请使用 `api_key` 配合 `api_key_type: "root"`。
- `account_id`:默认值为 `default`,即 OpenViking 的账号 ID。同一 OpenViking account 下的所有 user 共享 resources。
- - `api_key_type`:可选 `root` 或 `user`,默认 `user`。`user` 使用 OpenViking User-key 流程,并将 bot sender 映射为该 User 下的 peer。`root` 仅用于旧 root-key fanout 行为,如仍需使用必须显式配置。
- 旧配置如果把 root key 填在 `api_key`,需要补充 `api_key_type: "root"`,或迁移到 `root_api_key`;否则 `api_key` 会按 User key 解释。
+ - `api_key_type`:默认由同一个 `ov.conf` 中的 OpenViking `server.auth_mode` 推导:`api_key`/`dev` 为 `user`,`trusted` 为 `root`。通常无需手动配置。
+ 如果 `bot.ov_server` 指向另一套 OpenViking Server,且对方使用 trusted 鉴权,请设置 `api_key_type: "root"`,并在 `api_key` 中提供对方的 root key。
- `exp_write_tools`:可选,触发经验记忆注入的工具名列表(自演化 agent memory 循环,详见 #2007)。默认 `["write_file", "edit_file"]`。该配置只控制 bot 侧注入触发时机;已存储 experience 的生成由 OpenViking 记忆抽取和当前 session 的 `memory_policy.memory_types` 白名单控制。
- `recall_exp_first_round_only`:可选。为 `true` 时,`ContextBuilder._build_user_memory` 跳过每轮 user/agent 经验召回,仅在首个 user turn 注入一次经验。默认 `false`。
- 每轮 user/peer 记忆召回默认使用 type-quota 检索。`profile.md` 仍由 profile 链路单独注入,不占自动检索候选位。
@@ -223,8 +224,7 @@ bot 将连接到远程 OpenViking Server,使用前请先启动 OpenViking Serv
"ov_server": {
"server_url": "https://api.vikingdb.cn-beijing.volces.com/openviking",
"api_key": "<your-openviking-user-api-key>",
- "account_id": "default",
- "api_key_type": "user"
+ "account_id": "default"
},
"channels": [
{
diff --git a/bot/tests/test_gateway_startup_security.py b/bot/tests/test_gateway_startup_security.py
index 89fbca03e..0203a7963 100644
--- a/bot/tests/test_gateway_startup_security.py
+++ b/bot/tests/test_gateway_startup_security.py
@@ -11,6 +11,10 @@ class _AbortCalled(RuntimeError):
pass
+class _ValidateCalled(RuntimeError):
+ pass
+
+
def test_gateway_rejects_non_localhost_without_token(monkeypatch):
config = SimpleNamespace(
gateway=SimpleNamespace(host="0.0.0.0", port=18790, token=""),
@@ -43,3 +47,43 @@ def test_gateway_allows_non_localhost_with_token(monkeypatch):
with pytest.raises(_AbortCalled):
commands.gateway(port=None, host=None, verbose=False, config_path=None)
+
+
+def test_gateway_validates_openviking_auth_before_start(monkeypatch):
+ config = SimpleNamespace(
+ gateway=SimpleNamespace(host="127.0.0.1", port=18790, token=""),
+ )
+
+ monkeypatch.setattr(commands, "ensure_config", lambda _: config)
+
+ def _validate(_config):
+ raise _ValidateCalled
+
+ monkeypatch.setattr(commands, "validate_openviking_auth", _validate)
+
+ with pytest.raises(_ValidateCalled):
+ commands.gateway(port=None, host=None, verbose=False, config_path=None)
+
+
+def test_chat_validates_openviking_auth_before_start(monkeypatch):
+ config = SimpleNamespace()
+
+ monkeypatch.setattr(commands, "ensure_config", lambda _: config)
+
+ def _validate(_config):
+ raise _ValidateCalled
+
+ monkeypatch.setattr(commands, "validate_openviking_auth", _validate)
+
+ with pytest.raises(_ValidateCalled):
+ commands.chat(
+ message="hello",
+ session_id=None,
+ markdown=True,
+ logs=False,
+ eval=False,
+ config_path=None,
+ sender=None,
+ memory_peer=None,
+ memory_user=None,
+ )
diff --git a/bot/tests/test_openviking_api_key_type.py b/bot/tests/test_openviking_api_key_type.py
index 32055f600..26c63b729 100644
--- a/bot/tests/test_openviking_api_key_type.py
+++ b/bot/tests/test_openviking_api_key_type.py
@@ -42,6 +42,7 @@ class _DummyHTTPClient:
self.kwargs = kwargs
self.find_calls = []
self.ls_calls = []
+ self.read_calls = []
self.closed = False
_DummyHTTPClient.instances.append(self)
@@ -73,15 +74,6 @@ class _DummyHTTPClient:
async def admin_list_accounts(self):
return []
- async def admin_list_users(self, _account_id):
- return []
-
- async def admin_register_user(self, account_id, user_id, role="user"):
- return {"account_id": account_id, "user_id": user_id, "role": role}
-
- async def admin_remove_user(self, _account_id, _user_id):
- return None
-
async def find(self, *_args, **_kwargs):
self.find_calls.append((_args, _kwargs))
return []
@@ -93,6 +85,18 @@ class _DummyHTTPClient:
async def search(self, *_args, **_kwargs):
return {"memories": [], "resources": [], "skills": []}
+ async def abstract(self, uri):
+ self.read_calls.append(("abstract", uri))
+ return ""
+
+ async def overview(self, uri):
+ self.read_calls.append(("overview", uri))
+ return ""
+
+ async def read(self, uri):
+ self.read_calls.append(("read", uri))
+ return ""
+
async def grep(self, *_args, **_kwargs):
return {"matches": []}
@@ -117,8 +121,8 @@ def _make_config(api_key_type: str, mode: str = "remote", **ov_overrides):
mode=mode,
api_key_type=api_key_type,
server_url="http://ov.local",
- api_key="user-key",
- root_api_key="root-key",
+ api_key="root-key" if api_key_type == "root" else "user-key",
+ root_api_key="legacy-root-key",
account_id="acct",
admin_user_id="admin",
**ov_overrides,
@@ -141,6 +145,7 @@ def test_viking_client_init_root_mode_sets_account_and_user(monkeypatch):
first = _DummyHTTPClient.instances[0]
assert client.api_key_type == "root"
+ assert first.kwargs["api_key"] == "root-key"
assert first.kwargs["account"] == "acct"
assert first.kwargs["user"] == "admin"
assert first.kwargs["profile_enabled"] is False
@@ -176,11 +181,25 @@ def test_viking_client_actor_peer_id_sets_actor_header(monkeypatch):
assert first.kwargs["actor_peer_id"] == client.actor_peer_id
+def test_viking_client_uses_effective_auth_mode_for_dev(monkeypatch):
+ config = _make_config("user", mode="remote")
+ config.ov_server.effective_auth_mode = "dev"
+ monkeypatch.setattr(ov_server_module, "load_config", lambda: config)
+
+ client = VikingClient()
+
+ first = _DummyHTTPClient.instances[0]
+ assert client.auth_mode == "dev"
+ assert client.mode == "local"
+ assert first.kwargs == {"url": "http://ov.local"}
+
+
def test_openviking_config_api_key_type_empty_values_are_inferred():
assert OpenVikingConfig(api_key_type=None, api_key="user-key").api_key_type == "user"
assert OpenVikingConfig(api_key_type="", api_key="user-key").api_key_type == "user"
- assert OpenVikingConfig(api_key_type=None, root_api_key="root-key").api_key_type == "root"
- assert OpenVikingConfig(api_key_type="", root_api_key="root-key").api_key_type == "root"
+ config = OpenVikingConfig(api_key_type="root", api_key="root-key")
+ assert config.api_key_type == "root"
+ assert config.api_key == "root-key"
def test_user_key_current_memory_targets_use_current_user_shorthand(monkeypatch):
@@ -194,8 +213,8 @@ def test_user_key_current_memory_targets_use_current_user_shorthand(monkeypatch)
]
-def test_ov_server_legacy_root_api_key_takes_precedence_over_ovcli(monkeypatch):
- bot_data = {"root_api_key": "bot-user-key"}
+def test_ov_server_api_key_mode_ignores_bot_root_key_and_uses_ovcli_user_key(monkeypatch):
+ bot_data = {"root_api_key": "bot-root-key"}
ov_data = {"root_api_key": "server-root-key"}
monkeypatch.setattr(
config_loader_module,
@@ -206,13 +225,30 @@ def test_ov_server_legacy_root_api_key_takes_precedence_over_ovcli(monkeypatch):
config_loader_module._merge_ov_server_config(bot_data, ov_data)
assert bot_data["mode"] == "remote"
- assert bot_data["api_key"] == "bot-user-key"
- assert bot_data["api_key_type"] == "root"
+ assert bot_data["api_key"] == "stale-ovcli-key"
+ assert bot_data["api_key_type"] == "user"
-def test_ov_server_top_level_root_api_key_backfills_legacy_root_mode(monkeypatch):
+def test_ov_server_trusted_mode_fills_api_key_from_top_level_root_key(monkeypatch):
bot_data = {}
- ov_data = {"root_api_key": "server-root-key"}
+ ov_data = {"auth_mode": "trusted", "root_api_key": "server-root-key"}
+ monkeypatch.setattr(
+ config_loader_module,
+ "load_ovcli_config",
+ lambda: SimpleNamespace(api_key="stale-ovcli-key"),
+ )
+
+ config_loader_module._merge_ov_server_config(bot_data, ov_data)
+
+ assert bot_data["mode"] == "remote"
+ assert bot_data["api_key"] == "server-root-key"
+ assert "root_api_key" not in bot_data
+ assert bot_data["api_key_type"] == "root"
+
+
+def test_ov_server_current_trusted_prefers_top_level_root_key(monkeypatch):
+ bot_data = {"api_key": "stale-bot-key"}
+ ov_data = {"auth_mode": "trusted", "root_api_key": "server-root-key"}
monkeypatch.setattr(
config_loader_module,
"load_ovcli_config",
@@ -223,11 +259,96 @@ def test_ov_server_top_level_root_api_key_backfills_legacy_root_mode(monkeypatch
assert bot_data["mode"] == "remote"
assert bot_data["api_key"] == "server-root-key"
- assert bot_data["root_api_key"] == "server-root-key"
assert bot_data["api_key_type"] == "root"
-def test_ov_server_api_key_implies_remote_mode(monkeypatch):
+def test_ov_server_external_url_does_not_inherit_trusted_root_key(monkeypatch):
+ bot_data = {"server_url": "https://external.example"}
+ ov_data = {"auth_mode": "trusted", "root_api_key": "server-root-key"}
+ monkeypatch.setattr(
+ config_loader_module,
+ "load_ovcli_config",
+ lambda: SimpleNamespace(api_key="external-user-key"),
+ )
+
+ config_loader_module._merge_ov_server_config(bot_data, ov_data)
+
+ assert bot_data["mode"] == "remote"
+ assert bot_data["api_key"] == "external-user-key"
+ assert bot_data["api_key_type"] == "user"
+ assert "root_api_key" not in bot_data
+
+
+def test_ov_server_explicit_url_is_external_even_if_it_matches_local_url(monkeypatch):
+ bot_data = {"server_url": "http://localhost:1933"}
+ ov_data = {"auth_mode": "trusted", "root_api_key": "server-root-key"}
+ monkeypatch.setattr(
+ config_loader_module,
+ "load_ovcli_config",
+ lambda: SimpleNamespace(api_key="stale-ovcli-key"),
+ )
+
+ config_loader_module._merge_ov_server_config(bot_data, ov_data)
+
+ assert bot_data["mode"] == "remote"
+ assert bot_data["api_key"] == "stale-ovcli-key"
+ assert bot_data["api_key_type"] == "user"
+ assert "root_api_key" not in bot_data
+
+
+def test_ov_server_external_url_forces_remote_mode():
+ bot_data = {
+ "server_url": "https://external.example",
+ "mode": "local",
+ "api_key": "external-user-key",
+ }
+ ov_data = {"auth_mode": "trusted", "root_api_key": "server-root-key"}
+
+ config_loader_module._merge_ov_server_config(bot_data, ov_data)
+
+ assert bot_data["mode"] == "remote"
+ assert bot_data["api_key"] == "external-user-key"
+ assert bot_data["api_key_type"] == "user"
+ assert "root_api_key" not in bot_data
+
+
+def test_ov_server_external_url_root_key_does_not_imply_root_mode(monkeypatch):
+ bot_data = {
+ "server_url": "https://external.example",
+ "root_api_key": "bot-root-key",
+ }
+ ov_data = {"auth_mode": "trusted", "root_api_key": "server-root-key"}
+ monkeypatch.setattr(
+ config_loader_module,
+ "load_ovcli_config",
+ lambda: SimpleNamespace(api_key="external-user-key"),
+ )
+
+ config_loader_module._merge_ov_server_config(bot_data, ov_data)
+
+ assert bot_data["mode"] == "remote"
+ assert bot_data["api_key"] == "external-user-key"
+ assert bot_data["api_key_type"] == "user"
+ assert bot_data["root_api_key"] == "bot-root-key"
+
+
+def test_ov_server_legacy_mode_is_ignored_for_current_api_key_server(monkeypatch):
+ bot_data = {"mode": "local"}
+ ov_data = {"root_api_key": "server-root-key"}
+ monkeypatch.setattr(
+ config_loader_module,
+ "load_ovcli_config",
+ lambda: SimpleNamespace(api_key="ovcli-user-key"),
+ )
+
+ config_loader_module._merge_ov_server_config(bot_data, ov_data)
+
+ assert bot_data["mode"] == "remote"
+ assert bot_data["api_key"] == "ovcli-user-key"
+ assert bot_data["api_key_type"] == "user"
+
+
+def test_ov_server_current_dev_mode_ignores_legacy_api_key_for_mode(monkeypatch):
bot_data = {"api_key": "bot-user-key"}
monkeypatch.setattr(
config_loader_module,
@@ -237,42 +358,264 @@ def test_ov_server_api_key_implies_remote_mode(monkeypatch):
config_loader_module._merge_ov_server_config(bot_data, {})
- assert bot_data["mode"] == "remote"
+ assert bot_data["mode"] == "local"
assert bot_data["api_key"] == "bot-user-key"
-def test_validate_openviking_auth_allows_local_mode():
- config = SimpleNamespace(ov_server=SimpleNamespace(mode="local", api_key="", root_api_key=""))
+def _auth_probe(*, ok=True, status_code=200, data=None, error=""):
+ return config_loader_module._OpenVikingHTTPResult(
+ ok=ok,
+ status_code=status_code,
+ data=data,
+ error=error,
+ )
+
+
+def test_validate_openviking_auth_warns_when_server_unavailable(monkeypatch, capsys):
+ config = SimpleNamespace(
+ ov_server=SimpleNamespace(
+ mode="remote",
+ api_key_type="user",
+ api_key="user-key",
+ root_api_key="",
+ server_url="http://ov.local",
+ )
+ )
+ monkeypatch.setattr(
+ config_loader_module,
+ "_request_openviking_json",
+ lambda *_args, **_kwargs: _auth_probe(ok=False, error="ConnectError"),
+ )
+
+ config_loader_module.validate_openviking_auth(config)
+
+ captured = capsys.readouterr()
+ assert "OpenViking server at http://ov.local is unavailable" in captured.err
+ assert "Only basic VikingBot features are available" in captured.err
+ assert "user-key" not in captured.err
+
+
+def test_validate_openviking_auth_exits_for_auth_mode_mismatch(monkeypatch, capsys):
+ config = SimpleNamespace(
+ ov_server=SimpleNamespace(
+ mode="remote",
+ api_key_type="user",
+ api_key="user-key",
+ root_api_key="",
+ server_url="http://ov.local",
+ )
+ )
+ monkeypatch.setattr(
+ config_loader_module,
+ "_request_openviking_json",
+ lambda *_args, **_kwargs: _auth_probe(data={"auth_mode": "trusted"}),
+ )
+
+ with pytest.raises(SystemExit):
+ config_loader_module.validate_openviking_auth(config)
+
+ captured = capsys.readouterr()
+ assert "auth mode mismatch" in captured.err
+ assert "OpenViking server URL: http://ov.local" in captured.err
+ assert "Actual server auth_mode: trusted" in captured.err
+ assert "VikingBot current auth_mode: api_key" in captured.err
+ assert "bot.ov_server.api_key_type to 'root'" in captured.err
+ assert "user-key" not in captured.err
+
+
+def test_validate_openviking_auth_warns_for_api_key_mode_without_user_key(
+ monkeypatch, capsys
+):
+ config = SimpleNamespace(
+ ov_server=SimpleNamespace(
+ mode="remote",
+ api_key_type="user",
+ api_key="",
+ root_api_key="root-key",
+ server_url="http://ov.local",
+ )
+ )
+ monkeypatch.setattr(
+ config_loader_module,
+ "_request_openviking_json",
+ lambda *_args, **_kwargs: _auth_probe(data={"auth_mode": "api_key"}),
+ )
+
+ config_loader_module.validate_openviking_auth(config)
+
+ captured = capsys.readouterr()
+ assert "Warning:" in captured.err
+ assert "OpenViking User API key" in captured.err
+ assert "bot.ov_server.api_key" in captured.err
+ assert "Root API keys cannot access" in captured.err
+
+
+def test_validate_openviking_auth_warns_when_user_key_is_root(monkeypatch, capsys):
+ config = SimpleNamespace(
+ ov_server=SimpleNamespace(
+ mode="remote",
+ api_key_type="user",
+ api_key="configured-key",
+ root_api_key="",
+ server_url="http://ov.local",
+ )
+ )
+ calls = []
+
+ def _fake_probe(_server_url, path, *, headers=None):
+ calls.append((path, headers))
+ if headers:
+ return _auth_probe(
+ data={
+ "auth_mode": "api_key",
+ "role": "root",
+ "account_id": "default",
+ "user_id": "default",
+ }
+ )
+ return _auth_probe(data={"auth_mode": "api_key"})
+
+ monkeypatch.setattr(config_loader_module, "_request_openviking_json", _fake_probe)
config_loader_module.validate_openviking_auth(config)
+ captured = capsys.readouterr()
+ assert "resolves to a ROOT API key" in captured.err
+ assert "configured-key" not in captured.err
+ assert calls[1][1] == {"X-API-Key": "configured-key"}
+
+
+def test_validate_openviking_auth_allows_user_key(monkeypatch, capsys):
+ config = SimpleNamespace(
+ ov_server=SimpleNamespace(
+ mode="remote",
+ api_key_type="user",
+ api_key="configured-key",
+ root_api_key="",
+ server_url="http://ov.local",
+ )
+ )
+
+ def _fake_probe(_server_url, _path, *, headers=None):
+ if headers:
+ return _auth_probe(
+ data={
+ "auth_mode": "api_key",
+ "role": "admin",
+ "account_id": "acct",
+ "user_id": "alice",
+ }
+ )
+ return _auth_probe(data={"auth_mode": "api_key"})
+
+ monkeypatch.setattr(config_loader_module, "_request_openviking_json", _fake_probe)
+
+ config_loader_module.validate_openviking_auth(config)
+
+ captured = capsys.readouterr()
+ assert captured.err == ""
+
-def test_validate_openviking_auth_allows_api_key():
+def test_validate_openviking_auth_uses_effective_auth_mode_not_legacy_mode(
+ monkeypatch, capsys
+):
config = SimpleNamespace(
- ov_server=SimpleNamespace(mode="remote", api_key="user-key", root_api_key="")
+ ov_server=SimpleNamespace(
+ effective_auth_mode="dev",
+ mode="remote",
+ api_key_type="user",
+ api_key="configured-key",
+ root_api_key="",
+ server_url="http://ov.local",
+ )
+ )
+ monkeypatch.setattr(
+ config_loader_module,
+ "_request_openviking_json",
+ lambda *_args, **_kwargs: _auth_probe(data={"auth_mode": "dev"}),
)
config_loader_module.validate_openviking_auth(config)
+ captured = capsys.readouterr()
+ assert captured.err == ""
+
-def test_validate_openviking_auth_allows_legacy_root_api_key():
+def test_validate_openviking_auth_warns_for_trusted_bad_root_key(monkeypatch, capsys):
config = SimpleNamespace(
- ov_server=SimpleNamespace(mode="remote", api_key="", root_api_key="root-key")
+ ov_server=SimpleNamespace(
+ mode="remote",
+ api_key="configured-root",
+ api_key_type="root",
+ root_api_key="legacy-root",
+ account_id="acct",
+ admin_user_id="admin",
+ server_url="http://ov.local",
+ )
)
+ def _fake_probe(_server_url, path, *, headers=None):
+ if path == "/api/v1/system/status":
+ assert headers == {
+ "X-OpenViking-Account": "acct",
+ "X-OpenViking-User": "admin",
+ "X-API-Key": "configured-root",
+ }
+ return _auth_probe(ok=False, status_code=401)
+ return _auth_probe(data={"auth_mode": "trusted"})
+
+ monkeypatch.setattr(config_loader_module, "_request_openviking_json", _fake_probe)
+
config_loader_module.validate_openviking_auth(config)
+ captured = capsys.readouterr()
+ assert "configured root API key was rejected" in captured.err
+ assert "configured-root" not in captured.err
-def test_validate_openviking_auth_exits_with_migration_hint(capsys):
- config = SimpleNamespace(ov_server=SimpleNamespace(mode="remote", api_key="", root_api_key=""))
- with pytest.raises(SystemExit):
- config_loader_module.validate_openviking_auth(config)
+def test_validate_openviking_auth_allows_trusted_root(monkeypatch, capsys):
+ config = SimpleNamespace(
+ ov_server=SimpleNamespace(
+ mode="remote",
+ api_key="root-key",
+ api_key_type="root",
+ root_api_key="legacy-root",
+ account_id="acct",
+ admin_user_id="admin",
+ server_url="http://ov.local",
+ )
+ )
+
+ def _fake_probe(_server_url, path, *, headers=None):
+ if path == "/api/v1/system/status":
+ assert headers == {
+ "X-OpenViking-Account": "acct",
+ "X-OpenViking-User": "admin",
+ "X-API-Key": "root-key",
+ }
+ return _auth_probe(data={"status": "ok", "result": {"user": "admin"}})
+ return _auth_probe(data={"auth_mode": "trusted"})
+
+ monkeypatch.setattr(config_loader_module, "_request_openviking_json", _fake_probe)
+
+ config_loader_module.validate_openviking_auth(config)
captured = capsys.readouterr()
- assert "bot.ov_server.api_key" in captured.err
- assert "User API key" in captured.err
- assert "root_api_key is deprecated" in captured.err
+ assert captured.err == ""
+
+
+def test_warn_openviking_auth_config_uses_complete_validation(monkeypatch):
+ config = SimpleNamespace(ov_server=SimpleNamespace(server_url="http://ov.local"))
+ called = []
+ monkeypatch.setattr(
+ config_loader_module,
+ "validate_openviking_auth",
+ lambda value: called.append(value),
+ )
+
+ config_loader_module.warn_openviking_auth_config(config)
+
+ assert called == [config]
def test_memory_user_cli_option_warns_at_runtime(capsys):
@@ -315,6 +658,7 @@ def test_viking_client_request_connection_uses_active_identity(monkeypatch):
"user_id": "anonymous",
"agent_id": "web-playground",
"role": "user",
+ "api_key_type": "user",
"namespace_policy": {
"isolate_user_scope_by_agent": True,
"isolate_agent_scope_by_user": True,
@@ -327,7 +671,6 @@ def test_viking_client_request_connection_uses_active_identity(monkeypatch):
assert client.account_id == "acct"
assert client.admin_user_id == "anonymous"
assert client.agent_id == "web-playground"
- assert client._apikey_manager is None
assert client._namespace_policy_loaded is True
assert client.should_sender_fanout() is False
assert client._memory_target_uri(None) == "viking://user/memories/"
@@ -338,7 +681,7 @@ def test_viking_client_request_connection_uses_active_identity(monkeypatch):
}
-def test_viking_client_request_connection_preserves_admin_scope(monkeypatch):
+def test_viking_client_request_connection_preserves_trusted_scope(monkeypatch):
monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))
VikingClient(
@@ -350,6 +693,7 @@ def test_viking_client_request_connection_preserves_admin_scope(monkeypatch):
"user_id": "default",
"agent_id": "web-playground",
"role": "admin",
+ "api_key_type": "root",
},
)
@@ -363,18 +707,35 @@ def test_viking_client_request_connection_preserves_admin_scope(monkeypatch):
}
+def test_viking_client_request_connection_allows_trusted_no_key(monkeypatch):
+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))
+
+ VikingClient(
+ agent_id="workspace#channel",
+ connection={
+ "server_url": "http://studio.local",
+ "account_id": "acct",
+ "user_id": "alice",
+ "agent_id": "web-playground",
+ "role": "user",
+ "api_key_type": "root",
+ },
+ )
+
+ first = _DummyHTTPClient.instances[0]
+ assert first.kwargs == {
+ "url": "http://studio.local",
+ "profile_enabled": False,
+ "account": "acct",
+ "user": "alice",
+ }
+
+
@pytest.mark.asyncio
-async def test_commit_user_mode_ignores_user_specific_key_flow(monkeypatch):
+async def test_commit_user_mode_uses_user_key_client_only(monkeypatch):
monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))
client = VikingClient()
- async def _must_not_call(*_args, **_kwargs):
- raise AssertionError("user mode should not call user management path")
-
- monkeypatch.setattr(client, "_check_user_exists", _must_not_call)
- monkeypatch.setattr(client, "_initialize_user", _must_not_call)
- monkeypatch.setattr(client, "_get_or_create_user_apikey", _must_not_call)
-
result = await client.commit(
session_id="sess",
messages=[{"role": "user", "content": "hello", "tools_used": []}],
@@ -385,7 +746,7 @@ async def test_commit_user_mode_ignores_user_specific_key_flow(monkeypatch):
@pytest.mark.asyncio
-async def test_commit_request_connection_bypasses_cached_user_key_flow(monkeypatch):
+async def test_commit_request_connection_uses_request_client_only(monkeypatch):
monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))
client = VikingClient(
agent_id="workspace",
@@ -395,16 +756,10 @@ async def test_commit_request_connection_bypasses_cached_user_key_flow(monkeypat
"account_id": "acct",
"user_id": "anonymous",
"agent_id": "web-playground",
+ "api_key_type": "user",
},
)
- async def _must_not_call(*_args, **_kwargs):
- raise AssertionError("request connection should not call user key management path")
-
- monkeypatch.setattr(client, "_check_user_exists", _must_not_call)
- monkeypatch.setattr(client, "_initialize_user", _must_not_call)
- monkeypatch.setattr(client, "_get_or_create_user_apikey", _must_not_call)
-
result = await client.commit(
session_id="sess",
messages=[{"role": "user", "content": "hello", "tools_used": []}],
@@ -427,6 +782,7 @@ async def test_request_connection_search_memory_uses_request_client_only(monkeyp
"user_id": "anonymous",
"agent_id": "web-playground",
"role": "user",
+ "api_key_type": "user",
"namespace_policy": {
"isolate_user_scope_by_agent": False,
"isolate_agent_scope_by_user": False,
@@ -434,12 +790,6 @@ async def test_request_connection_search_memory_uses_request_client_only(monkeyp
},
)
- async def _must_not_call(*_args, **_kwargs):
- raise AssertionError("request connection should not call user management path")
-
- monkeypatch.setattr(client, "_initialize_user", _must_not_call)
- monkeypatch.setattr(client, "_get_or_create_user_apikey", _must_not_call)
-
result = await client.search_memory(
query="php",
user_ids=["anonymous"],
@@ -455,20 +805,10 @@ async def test_request_connection_search_memory_uses_request_client_only(monkeyp
@pytest.mark.asyncio
-async def test_commit_root_mode_uses_sender_user_key(monkeypatch):
+async def test_commit_trusted_root_mode_uses_sender_identity_header(monkeypatch):
monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))
client = VikingClient()
- async def _exists(_user_id):
- return True
-
- async def _user_key(_user_id):
- return "user-key-1"
-
- monkeypatch.setattr(client, "_check_user_exists", _exists)
- monkeypatch.setattr(client, "_get_or_create_user_apikey", _user_key)
- client._apikey_manager = object()
-
result = await client.commit(
session_id="sess",
messages=[{"role": "user", "content": "hello", "tools_used": []}],
@@ -476,7 +816,12 @@ async def test_commit_root_mode_uses_sender_user_key(monkeypatch):
)
assert result["success"] is True
- assert any(inst.kwargs.get("api_key") == "user-key-1" for inst in _DummyHTTPClient.instances)
+ assert any(
+ inst.kwargs.get("api_key") == "root-key"
+ and inst.kwargs.get("account") == "acct"
+ and inst.kwargs.get("user") == "sender-2"
+ for inst in _DummyHTTPClient.instances
+ )
@pytest.mark.asyncio
@@ -1253,24 +1598,14 @@ async def test_search_memory_uses_user_namespace(monkeypatch):
monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))
client = VikingClient()
- calls = []
-
- class _Result:
- memories = []
-
- async def _exists(_user_id):
- return True
-
- async def _find(*, query, target_uri, limit):
- calls.append(target_uri)
- return _Result()
-
- monkeypatch.setattr(client, "_check_user_exists", _exists)
- monkeypatch.setattr(client.client, "find", _find)
-
await client.search_memory("hello", "sender-1", limit=5)
- assert calls == ["viking://user/sender-1/memories/"]
+ scoped = _DummyHTTPClient.instances[1]
+ assert scoped.kwargs["api_key"] == "root-key"
+ assert scoped.kwargs["account"] == "acct"
+ assert scoped.kwargs["user"] == "sender-1"
+ assert scoped.find_calls[0][1]["target_uri"] == "viking://user/sender-1/memories/"
+ assert scoped.closed is True
@pytest.mark.asyncio
@@ -1278,24 +1613,27 @@ async def test_search_memory_uses_user_namespace_without_agent_scope(monkeypatch
monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))
client = VikingClient()
- calls = []
-
- class _Result:
- memories = []
+ await client.search_memory("hello", "sender-1", limit=5)
- async def _exists(_user_id):
- return True
+ scoped = _DummyHTTPClient.instances[1]
+ assert scoped.kwargs["user"] == "sender-1"
+ assert scoped.find_calls[0][1]["target_uri"] == "viking://user/sender-1/memories/"
+ assert scoped.closed is True
- async def _find(*, query, target_uri, limit):
- calls.append(target_uri)
- return _Result()
- monkeypatch.setattr(client, "_check_user_exists", _exists)
- monkeypatch.setattr(client.client, "find", _find)
+async def test_read_content_trusted_owner_uri_uses_owner_identity(monkeypatch):
+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))
+ client = VikingClient()
- await client.search_memory("hello", "sender-1", limit=5)
+ await client.read_content("viking://user/sender-1/memories/profile.md", level="read")
- assert calls == ["viking://user/sender-1/memories/"]
+ scoped = _DummyHTTPClient.instances[1]
+ assert scoped.kwargs["api_key"] == "root-key"
+ assert scoped.kwargs["account"] == "acct"
+ assert scoped.kwargs["user"] == "sender-1"
+ assert scoped.read_calls == [("read", "viking://user/sender-1/memories/profile.md")]
+ assert scoped.closed is True
@pytest.mark.asyncio
@@ -1912,8 +2250,8 @@ async def test_openviking_search_uses_user_namespace(monkeypatch):
assert "sender-1/memories" in result
assert calls == [
("viking://resources/", None),
- ("viking://user/sender-1/memories/", None),
- ("viking://user/sender-1/skills/", None),
+ ("viking://user/sender-1/memories/", "sender-1"),
+ ("viking://user/sender-1/skills/", "sender-1"),
]
diff --git a/bot/vikingbot/agent/context.py b/bot/vikingbot/agent/context.py
index 84fbe1e22..6fdab7643 100644
--- a/bot/vikingbot/agent/context.py
+++ b/bot/vikingbot/agent/context.py
@@ -104,7 +104,7 @@ class ContextBuilder:
ov_tools_enable: Whether to enable OpenViking tools and memory.
profile_user_list: Deprecated list of additional peer IDs to fetch profiles for.
memory_peer_ids: Peer IDs used for memory retrieval; profiles are fetched too.
- memory_owner_user_ids: Deprecated legacy owner-user IDs used for root-key fanout.
+ memory_owner_user_ids: Deprecated owner-user IDs used for trusted-mode lookup.
Returns:
Complete system prompt.
@@ -369,7 +369,7 @@ IMPORTANT:
ov_tools_enable: Whether to enable OpenViking tools and memory.
profile_user_list: Deprecated list of additional peer IDs to fetch profiles for.
memory_peer_ids: Optional list of peer IDs to fetch memory for.
- memory_owner_user_ids: Deprecated legacy owner-user IDs used for root-key fanout.
+ memory_owner_user_ids: Deprecated owner-user IDs used for trusted-mode lookup.
Returns:
List of messages including system prompt.
diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.py
index 068a55853..e6096a146 100644
--- a/bot/vikingbot/agent/loop.py
+++ b/bot/vikingbot/agent/loop.py
@@ -662,7 +662,7 @@ class AgentLoop:
ov_tools_enable: Whether to enable OpenViking tools for this session
memory_peer_ids: List of peer IDs for memory retrieval
memory_owner_user_ids: List of explicit OpenViking user IDs for
- legacy root-key fanout searches
+ trusted-mode owner-user memory lookup
disabled_tools: Tool names to hide from the model for this request
openviking_connection: Request-scoped OpenViking identity for tools
diff --git a/bot/vikingbot/agent/tools/base.py b/bot/vikingbot/agent/tools/base.py
index b3e415faa..533407995 100644
--- a/bot/vikingbot/agent/tools/base.py
+++ b/bot/vikingbot/agent/tools/base.py
@@ -27,7 +27,7 @@ class ToolContext:
memory_peer_ids: Optional list of peer IDs for memory retrieval inside
the current OpenViking user scope.
memory_owner_user_ids: Optional list of explicit OpenViking user IDs
- for legacy root-key fanout searches.
+ for trusted-mode owner-user memory lookup.
openviking_connection: Optional request-scoped OpenViking identity. Studio
requests use this so tools call OpenViking with the same connection
selected in the browser.
diff --git a/bot/vikingbot/agent/tools/ov_file.py b/bot/vikingbot/agent/tools/ov_file.py
index d04129872..ea7cbf738 100644
--- a/bot/vikingbot/agent/tools/ov_file.py
+++ b/bot/vikingbot/agent/tools/ov_file.py
@@ -410,7 +410,7 @@ class VikingSearchTool(OVFileTool):
and (memory_owner_user_ids or legacy_memory_user_ids)
):
user_ids = memory_owner_user_ids or legacy_memory_user_ids
- target_uris = ["viking://resources/"]
+ search_targets: list[tuple[str, str | None]] = [("viking://resources/", None)]
for user_id in self._dedupe_strings(list(user_ids or [])):
memory_uri = client._memory_target_uri(user_id)
skill_uri = (
@@ -418,7 +418,7 @@ class VikingSearchTool(OVFileTool):
if memory_uri.rstrip("/").endswith("/memories")
else "viking://user/skills/"
)
- target_uris.extend([memory_uri, skill_uri])
+ search_targets.extend([(memory_uri, user_id), (skill_uri, user_id)])
else:
peer_ids = self._memory_peer_ids(tool_context)
if not target_uri:
@@ -451,11 +451,15 @@ class VikingSearchTool(OVFileTool):
else:
target_uris = [target_uri]
- for search_target_uri in target_uris:
+ search_targets = [(search_target_uri, None) for search_target_uri in target_uris]
+
+ for search_target_uri, search_user_id in search_targets:
search_kwargs = {
"target_uri": search_target_uri,
"limit": 10,
}
+ if search_user_id:
+ search_kwargs["user_id"] = search_user_id
results = await client.search(query, **search_kwargs)
filtered_items = self._filter_search_items(results, min_score=min_score)
for item_type, items in filtered_items.items():
diff --git a/bot/vikingbot/agent/tools/registry.py b/bot/vikingbot/agent/tools/registry.py
index 4a485e0ec..93a6fbbeb 100644
--- a/bot/vikingbot/agent/tools/registry.py
+++ b/bot/vikingbot/agent/tools/registry.py
@@ -156,7 +156,7 @@ class ToolRegistry:
sender_id: Sender id for the current session.
memory_peer_ids: List of peer IDs for memory retrieval.
memory_owner_user_ids: List of explicit OpenViking user IDs for
- legacy root-key fanout searches.
+ trusted-mode owner-user memory lookup.
memory_user_ids: Deprecated alias for memory_owner_user_ids.
openviking_connection: Request-scoped OpenViking identity.
diff --git a/bot/vikingbot/channels/openapi_models.py b/bot/vikingbot/channels/openapi_models.py
index 8e1f258a2..336fae522 100644
--- a/bot/vikingbot/channels/openapi_models.py
+++ b/bot/vikingbot/channels/openapi_models.py
@@ -54,6 +54,7 @@ class OpenVikingConnection(BaseModel):
user_id: Optional[str] = Field(default=None, description="Effective user ID")
agent_id: Optional[str] = Field(default=None, description="Effective agent ID")
role: Optional[str] = Field(default=None, description="Effective OpenViking role")
+ api_key_type: Optional[str] = Field(default=None, description="OpenViking API key type")
namespace_policy: Optional[Dict[str, bool]] = Field(
default=None,
description="Effective account namespace policy",
diff --git a/bot/vikingbot/cli/commands.py b/bot/vikingbot/cli/commands.py
index 30931e672..705628628 100644
--- a/bot/vikingbot/cli/commands.py
+++ b/bot/vikingbot/cli/commands.py
@@ -77,7 +77,7 @@ def _warn_deprecated_memory_user(memory_user: list[str] | None) -> None:
if not memory_user:
return
typer.secho(
- "Warning: --memory-user is deprecated and only kept for legacy root-key fanout. "
+ "Warning: --memory-user is deprecated and only kept for explicit owner-user lookup. "
"Use --memory-peer for the current OpenViking User/Peer model.",
fg=typer.colors.YELLOW,
err=True,
diff --git a/bot/vikingbot/config/loader.py b/bot/vikingbot/config/loader.py
index cecfbbd5a..20ef334bd 100644
--- a/bot/vikingbot/config/loader.py
+++ b/bot/vikingbot/config/loader.py
@@ -3,15 +3,22 @@
import json
import os
import sys
+from dataclasses import dataclass
from pathlib import Path
from typing import Any
+import httpx
from loguru import logger
+from openviking.server.config import (
+ ServerConfig,
+ get_server_url_from_server_data,
+)
from openviking_cli.utils.config.ovcli_config import load_ovcli_config
from vikingbot.config.schema import Config
CONFIG_PATH = None
+OPENVIKING_AUTH_CHECK_TIMEOUT_SECONDS = 2.0
def get_config_path() -> Path:
@@ -106,10 +113,13 @@ def load_config() -> Config:
bot_server_data = bot_data.get("ov_server", {})
ov_server_data = full_data.get("server", {})
- _merge_ov_server_config(bot_server_data, ov_server_data)
+ effective_auth_mode = _merge_ov_server_config(bot_server_data, ov_server_data)
bot_data["ov_server"] = bot_server_data
- return Config.model_validate(bot_data)
+ config = Config.model_validate(bot_data)
+ config.ov_server.set_effective_auth_mode(effective_auth_mode)
+
+ return config
except (json.JSONDecodeError, ValueError) as e:
print(f"Warning: Failed to load config from {path}: {e}")
print("Using default configuration.")
@@ -141,55 +151,332 @@ def _merge_vlm_model_config(bot_data: dict, vlm_data: dict) -> None:
bot_data["agents"]["extra_headers"] = vlm_data["extra_headers"]
-def _merge_ov_server_config(bot_data: dict, ov_data: dict) -> None:
+def _merge_ov_server_config(bot_data: dict, ov_data: dict) -> str:
"""
Merge ov_server config into bot config.
"""
- if "server_url" not in bot_data or not bot_data["server_url"]:
- host = ov_data.get("host", "127.0.0.1")
- port = ov_data.get("port", "1933")
- bot_data["server_url"] = f"http://{host}:{port}"
- api_key = bot_data.get("api_key") or ""
- legacy_bot_api_key = bot_data.get("root_api_key") or ""
- server_root_api_key = ov_data.get("root_api_key", "")
- if not api_key and legacy_bot_api_key:
- bot_data["api_key"] = legacy_bot_api_key
- bot_data["api_key_type"] = "root"
- api_key = legacy_bot_api_key
- elif not api_key and server_root_api_key:
- bot_data["root_api_key"] = server_root_api_key
+ server_data = ov_data if isinstance(ov_data, dict) else {}
+ configured_server_url = str(bot_data.get("server_url") or "").strip()
+
+ if configured_server_url:
+ return _merge_external_ov_server_config(bot_data, configured_server_url)
+
+ return _merge_current_ov_server_config(bot_data, server_data)
+
+
+def _merge_external_ov_server_config(bot_data: dict, server_url: str) -> str:
+ bot_data["server_url"] = server_url
+ bot_data["mode"] = "remote"
+ bot_data["api_key_type"] = _normalize_api_key_type(bot_data.get("api_key_type")) or "user"
+ if bot_data["api_key_type"] == "user":
+ _fill_user_api_key_from_ovcli(bot_data)
+ return _bot_auth_mode_from_api_key_type(bot_data["api_key_type"], "api_key")
+
+
+def _merge_current_ov_server_config(bot_data: dict, server_data: dict) -> str:
+ bot_data["server_url"] = get_server_url_from_server_data(server_data)
+
+ server_auth_mode = ServerConfig(
+ auth_mode=server_data.get("auth_mode"),
+ root_api_key=server_data.get("root_api_key"),
+ ).get_effective_auth_mode()
+ api_key_type = _normalize_api_key_type(bot_data.get("api_key_type")) or (
+ "root" if server_auth_mode == "trusted" else "user"
+ )
+ bot_data["api_key_type"] = api_key_type
+
+ server_root_api_key = str(server_data.get("root_api_key") or "").strip()
+ if (
+ api_key_type == "root"
+ and server_auth_mode == "trusted"
+ and server_root_api_key
+ ):
bot_data["api_key"] = server_root_api_key
- bot_data["api_key_type"] = "root"
- api_key = server_root_api_key
- mode = bot_data["mode"] if "mode" in bot_data and bot_data["mode"] else ""
- if not mode:
- mode = "remote" if api_key or server_root_api_key else "local"
- bot_data["mode"] = mode
- if not api_key and mode == "remote":
- try:
- cli_config = load_ovcli_config()
- except ValueError as e:
- print(str(e), file=sys.stderr)
- raise
- if cli_config and cli_config.api_key:
- bot_data["api_key"] = cli_config.api_key
-def validate_openviking_auth(config: Config) -> None:
- ov_server = config.ov_server
- if ov_server.mode == "local":
- return
- if ov_server.api_key or ov_server.root_api_key:
+ effective_auth_mode = _bot_auth_mode_from_api_key_type(api_key_type, server_auth_mode)
+ mode = "local" if effective_auth_mode == "dev" else "remote"
+ bot_data["mode"] = mode
+ if effective_auth_mode == "api_key":
+ _fill_user_api_key_from_ovcli(bot_data)
+ return effective_auth_mode
+
+
+def _fill_user_api_key_from_ovcli(bot_data: dict) -> None:
+ if str(bot_data.get("api_key") or "").strip():
return
+ try:
+ cli_config = load_ovcli_config()
+ except ValueError as e:
+ print(str(e), file=sys.stderr)
+ raise
+ if cli_config and cli_config.api_key:
+ bot_data["api_key"] = cli_config.api_key
+
+
+def _normalize_api_key_type(value: Any) -> str:
+ normalized = str(value or "").strip().lower()
+ return normalized if normalized in {"root", "user"} else ""
+
+
+def _bot_auth_mode_from_api_key_type(api_key_type: str, server_auth_mode: str) -> str:
+ if api_key_type == "root":
+ return "trusted"
+ if server_auth_mode == "dev":
+ return "dev"
+ return "api_key"
+
+
+def _ov_server_auth_mode(ov_server: Any) -> str:
+ effective_auth_mode = str(getattr(ov_server, "effective_auth_mode", "") or "").strip().lower()
+ if effective_auth_mode in {"trusted", "api_key", "dev"}:
+ return effective_auth_mode
+
+ api_key_type = _normalize_api_key_type(getattr(ov_server, "api_key_type", "user"))
+ if api_key_type == "root":
+ return "trusted"
+ return "api_key"
+
+
+def _ov_server_trusted_api_key(ov_server: Any) -> str:
+ if _normalize_api_key_type(getattr(ov_server, "api_key_type", "")) == "root":
+ return str(getattr(ov_server, "api_key", "") or "").strip()
+ return ""
+
+
+@dataclass
+class _OpenVikingHTTPResult:
+ ok: bool
+ status_code: int | None = None
+ data: dict[str, Any] | None = None
+ error: str = ""
+
+
+def _openviking_url(server_url: str, path: str) -> str:
+ return f"{str(server_url or '').rstrip('/')}/{path.lstrip('/')}"
+
+
+def _request_openviking_json(
+ server_url: str,
+ path: str,
+ *,
+ headers: dict[str, str] | None = None,
+) -> _OpenVikingHTTPResult:
+ try:
+ with httpx.Client(
+ timeout=OPENVIKING_AUTH_CHECK_TIMEOUT_SECONDS,
+ trust_env=False,
+ ) as client:
+ response = client.get(_openviking_url(server_url, path), headers=headers)
+ except httpx.HTTPError as exc:
+ return _OpenVikingHTTPResult(ok=False, error=exc.__class__.__name__)
+
+ data: dict[str, Any] | None = None
+ try:
+ parsed = response.json()
+ if isinstance(parsed, dict):
+ data = parsed
+ except ValueError:
+ data = None
+ return _OpenVikingHTTPResult(
+ ok=200 <= response.status_code < 300,
+ status_code=response.status_code,
+ data=data,
+ )
+
+def _result_reason(result: _OpenVikingHTTPResult) -> str:
+ if result.status_code is not None:
+ return f"HTTP {result.status_code}"
+ if result.error:
+ return result.error
+ return "unknown error"
+
+
+def _server_unavailable_warning(server_url: str, result: _OpenVikingHTTPResult) -> None:
+ print(
+ f"Warning: OpenViking server at {server_url} is unavailable "
+ f"({_result_reason(result)}). Only basic VikingBot features are available; "
+ "OpenViking memory and file tools may not work.",
+ file=sys.stderr,
+ )
+
+
+def _auth_mode_change_hint(actual_auth_mode: str, current_auth_mode: str) -> str:
+ if actual_auth_mode == "trusted":
+ return (
+ "To use this server, set bot.ov_server.api_key_type to 'root' and configure "
+ "bot.ov_server.api_key with the OpenViking root API key, or remove the "
+ "bot.ov_server override so VikingBot "
+ "inherits server.auth_mode='trusted' from the same ov.conf."
+ )
+ if actual_auth_mode == "api_key":
+ return (
+ "To use this server, set bot.ov_server.api_key_type to 'user' and configure "
+ "bot.ov_server.api_key with an OpenViking User API key, or change the "
+ "OpenViking server.auth_mode and restart the server."
+ )
+ if actual_auth_mode == "dev":
+ return (
+ "To use this server, let VikingBot inherit the same dev OpenViking server "
+ "configuration, or change the OpenViking server.auth_mode and restart the server."
+ )
+ return (
+ "Update bot.ov_server.api_key_type or the OpenViking server.auth_mode so both "
+ f"sides use the same auth mode. VikingBot currently expects '{current_auth_mode}'."
+ )
+
+
+def _raise_auth_mode_mismatch(
+ server_url: str,
+ actual_auth_mode: str,
+ current_auth_mode: str,
+) -> None:
print(
- "Error: missing OpenViking API key for remote mode. "
- "New VikingBot deployments should configure bot.ov_server.api_key with a User API key. "
- "Legacy root-key deployments may still use bot.ov_server.root_api_key, but root_api_key is deprecated.",
+ "Error: OpenViking auth mode mismatch.\n"
+ f"OpenViking server URL: {server_url}\n"
+ f"Actual server auth_mode: {actual_auth_mode}\n"
+ f"VikingBot current auth_mode: {current_auth_mode}\n"
+ f"{_auth_mode_change_hint(actual_auth_mode, current_auth_mode)}",
file=sys.stderr,
)
raise SystemExit(1)
+def _warn_api_key_mode_requires_user_key() -> None:
+ print(
+ "Warning: OpenViking is configured for api_key mode, but bot.ov_server.api_key "
+ "is not configured with a valid OpenViking User API key. OpenViking memory and "
+ "file tools may not work correctly. Configure bot.ov_server.api_key with a User "
+ "API key. Root API keys cannot access OpenViking data APIs in api_key mode.",
+ file=sys.stderr,
+ )
+
+
+def _validate_api_key_mode_key(ov_server: Any, server_url: str) -> None:
+ api_key = str(getattr(ov_server, "api_key", "") or "").strip()
+ api_key_type = _normalize_api_key_type(getattr(ov_server, "api_key_type", "user")) or "user"
+ if not api_key or api_key_type != "user":
+ _warn_api_key_mode_requires_user_key()
+ return
+
+ result = _request_openviking_json(
+ server_url,
+ "/health",
+ headers={"X-API-Key": api_key},
+ )
+ if not result.ok:
+ _server_unavailable_warning(server_url, result)
+ return
+
+ data = result.data or {}
+ role = str(data.get("role") or "").strip().lower()
+ account_id = str(data.get("account_id") or "").strip()
+ user_id = str(data.get("user_id") or "").strip()
+ if role in {"user", "admin"} and account_id and user_id:
+ return
+ if role == "root":
+ print(
+ "Warning: bot.ov_server.api_key resolves to a ROOT API key, but OpenViking "
+ "api_key mode requires a User/Admin API key for memory and file data APIs. "
+ "Configure bot.ov_server.api_key with a User API key.",
+ file=sys.stderr,
+ )
+ return
+ _warn_api_key_mode_requires_user_key()
+
+
+def _validate_trusted_mode_key(ov_server: Any, server_url: str) -> None:
+ root_api_key = _ov_server_trusted_api_key(ov_server)
+ account_id = str(getattr(ov_server, "account_id", "") or "default").strip()
+ user_id = str(getattr(ov_server, "admin_user_id", "") or "default").strip()
+ headers = {
+ "X-OpenViking-Account": account_id,
+ "X-OpenViking-User": user_id,
+ }
+ if root_api_key:
+ headers["X-API-Key"] = root_api_key
+
+ result = _request_openviking_json(server_url, "/api/v1/system/status", headers=headers)
+ if result.ok:
+ return
+
+ if result.status_code in {401, 403}:
+ if root_api_key:
+ print(
+ "Warning: VikingBot is configured for trusted OpenViking access "
+ "(api_key_type=root), but the configured root API key was rejected. "
+ "OpenViking memory and file tools may not work correctly. Configure "
+ "bot.ov_server.api_key with the OpenViking root API key.",
+ file=sys.stderr,
+ )
+ else:
+ print(
+ "Warning: VikingBot is configured for trusted OpenViking access "
+ "(api_key_type=root), but no usable root API key is configured. "
+ "OpenViking memory and file tools may not work correctly. Configure "
+ "bot.ov_server.api_key with the OpenViking root API key, or use localhost "
+ "trusted mode without a root key.",
+ file=sys.stderr,
+ )
+ return
+
+ print(
+ f"Warning: VikingBot could not validate trusted OpenViking access at {server_url} "
+ f"({_result_reason(result)}). OpenViking memory and file tools may not work correctly.",
+ file=sys.stderr,
+ )
+
+
+def validate_openviking_auth(config: Config) -> None:
+ """Validate VikingBot's OpenViking server, auth mode, and API key wiring."""
+ ov_server = config.ov_server
+ server_url = str(getattr(ov_server, "server_url", "") or "").strip()
+ if not server_url:
+ print(
+ "Warning: bot.ov_server.server_url is not configured. Only basic VikingBot "
+ "features are available; OpenViking memory and file tools may not work.",
+ file=sys.stderr,
+ )
+ return
+
+ auth_mode = _ov_server_auth_mode(ov_server)
+
+ health = _request_openviking_json(server_url, "/health")
+ if not health.ok:
+ _server_unavailable_warning(server_url, health)
+ return
+
+ health_data = health.data or {}
+ actual_auth_mode = str(health_data.get("auth_mode") or "").strip().lower()
+ if not actual_auth_mode:
+ print(
+ f"Warning: OpenViking server at {server_url} is reachable, but /health did not "
+ "return auth_mode. OpenViking memory and file tools may not work correctly.",
+ file=sys.stderr,
+ )
+ return
+ if actual_auth_mode != auth_mode:
+ _raise_auth_mode_mismatch(server_url, actual_auth_mode, auth_mode)
+
+ if auth_mode == "trusted":
+ _validate_trusted_mode_key(ov_server, server_url)
+ return
+ if auth_mode == "api_key":
+ _validate_api_key_mode_key(ov_server, server_url)
+ return
+ return
+
+
+def warn_openviking_auth_config(config: Config) -> None:
+ """Backward-compatible wrapper for the complete OpenViking auth validation."""
+ validate_openviking_auth(config)
+
+
+def warn_missing_openviking_user_api_key(config: Config) -> None:
+ """Backward-compatible wrapper for the complete OpenViking auth validation."""
+ warn_openviking_auth_config(config)
+
+
def save_config(
config: Config, config_path: Path | None = None, include_defaults: bool = False
) -> None:
diff --git a/bot/vikingbot/config/schema.py b/bot/vikingbot/config/schema.py
index b829ef6e8..d6287abd5 100644
--- a/bot/vikingbot/config/schema.py
+++ b/bot/vikingbot/config/schema.py
@@ -4,7 +4,7 @@ from enum import Enum
from pathlib import Path
from typing import Any, Dict, Literal, Optional
-from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
+from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
@@ -65,7 +65,7 @@ class BaseChannelConfig(BaseModel):
enabled: bool = True
ov_tools_enable: bool = True
memory_peer: list[str] | None = None
- memory_user: list[str] | None = None # Deprecated legacy owner-user memory lookup.
+ memory_user: list[str] | None = None # Deprecated alias for owner-user memory lookup.
def channel_id(self) -> str:
return "default"
@@ -515,11 +515,16 @@ class WebSearchConfig(BaseModel):
class OpenVikingConfig(BaseModel):
"""Viking tools configuration."""
- mode: str = "remote" # local or remote
+ _effective_auth_mode: str = PrivateAttr(default="")
+
+ # Deprecated as user config. Kept for compatibility; load_config derives it
+ # from OpenViking's effective dev auth mode.
+ mode: str = "remote"
api_key_type: Literal["root", "user"] | None = None
server_url: str = ""
+ # User API key when api_key_type=user; root API key when api_key_type=root.
api_key: str = ""
- # 废弃,后续使用api_key
+ # Deprecated compatibility field. Use api_key with api_key_type=root instead.
root_api_key: str = ""
account_id: str = "default"
admin_user_id: str = "default"
@@ -552,13 +557,18 @@ class OpenVikingConfig(BaseModel):
return normalized or None
@model_validator(mode="after")
- def apply_api_key_compatibility(self):
+ def default_api_key_type(self):
if not self.api_key_type:
- self.api_key_type = "user" if not self.root_api_key or self.api_key else "root"
- if self.root_api_key and not self.api_key:
- self.api_key = self.root_api_key
+ self.api_key_type = "user"
return self
+ @property
+ def effective_auth_mode(self) -> str:
+ return self._effective_auth_mode
+
+ def set_effective_auth_mode(self, auth_mode: str) -> None:
+ self._effective_auth_mode = str(auth_mode or "").strip().lower()
+
class WebToolsConfig(BaseModel):
"""Web tools configuration."""
diff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.py
index 715ce62ec..57ae73bc1 100644
--- a/bot/vikingbot/openviking_mount/ov_server.py
+++ b/bot/vikingbot/openviking_mount/ov_server.py
@@ -8,9 +8,9 @@ from typing import Any, Dict, List, Mapping, Optional
from loguru import logger
import openviking as ov
+from openviking.core.namespace import uri_parts
from openviking.core.peer_id import normalize_peer_id
from vikingbot.config.loader import load_config
-from vikingbot.openviking_mount.user_apikey_manager import UserApiKeyManager
viking_resource_prefix = "viking://resources/"
@@ -56,12 +56,10 @@ class VikingClient:
self.workspace_id = agent_id
self.agent_id = agent_id
self.ov_path = config.ov_data_path
- self.mode = openviking_config.mode
- self.api_key_type = (openviking_config.api_key_type or "user").strip().lower()
- if self.api_key_type not in {"root", "user"}:
- raise ValueError(f"Invalid ov_server.api_key_type: {self.api_key_type}")
+ self.auth_mode = self._resolve_auth_mode(openviking_config)
+ self.mode = "local" if self.auth_mode == "dev" else "remote"
+ self.api_key_type = self._resolve_api_key_type(openviking_config)
- self._apikey_manager = None
self.admin_user_client = None
self._user_clients = {}
self._namespace_policy = {
@@ -76,7 +74,7 @@ class VikingClient:
)
self.actor_peer_id = self._peer_id(actor_peer_id) or self._peer_id(connection_actor_peer_id)
- if openviking_config.mode == "local":
+ if self._is_dev_mode():
client_kwargs = {"url": openviking_config.server_url}
self._apply_actor_peer_scope(client_kwargs)
if agent_id is None or _is_session_key(agent_id):
@@ -96,7 +94,7 @@ class VikingClient:
self.account_id = openviking_config.account_id
self.admin_user_id = openviking_config.admin_user_id
- api_key = openviking_config.api_key or openviking_config.root_api_key
+ api_key = openviking_config.api_key
remote_client_kwargs = {
"url": openviking_config.server_url,
"api_key": api_key,
@@ -109,12 +107,31 @@ class VikingClient:
self._apply_actor_peer_scope(remote_client_kwargs)
self.client = ov.AsyncHTTPClient(**remote_client_kwargs)
- if self._is_root_key_mode() and self.ov_path:
- self._apikey_manager = UserApiKeyManager(
- ov_path=self.ov_path,
- server_url=openviking_config.server_url,
- account_id=openviking_config.account_id,
- )
+ @staticmethod
+ def _normalize_auth_value(value: Any) -> str:
+ return str(value or "").strip().lower()
+
+ def _resolve_auth_mode(self, openviking_config: Any) -> str:
+ effective_auth_mode = self._normalize_auth_value(
+ getattr(openviking_config, "effective_auth_mode", None)
+ )
+ if effective_auth_mode in {"trusted", "api_key", "dev"}:
+ return effective_auth_mode
+
+ api_key_type = self._normalize_auth_value(getattr(openviking_config, "api_key_type", None))
+ if api_key_type == "root":
+ return "trusted"
+ return "api_key"
+
+ def _resolve_api_key_type(self, openviking_config: Any) -> str:
+ api_key_type = self._normalize_auth_value(getattr(openviking_config, "api_key_type", None))
+ if self.auth_mode == "trusted":
+ api_key_type = "root"
+ elif self.auth_mode in {"api_key", "dev"}:
+ api_key_type = "user"
+ if api_key_type not in {"root", "user"}:
+ raise ValueError(f"Invalid ov_server.api_key_type: {api_key_type}")
+ return api_key_type
@staticmethod
def _normalize_connection(
@@ -129,6 +146,7 @@ class VikingClient:
"user_id",
"agent_id",
"role",
+ "api_key_type",
"server_url",
"actor_peer_id",
):
@@ -146,6 +164,12 @@ class VikingClient:
),
}
if not normalized.get("api_key"):
+ if (
+ normalized.get("api_key_type") == "root"
+ and normalized.get("account_id")
+ and normalized.get("user_id")
+ ):
+ return normalized
return None
return normalized
@@ -154,7 +178,8 @@ class VikingClient:
self.mode = "remote"
request_role = str(connection.get("role") or "").strip().lower()
self._request_role = request_role or None
- self.api_key_type = "user"
+ self.api_key_type = self._normalize_auth_value(connection.get("api_key_type")) or "user"
+ self.auth_mode = "trusted" if self.api_key_type == "root" else "api_key"
self.agent_id = connection.get("agent_id") or agent_id
self.workspace_id = self.agent_id
self.account_id = connection.get("account_id") or self.openviking_config.account_id
@@ -167,12 +192,13 @@ class VikingClient:
remote_client_kwargs = {
"url": connection.get("server_url") or self.openviking_config.server_url,
- "api_key": connection["api_key"],
"profile_enabled": False,
}
- if request_role != "user" and self.account_id:
+ if connection.get("api_key"):
+ remote_client_kwargs["api_key"] = connection["api_key"]
+ if self.api_key_type == "root" and self.account_id:
remote_client_kwargs["account"] = self.account_id
- if request_role != "user" and self.admin_user_id:
+ if self.api_key_type == "root" and self.admin_user_id:
remote_client_kwargs["user"] = self.admin_user_id
self._apply_actor_peer_scope(remote_client_kwargs)
@@ -229,18 +255,21 @@ class VikingClient:
def _is_root_key_mode(self) -> bool:
return (
- self.mode == "remote"
+ self.auth_mode == "trusted"
and self.api_key_type == "root"
and not self._has_request_connection()
)
def _is_user_key_mode(self) -> bool:
return (
- self.mode == "remote"
+ self.auth_mode == "api_key"
and self.api_key_type == "user"
and not self._has_request_connection()
)
+ def _is_dev_mode(self) -> bool:
+ return self.auth_mode == "dev" and not self._has_request_connection()
+
def _has_request_connection(self) -> bool:
return self._request_connection is not None
@@ -255,7 +284,7 @@ class VikingClient:
return user_id or self.admin_user_id
def _effective_session_user_id(self, user_id: Optional[str] = None) -> Optional[str]:
- if self._has_request_connection() or self.mode == "local" or self._is_user_key_mode():
+ if self._has_request_connection() or self._is_dev_mode() or self._is_user_key_mode():
return None
return user_id or self.admin_user_id
@@ -287,7 +316,7 @@ class VikingClient:
"isolate_user_scope_by_agent": False,
"isolate_agent_scope_by_user": False,
}
- if self._has_request_connection() or self.mode == "local" or self._is_user_key_mode():
+ if self._has_request_connection() or self._is_dev_mode() or self._is_user_key_mode():
self._namespace_policy = policy
self._namespace_policy_loaded = True
return
@@ -328,6 +357,22 @@ class VikingClient:
return f"viking://user/{user_space}/memories/"
return "viking://user/memories/"
+ def _owner_user_id_for_uri(self, uri: Optional[str]) -> Optional[str]:
+ if not self._is_root_key_mode():
+ return None
+ try:
+ parts = uri_parts(str(uri or ""))
+ except Exception:
+ return None
+ if len(parts) < 2 or parts[0] != "user":
+ return None
+ if parts[1] in {"memories", "resources", "skills", "peers", "privacy", "sessions"}:
+ return None
+ owner_user_id = parts[1]
+ if owner_user_id == self.admin_user_id:
+ return None
+ return owner_user_id
+
def _peer_memory_target_uri(self, user_id: Optional[str], peer_id: str) -> str:
user_space = self._user_space_fragment(user_id)
normalized_peer_id = self._peer_id(peer_id)
@@ -449,6 +494,23 @@ class VikingClient:
deduped.append(target_uri)
return deduped
+ def build_memory_search_targets(
+ self,
+ *,
+ user_ids: Optional[List[str]] = None,
+ owner_user_id: Optional[str] = None,
+ peer_ids: Optional[List[str]] = None,
+ ) -> List[tuple[str, Optional[str]]]:
+ target_uris = self.build_memory_search_target_uris(
+ user_ids=user_ids,
+ owner_user_id=owner_user_id,
+ peer_ids=peer_ids,
+ )
+ return [
+ (target_uri, self._owner_user_id_for_uri(target_uri))
+ for target_uri in target_uris
+ ]
+
def _skill_memory_uri(self, skill_name: str, user_id: Optional[str] = None) -> str:
return f"{self._memory_target_uri(user_id)}skills/{skill_name}.md"
@@ -484,20 +546,31 @@ class VikingClient:
entries = await self.client.ls(path, recursive=recursive)
return entries
- async def read_content(self, uri: str, level: str = "abstract") -> str:
+ async def read_content(
+ self,
+ uri: str,
+ level: str = "abstract",
+ user_id: Optional[str] = None,
+ ) -> str:
"""读取内容
Args:
uri: Viking URI
level: 读取级别 ("abstract" - L0摘要, "overview" - L1概览, "read" - L2完整内容)
"""
+ client = self.client
+ should_close = False
+ scoped_user_id = user_id or self._owner_user_id_for_uri(uri)
+ if scoped_user_id:
+ client, should_close = await self._get_user_scoped_client(scoped_user_id)
+
try:
if level == "abstract":
- return await self.client.abstract(uri)
+ return await client.abstract(uri)
elif level == "overview":
- return await self.client.overview(uri)
+ return await client.overview(uri)
elif level == "read":
- return await self.client.read(uri)
+ return await client.read(uri)
else:
raise ValueError(f"Unsupported level: {level}")
except FileNotFoundError:
@@ -505,6 +578,9 @@ class VikingClient:
except Exception as e:
logger.warning(f"Failed to read content from {uri}: {e}")
return ""
+ finally:
+ if should_close:
+ await client.close()
async def read_user_profile(self, user_id: str) -> str:
"""读取用户 profile。"""
@@ -512,14 +588,8 @@ class VikingClient:
if not effective_user_id:
return await self.read_content(uri="viking://user/memories/profile.md", level="read")
- user_exists = await self._check_user_exists(effective_user_id)
-
- if not user_exists:
- await self._initialize_user(effective_user_id)
- return ""
-
uri = f"{self._memory_target_uri(effective_user_id)}profile.md"
- result = await self.read_content(uri=uri, level="read")
+ result = await self.read_content(uri=uri, level="read", user_id=effective_user_id)
return result
async def read_peer_profile(self, peer_id: str) -> str:
@@ -539,8 +609,11 @@ class VikingClient:
) -> Dict[str, Any]:
client = self.client
should_close = False
- if user_id:
- client, should_close = await self._get_user_scoped_client(user_id)
+ scoped_user_id = user_id
+ if scoped_user_id is None and isinstance(target_uri, str):
+ scoped_user_id = self._owner_user_id_for_uri(target_uri)
+ if scoped_user_id:
+ client, should_close = await self._get_user_scoped_client(scoped_user_id)
try:
result = await client.search(
@@ -570,87 +643,10 @@ class VikingClient:
async def search_user_memory(self, query: str, user_id: str) -> list[Any]:
effective_user_id = self._effective_user_id(user_id)
- user_exists = await self._check_user_exists(effective_user_id)
- if not user_exists:
- return []
uri_user_memory = self._memory_target_uri(effective_user_id)
- result = await self.client.search(query, target_uri=uri_user_memory)
- return (
- [self._matched_context_to_dict(m) for m in result.memories]
- if hasattr(result, "memories")
- else []
- )
-
- async def _check_user_exists(self, user_id: str) -> bool:
- """检查用户是否存在于账户中。"""
- if self.mode == "local" or self._is_user_key_mode() or self._has_request_connection():
- return True
- if not user_id:
- return False
- try:
- res = await self.client.admin_list_users(self.account_id)
- if not res or len(res) == 0:
- return False
- return any(user.get("user_id") == user_id for user in res)
- except Exception as e:
- logger.warning(f"Failed to check user existence: {e}")
- return False
-
- async def _initialize_user(self, user_id: str, role: str = "user") -> bool:
- """初始化用户。"""
- if self.mode == "local" or self._is_user_key_mode() or self._has_request_connection():
- return True
- if not user_id:
- return False
- try:
- result = await self.client.admin_register_user(
- account_id=self.account_id, user_id=user_id, role=role
- )
-
- if self._apikey_manager and isinstance(result, dict):
- api_key = result.get("user_key")
- if api_key:
- self._apikey_manager.set_apikey(user_id, api_key)
-
- return True
- except Exception as e:
- if "User already exists" in str(e):
- return True
- logger.warning(f"Failed to initialize user {user_id}: {e}")
- return False
-
- async def _get_or_create_user_apikey(self, user_id: str, role: str = "user") -> Optional[str]:
- """获取或创建用户的 API key。"""
- if (
- self._has_request_connection()
- or self._is_user_key_mode()
- or not self._apikey_manager
- or not user_id
- ):
- return None
-
- api_key = self._apikey_manager.get_apikey(user_id)
- if api_key:
- return api_key
-
- try:
- user_exists = await self._check_user_exists(user_id)
- if user_exists:
- await self.client.admin_remove_user(self.account_id, user_id)
- success = await self._initialize_user(user_id, role=role)
- if not success:
- logger.warning(f"Failed to recreate user {user_id}")
- return None
-
- api_key = self._apikey_manager.get_apikey(user_id)
- if api_key:
- return api_key
- else:
- return None
-
- except Exception as e:
- logger.error(f"Error getting or creating API key for user {user_id}: {e}")
- return None
+ result = await self.search(query, target_uri=uri_user_memory, user_id=effective_user_id)
+ memories = result.get("memories") if isinstance(result, dict) else None
+ return memories if isinstance(memories, list) else []
async def _get_user_scoped_client(self, user_id: Optional[str]) -> tuple[Any, bool]:
effective_user_id = self._effective_user_id(user_id)
@@ -658,36 +654,24 @@ class VikingClient:
return self.client, False
if self._is_root_key_mode():
- if not self._apikey_manager:
- raise RuntimeError("User API key manager is unavailable for user-scoped client")
-
- role = "admin" if effective_user_id == self.admin_user_id else "user"
- user_exists = await self._check_user_exists(effective_user_id)
- if not user_exists:
- success = await self._initialize_user(effective_user_id, role=role)
- if not success:
- raise RuntimeError(f"Failed to initialize user {effective_user_id}")
-
- user_api_key = await self._get_or_create_user_apikey(effective_user_id, role=role)
- if not user_api_key:
- raise RuntimeError(f"Failed to get API key for user {effective_user_id}")
-
- client_kwargs = {
- "url": self.openviking_config.server_url,
- "api_key": user_api_key,
- "profile_enabled": False,
- }
- if effective_user_id == self.admin_user_id:
- client_kwargs["account"] = self.account_id
- client_kwargs["user"] = self.admin_user_id
-
- self._apply_actor_peer_scope(client_kwargs)
- client = ov.AsyncHTTPClient(**client_kwargs)
- await client.initialize()
+ client = await self._create_trusted_user_client(effective_user_id)
return client, True
return self.client, False
+ async def _create_trusted_user_client(self, user_id: str):
+ client_kwargs = {
+ "url": self.openviking_config.server_url,
+ "api_key": self.openviking_config.api_key,
+ "account": self.account_id,
+ "user": user_id,
+ "profile_enabled": False,
+ }
+ self._apply_actor_peer_scope(client_kwargs)
+ client = ov.AsyncHTTPClient(**client_kwargs)
+ await client.initialize()
+ return client
+
async def search_memory(
self,
query: str,
@@ -730,38 +714,31 @@ class VikingClient:
)
effective_owner_user_id = self._effective_user_id(owner_user_id) if owner_user_id else None
- user_ids_to_check = self._dedupe_strings(
- [
- *normalized_user_ids,
- *( [effective_owner_user_id] if effective_owner_user_id else [] ),
- ]
- )
-
- for user_id in user_ids_to_check:
- effective_user_id = self._effective_user_id(user_id)
- if not effective_user_id:
- continue
- user_exists = await self._check_user_exists(effective_user_id)
- if not user_exists:
- await self._initialize_user(effective_user_id)
-
- target_uris = self.build_memory_search_target_uris(
+ search_targets = self.build_memory_search_targets(
user_ids=normalized_user_ids,
owner_user_id=effective_owner_user_id,
peer_ids=normalized_peer_ids,
)
- if not target_uris:
+ if not search_targets:
return []
all_user_memories = []
- for target_uri in target_uris:
+ for target_uri, scoped_user_id in search_targets:
find_kwargs: Dict[str, Any] = {
"query": query,
"target_uri": target_uri,
"limit": limit,
}
- user_memory = await self.client.find(**find_kwargs)
- all_user_memories.extend(_extract_memories(user_memory))
+ client = self.client
+ should_close = False
+ if scoped_user_id:
+ client, should_close = await self._get_user_scoped_client(scoped_user_id)
+ try:
+ user_memory = await client.find(**find_kwargs)
+ all_user_memories.extend(_extract_memories(user_memory))
+ finally:
+ if should_close:
+ await client.close()
if agent_user_id is not None:
agent_uri = f"viking://agent/{self.agent_id or self.admin_user_id}/memories/"
@@ -833,33 +810,16 @@ class VikingClient:
async def _session_client_for_user(self, user_id: Optional[str] = None):
if self._has_request_connection():
return self.client
- if not user_id or self.mode == "local" or self._is_user_key_mode():
+ if not user_id or self._is_dev_mode() or self._is_user_key_mode():
return self._session_client(user_id)
if user_id == self.admin_user_id and self.admin_user_client:
return self.admin_user_client
- user_exists = await self._check_user_exists(user_id)
- if not user_exists:
- await self._initialize_user(user_id)
-
- api_key = await self._get_or_create_user_apikey(user_id)
- if not api_key:
- return self._session_client(user_id)
-
client = self._user_clients.get(user_id)
- if client is None:
- client_kwargs = {
- "url": self.openviking_config.server_url,
- "api_key": api_key,
- "account": self.account_id,
- "user": user_id,
- "profile_enabled": False,
- }
- self._apply_actor_peer_scope(client_kwargs)
- client = ov.AsyncHTTPClient(**client_kwargs)
- await client.initialize()
+ if client is None and self._is_root_key_mode():
+ client = await self._create_trusted_user_client(user_id)
self._user_clients[user_id] = client
- return client
+ return client or self._session_client(user_id)
def _assistant_peer_id(self) -> Optional[str]:
return None
@@ -1136,11 +1096,6 @@ async def account_test():
)
await client.initialize()
- # res = await client.admin_list_users("eval")
- # res = await client.admin_remove_user("default", "")
- # res = await client.admin_remove_user("default", "admin")
- # res = await client.admin_list_accounts()
- # res = await client.admin_create_account("eval", "default")
res = await client.search("123")
print(res)
diff --git a/bot/vikingbot/openviking_mount/user_apikey_manager.py b/bot/vikingbot/openviking_mount/user_apikey_manager.py
deleted file mode 100644
index da638d95d..000000000
--- a/bot/vikingbot/openviking_mount/user_apikey_manager.py
+++ /dev/null
@@ -1,122 +0,0 @@
-"""User API Key persistence manager for OpenViking remote mode."""
-
-import json
-import hashlib
-from pathlib import Path
-from typing import Optional
-
-from loguru import logger
-
-
-class UserApiKeyManager:
- """Manages user API key persistence based on server_url and account_id.
-
- Stores API keys in a JSON file located at:
- {ov_path}/user_apikeys_{hash}.json
-
- where {hash} is derived from server_url and account_id.
- """
-
- def __init__(self, ov_path: Path, server_url: str, account_id: str):
- """Initialize the API key manager.
-
- Args:
- ov_path: The ov_path where config files are stored
- server_url: The OpenViking server URL
- account_id: The account ID
- """
- self.ov_path = Path(ov_path)
- self.server_url = server_url
- self.account_id = account_id
-
- # Generate hash from server_url and account_id
- hash_input = f"{server_url}:{account_id}"
- self.config_hash = hashlib.md5(hash_input.encode()).hexdigest()[:16]
-
- # Config file path
- self.config_dir = self.ov_path
- self.config_file = self.config_dir / f"user_apikeys_{self.config_hash}.json"
-
- # In-memory cache
- self._apikeys: dict[str, str] = {}
- self._loaded = False
-
- def _ensure_config_dir(self) -> None:
- """Ensure the config directory exists."""
- self.config_dir.mkdir(parents=True, exist_ok=True)
-
- def _load(self) -> None:
- """Load API keys from the config file."""
- if self._loaded:
- return
-
- if self.config_file.exists():
- try:
- with open(self.config_file, "r", encoding="utf-8") as f:
- data = json.load(f)
- self._apikeys = data.get("apikeys", {})
- except Exception as e:
- logger.warning(f"Failed to load API keys from {self.config_file}: {e}")
- self._apikeys = {}
- else:
- logger.debug(f"API key config file not found: {self.config_file}")
-
- self._loaded = True
-
- def _save(self) -> None:
- """Save API keys to the config file."""
- self._ensure_config_dir()
-
- try:
- data = {
- "server_url": self.server_url,
- "account_id": self.account_id,
- "apikeys": self._apikeys,
- }
-
- with open(self.config_file, "w", encoding="utf-8") as f:
- json.dump(data, f, indent=2, ensure_ascii=False)
-
- logger.debug(f"Saved {len(self._apikeys)} API keys to {self.config_file}")
- except Exception as e:
- logger.error(f"Failed to save API keys to {self.config_file}: {e}")
- raise
-
- def get_apikey(self, user_id: str) -> Optional[str]:
- """Get the API key for a specific user.
-
- Args:
- user_id: The user ID
-
- Returns:
- The API key if found, None otherwise
- """
- self._load()
- return self._apikeys.get(user_id)
-
- def set_apikey(self, user_id: str, api_key: str) -> None:
- """Set the API key for a specific user.
-
- Args:
- user_id: The user ID
- api_key: The API key to store
- """
- self._load()
- self._apikeys[user_id] = api_key
- self._save()
-
- def delete_apikey(self, user_id: str) -> bool:
- """Delete the API key for a specific user.
-
- Args:
- user_id: The user ID
-
- Returns:
- True if the key was deleted, False if not found
- """
- self._load()
- if user_id in self._apikeys:
- del self._apikeys[user_id]
- self._save()
- return True
- return False
diff --git a/bot/vikingbot/tests/unit/test_openviking_peer_identity.py b/bot/vikingbot/tests/unit/test_openviking_peer_identity.py
index 607b9ca47..5057102a4 100644
--- a/bot/vikingbot/tests/unit/test_openviking_peer_identity.py
+++ b/bot/vikingbot/tests/unit/test_openviking_peer_identity.py
@@ -24,6 +24,7 @@ TELEGRAM_ALICE_PEER_ID = "ext-dGVsZWdyYW06YWxpY2U"
def _client(api_key_type: str = "user") -> VikingClient:
client = VikingClient.__new__(VikingClient)
client.mode = "remote"
+ client.auth_mode = "trusted" if api_key_type == "root" else "api_key"
client.api_key_type = api_key_type
client.admin_user_id = "bot-user"
client.agent_id = "agent-1"
diff --git a/crates/ov_cli/src/base_client.rs b/crates/ov_cli/src/base_client.rs
index c21f69ded..1cf5e58ef 100644
--- a/crates/ov_cli/src/base_client.rs
+++ b/crates/ov_cli/src/base_client.rs
@@ -934,4 +934,4 @@ impl<'a> FileUploader<'a> {
.map(|s| s.to_string())
.ok_or_else(|| Error::Parse("Missing temp_file_id in response".to_string()))
}
-}
\ No newline at end of file
+}
diff --git a/crates/ov_cli/src/commands/chat.rs b/crates/ov_cli/src/commands/chat.rs
index 904fc26c5..b64df88be 100644
--- a/crates/ov_cli/src/commands/chat.rs
+++ b/crates/ov_cli/src/commands/chat.rs
@@ -103,6 +103,18 @@ struct ChatStreamEvent {
data: serde_json::Value,
}
+#[derive(Debug, Deserialize)]
+struct OpenVikingHealth {
+ #[serde(default)]
+ auth_mode: Option<String>,
+ #[serde(default)]
+ role: Option<String>,
+ #[serde(default)]
+ account_id: Option<String>,
+ #[serde(default)]
+ user_id: Option<String>,
+}
+
struct ChatAuth {
api_key: Option<String>,
account: Option<String>,
@@ -112,12 +124,16 @@ struct ChatAuth {
impl ChatCommand {
/// Execute the chat command
pub async fn execute(&self) -> Result<()> {
- let auth = self.resolve_auth()?;
let client = Client::builder()
.timeout(Duration::from_secs(300))
.build()
.map_err(|e| Error::Network(format!("Failed to create HTTP client: {}", e)))?;
+ let health = self.fetch_openviking_health(&client, None).await;
+ let auth = self.resolve_auth(health.as_ref().map(health_auth_mode))?;
+ self.warn_openviking_chat_auth(&client, health.as_ref(), &auth)
+ .await;
+
if let Some(message) = &self.message {
// Single message mode
self.send_message(&client, message, &auth).await
@@ -127,19 +143,39 @@ impl ChatCommand {
}
}
- fn resolve_auth(&self) -> Result<ChatAuth> {
+ fn resolve_auth(&self, server_auth_mode: Option<&str>) -> Result<ChatAuth> {
let config = Config::load()?;
+ Ok(self.resolve_auth_from_config(config, server_auth_mode))
+ }
+
+ fn resolve_auth_from_config(&self, config: Config, server_auth_mode: Option<&str>) -> ChatAuth {
+ if server_auth_mode
+ .map(|mode| mode.trim().eq_ignore_ascii_case("trusted"))
+ .unwrap_or(false)
+ {
+ return ChatAuth {
+ api_key: non_empty_string(self.api_key.clone())
+ .or_else(|| non_empty_string(config.root_api_key.clone()))
+ .or_else(|| non_empty_string(config.api_key.clone())),
+ account: non_empty_string(self.account.clone())
+ .or_else(|| non_empty_string(config.account.clone())),
+ user: non_empty_string(self.user.clone())
+ .or_else(|| non_empty_string(config.user.clone())),
+ };
+ }
+
let auth = config.effective_auth_with_overrides(
self.api_key.clone(),
self.account.clone(),
self.user.clone(),
false,
);
- Ok(ChatAuth {
+
+ ChatAuth {
api_key: auth.api_key,
account: auth.account,
user: auth.user,
- })
+ }
}
fn apply_auth_headers(
@@ -159,6 +195,85 @@ impl ChatCommand {
req_builder
}
+ fn openviking_health_url(&self) -> Option<String> {
+ let endpoint = self.endpoint.trim_end_matches('/');
+ endpoint
+ .strip_suffix("/bot/v1")
+ .map(|server_url| format!("{}/health", server_url.trim_end_matches('/')))
+ }
+
+ async fn fetch_openviking_health(
+ &self,
+ client: &Client,
+ auth: Option<&ChatAuth>,
+ ) -> Option<OpenVikingHealth> {
+ let health_url = self.openviking_health_url()?;
+ let mut req_builder = client.get(health_url).timeout(Duration::from_secs(5));
+ if let Some(auth) = auth {
+ req_builder = self.apply_auth_headers(req_builder, auth);
+ }
+ let response = req_builder.send().await.ok()?;
+ if !response.status().is_success() {
+ return None;
+ }
+ response.json::<OpenVikingHealth>().await.ok()
+ }
+
+ async fn warn_openviking_chat_auth(
+ &self,
+ client: &Client,
+ health: Option<&OpenVikingHealth>,
+ auth: &ChatAuth,
+ ) {
+ let Some(health) = health else {
+ return;
+ };
+ if health_auth_mode(health) != "api_key" {
+ return;
+ }
+
+ if auth
+ .api_key
+ .as_deref()
+ .unwrap_or_default()
+ .trim()
+ .is_empty()
+ {
+ eprintln!(
+ "Warning: OpenViking server is in api_key mode, but ov chat is not configured \
+with a User API key. OpenViking-backed VikingBot memory and file tools may not work correctly. \
+Configure api_key in ovcli.conf with a User/Admin API key, or pass --api-key."
+ );
+ return;
+ }
+
+ let Some(authenticated_health) = self.fetch_openviking_health(client, Some(auth)).await
+ else {
+ eprintln!(
+ "Warning: OpenViking server is in api_key mode, but ov chat could not validate \
+the configured API key. OpenViking-backed VikingBot memory and file tools may not work correctly."
+ );
+ return;
+ };
+
+ if health_has_user_identity(&authenticated_health) {
+ return;
+ }
+
+ if health_role(&authenticated_health) == "root" {
+ eprintln!(
+ "Warning: ov chat is using a ROOT API key, but OpenViking api_key mode requires \
+a User/Admin API key for VikingBot memory and file tools. Configure api_key in ovcli.conf with \
+a User/Admin API key, or pass --api-key."
+ );
+ } else {
+ eprintln!(
+ "Warning: ov chat could not validate the configured API key as an OpenViking \
+User/Admin API key. OpenViking-backed VikingBot memory and file tools may not work correctly."
+ );
+ }
+ }
+
/// Send a single message and get response
async fn send_message(&self, client: &Client, message: &str, auth: &ChatAuth) -> Result<()> {
if self.stream {
@@ -682,3 +797,179 @@ fn render_markdown(text: &str) {
let skin = MadSkin::default();
skin.print_text(text);
}
+
+fn health_auth_mode(health: &OpenVikingHealth) -> &str {
+ health.auth_mode.as_deref().unwrap_or_default().trim()
+}
+
+fn health_role(health: &OpenVikingHealth) -> &str {
+ health.role.as_deref().unwrap_or_default().trim()
+}
+
+fn health_has_user_identity(health: &OpenVikingHealth) -> bool {
+ let role = health_role(health);
+ let account_id = health.account_id.as_deref().unwrap_or_default().trim();
+ let user_id = health.user_id.as_deref().unwrap_or_default().trim();
+ matches!(role, "user" | "admin") && !account_id.is_empty() && !user_id.is_empty()
+}
+
+fn non_empty_string(value: Option<String>) -> Option<String> {
+ value.and_then(|text| {
+ if text.trim().is_empty() {
+ None
+ } else {
+ Some(text)
+ }
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn command_with_api_key(api_key: Option<&str>) -> ChatCommand {
+ ChatCommand {
+ endpoint: DEFAULT_ENDPOINT.to_string(),
+ api_key: api_key.map(ToString::to_string),
+ account: None,
+ user: None,
+ session: None,
+ sender: "user".to_string(),
+ message: None,
+ stream: true,
+ no_format: false,
+ no_history: false,
+ }
+ }
+
+ #[test]
+ fn auth_uses_configured_api_key() {
+ let command = command_with_api_key(None);
+ let config = Config {
+ api_key: Some("user-key".to_string()),
+ ..Config::default()
+ };
+
+ let auth = command.resolve_auth_from_config(config, None);
+
+ assert_eq!(auth.api_key.as_deref(), Some("user-key"));
+ }
+
+ #[test]
+ fn auth_uses_api_key_override() {
+ let command = command_with_api_key(Some("override-key"));
+ let config = Config {
+ api_key: Some("config-key".to_string()),
+ ..Config::default()
+ };
+
+ let auth = command.resolve_auth_from_config(config, None);
+
+ assert_eq!(auth.api_key.as_deref(), Some("override-key"));
+ }
+
+ #[test]
+ fn trusted_auth_uses_root_api_key_and_identity() {
+ let command = command_with_api_key(None);
+ let config = Config {
+ api_key: Some("stale-user-key".to_string()),
+ root_api_key: Some("root-key".to_string()),
+ account: Some("acme".to_string()),
+ user: Some("alice".to_string()),
+ ..Config::default()
+ };
+
+ let auth = command.resolve_auth_from_config(config, Some("trusted"));
+
+ assert_eq!(auth.api_key.as_deref(), Some("root-key"));
+ assert_eq!(auth.account.as_deref(), Some("acme"));
+ assert_eq!(auth.user.as_deref(), Some("alice"));
+ }
+
+ #[test]
+ fn trusted_auth_honors_explicit_api_key_override_as_root_key() {
+ let command = command_with_api_key(Some("override-root-key"));
+ let config = Config {
+ api_key: Some("stale-user-key".to_string()),
+ root_api_key: Some("root-key".to_string()),
+ account: Some("acme".to_string()),
+ user: Some("alice".to_string()),
+ ..Config::default()
+ };
+
+ let auth = command.resolve_auth_from_config(config, Some("trusted"));
+
+ assert_eq!(auth.api_key.as_deref(), Some("override-root-key"));
+ assert_eq!(auth.account.as_deref(), Some("acme"));
+ assert_eq!(auth.user.as_deref(), Some("alice"));
+ }
+
+ #[test]
+ fn api_key_auth_still_uses_user_key_and_omits_stale_identity() {
+ let command = command_with_api_key(None);
+ let config = Config {
+ api_key: Some("user-key".to_string()),
+ root_api_key: Some("root-key".to_string()),
+ account: Some("stale-account".to_string()),
+ user: Some("stale-user".to_string()),
+ ..Config::default()
+ };
+
+ let auth = command.resolve_auth_from_config(config, Some("api_key"));
+
+ assert_eq!(auth.api_key.as_deref(), Some("user-key"));
+ assert!(auth.account.is_none());
+ assert!(auth.user.is_none());
+ }
+
+ #[test]
+ fn openviking_health_url_is_derived_from_bot_proxy_endpoint() {
+ let command = command_with_api_key(None);
+
+ assert_eq!(
+ command.openviking_health_url().as_deref(),
+ Some("http://localhost:1933/health")
+ );
+ }
+
+ #[test]
+ fn openviking_health_url_ignores_non_bot_proxy_endpoint() {
+ let mut command = command_with_api_key(None);
+ command.endpoint = "http://localhost:18790".to_string();
+
+ assert_eq!(command.openviking_health_url(), None);
+ }
+
+ #[test]
+ fn health_identity_accepts_user_or_admin_only() {
+ let user_health = OpenVikingHealth {
+ auth_mode: Some("api_key".to_string()),
+ role: Some("user".to_string()),
+ account_id: Some("default".to_string()),
+ user_id: Some("alice".to_string()),
+ };
+ let admin_health = OpenVikingHealth {
+ auth_mode: Some("api_key".to_string()),
+ role: Some("admin".to_string()),
+ account_id: Some("default".to_string()),
+ user_id: Some("alice".to_string()),
+ };
+ let root_health = OpenVikingHealth {
+ auth_mode: Some("api_key".to_string()),
+ role: Some("root".to_string()),
+ account_id: Some("default".to_string()),
+ user_id: Some("root".to_string()),
+ };
+ let missing_identity = OpenVikingHealth {
+ auth_mode: Some("api_key".to_string()),
+ role: Some("user".to_string()),
+ account_id: None,
+ user_id: Some("alice".to_string()),
+ };
+
+ assert!(health_has_user_identity(&user_health));
+ assert!(health_has_user_identity(&admin_health));
+ assert!(!health_has_user_identity(&root_health));
+ assert!(!health_has_user_identity(&missing_identity));
+ }
+}
diff --git a/crates/ov_cli/src/commands/content.rs b/crates/ov_cli/src/commands/content.rs
index b9848c6f5..593ccf691 100644
--- a/crates/ov_cli/src/commands/content.rs
+++ b/crates/ov_cli/src/commands/content.rs
@@ -248,7 +248,8 @@ mod tests {
"tags_updated": true
});
- let rendered = super::render_set_tags_result_for_table(&result).map(|value| strip_ansi(&value));
+ let rendered =
+ super::render_set_tags_result_for_table(&result).map(|value| strip_ansi(&value));
assert_eq!(
rendered,
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 6363b7153..14299d066 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -2830,9 +2830,7 @@ async fn main() {
} else {
format!("{}/bot/v1", ctx.config.url)
};
- let api_key = std::env::var("VIKINGBOT_API_KEY")
- .ok()
- .or_else(|| ctx.config.api_key.clone());
+ let api_key = std::env::var("VIKINGBOT_API_KEY").ok();
let cmd = commands::chat::ChatCommand {
endpoint,
api_key,
@@ -3090,9 +3088,7 @@ mod tests {
#[test]
fn cli_find_and_search_reject_removed_peer_id_flag() {
assert!(Cli::try_parse_from(["ov", "find", "invoice", "--peer-id", "peer-a"]).is_err());
- assert!(
- Cli::try_parse_from(["ov", "search", "invoice", "--peer-id", "peer-a"]).is_err()
- );
+ assert!(Cli::try_parse_from(["ov", "search", "invoice", "--peer-id", "peer-a"]).is_err());
}
#[test]
diff --git a/openviking/server/auth/plugins/trusted.py b/openviking/server/auth/plugins/trusted.py
index 2e305103b..af50e5b00 100644
--- a/openviking/server/auth/plugins/trusted.py
+++ b/openviking/server/auth/plugins/trusted.py
@@ -199,6 +199,9 @@ class TrustedAuthPlugin(AuthPlugin):
def requires_api_key_manager(self) -> bool:
return False
+ def can_skip_api_key_for_bot_proxy(self) -> bool:
+ return True
+
def get_request_context_checks(
self,
path: str,
diff --git a/openviking/server/config.py b/openviking/server/config.py
index f063650bc..27fc87423 100644
--- a/openviking/server/config.py
+++ b/openviking/server/config.py
@@ -192,13 +192,30 @@ class ServerConfig(BaseModel):
- If root_api_key is configured (non-empty) and auth_mode is None: api_key
- If root_api_key is not configured and auth_mode is None: dev
"""
- if self.auth_mode is not None:
- return self.auth_mode
- if self.root_api_key is not None and self.root_api_key != "":
+ auth_mode_text = str(self.auth_mode).strip() if self.auth_mode is not None else ""
+ if auth_mode_text:
+ return auth_mode_text
+
+ if self.root_api_key is not None and str(self.root_api_key).strip():
return AuthMode.API_KEY.value
return AuthMode.DEV.value
+def get_server_url_from_server_data(server_data: object) -> str:
+ """Return the loopback URL clients use for the configured OpenViking server."""
+ if isinstance(server_data, dict):
+ host_value = server_data.get("host")
+ port_value = server_data.get("port")
+ else:
+ host_value = getattr(server_data, "host", None)
+ port_value = getattr(server_data, "port", None)
+ host = str(host_value or "127.0.0.1").strip()
+ if ":" in host and not (host.startswith("[") and host.endswith("]")):
+ host = f"[{host}]"
+ port = str(port_value or "1933").strip()
+ return f"http://{host}:{port}"
+
+
def load_server_config(config_path: Optional[str] = None) -> ServerConfig:
"""Load server configuration from ov.conf.
diff --git a/openviking/server/routers/bot.py b/openviking/server/routers/bot.py
index e99d04255..d0672ebba 100644
--- a/openviking/server/routers/bot.py
+++ b/openviking/server/routers/bot.py
@@ -11,7 +11,8 @@ import httpx
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.responses import StreamingResponse
-from openviking.server.auth import get_request_context
+from openviking.server.auth import _auth_mode, get_request_context
+from openviking.server.config import get_server_url_from_server_data
from openviking.server.identity import RequestContext
from openviking_cli.utils.logger import get_logger
@@ -71,6 +72,27 @@ def _extract_forward_api_key(request: Request) -> str:
return ""
+def _build_openviking_connection(
+ *,
+ api_key: str,
+ ctx: RequestContext,
+ effective_auth_mode: str,
+ server_url: str,
+) -> dict:
+ connection = {
+ "account_id": ctx.user.account_id,
+ "user_id": ctx.user.user_id,
+ "agent_id": DEFAULT_BOT_AGENT_ID,
+ "role": getattr(ctx.role, "value", str(ctx.role)),
+ "api_key_type": "root" if effective_auth_mode == "trusted" else "user",
+ "server_url": server_url,
+ "namespace_policy": dict(DEFAULT_NAMESPACE_POLICY),
+ }
+ if api_key:
+ connection["api_key"] = api_key
+ return connection
+
+
def _attach_openviking_connection(
body: dict,
request: Request,
@@ -84,24 +106,31 @@ def _attach_openviking_connection(
"""
enriched = dict(body)
api_key = _extract_forward_api_key(request)
- config = getattr(request.app.state, "config", None)
plugin = getattr(request.app.state, "auth_plugin", None)
+ effective_auth_mode = _auth_mode(request)
+ server_url = get_server_url_from_server_data(getattr(request.app.state, "config", None))
if not api_key:
if plugin is not None and plugin.can_skip_api_key_for_bot_proxy():
+ if effective_auth_mode == "trusted":
+ enriched["openviking_connection"] = _build_openviking_connection(
+ api_key="",
+ ctx=ctx,
+ effective_auth_mode=effective_auth_mode,
+ server_url=server_url,
+ )
+ return enriched
enriched.setdefault("user_id", ctx.user.user_id)
return enriched
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Bot proxy requires a forwardable OpenViking API key.",
)
- enriched["openviking_connection"] = {
- "api_key": api_key,
- "account_id": ctx.user.account_id,
- "user_id": ctx.user.user_id,
- "agent_id": DEFAULT_BOT_AGENT_ID,
- "role": getattr(ctx.role, "value", str(ctx.role)),
- "namespace_policy": dict(DEFAULT_NAMESPACE_POLICY),
- }
+ enriched["openviking_connection"] = _build_openviking_connection(
+ api_key=api_key,
+ ctx=ctx,
+ effective_auth_mode=effective_auth_mode,
+ server_url=server_url,
+ )
return enriched
diff --git a/openviking_cli/doctor.py b/openviking_cli/doctor.py
index 87c516d3c..cb86c8385 100644
--- a/openviking_cli/doctor.py
+++ b/openviking_cli/doctor.py
@@ -4,7 +4,8 @@
Unlike ``ov health`` (which pings a running server), ``openviking-server doctor`` checks
local prerequisites without requiring a server: config file, Python version,
-native vector engine, AGFS, embedding provider, VLM provider, and disk space.
+native vector engine, AGFS, embedding provider, VLM provider, VikingBot auth,
+and disk space.
"""
from __future__ import annotations
@@ -17,12 +18,20 @@ import platform
import shutil
import sys
from pathlib import Path
-from typing import Any, Optional
+from typing import Any, Literal, Optional
+from openviking.server.config import (
+ ServerConfig,
+ get_server_url_from_server_data,
+)
from openviking_cli.utils.config.config_loader import resolve_config_path
from openviking_cli.utils.config.consts import OPENVIKING_CONFIG_ENV
+from openviking_cli.utils.config.ovcli_config import load_ovcli_config
from openviking_cli.utils.config.vlm_config import VLMConfig
+CheckStatus = Literal["pass", "warn", "fail"]
+CheckResult = tuple[bool | CheckStatus, str, Optional[str]]
+
# ANSI helpers (disabled when stdout is not a terminal)
_USE_COLOR = hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
@@ -62,6 +71,18 @@ def _load_config_json(config_path: Path) -> Optional[dict]:
return None
+def _normalize_check_result(result: CheckResult) -> tuple[CheckStatus, str, Optional[str]]:
+ """Normalize legacy bool checks and newer tri-state checks."""
+ status, detail, fix = result
+ if status is True:
+ return "pass", detail, fix
+ if status is False:
+ return "fail", detail, fix
+ if status in {"pass", "warn", "fail"}:
+ return status, detail, fix
+ return "fail", f"Invalid check status: {status!r}", None
+
+
def check_config() -> tuple[bool, str, Optional[str]]:
"""Validate ov.conf exists and is valid JSON with required sections."""
config_path = _find_config()
@@ -418,6 +439,146 @@ def check_ollama() -> tuple[bool, str, Optional[str]]:
)
+def _is_placeholder_secret(value: str) -> bool:
+ stripped = value.strip()
+ return (
+ not stripped
+ or stripped.startswith("{")
+ or stripped.startswith("<")
+ or stripped.startswith("$")
+ )
+
+
+def _load_ovcli_api_key_for_doctor() -> str:
+ try:
+ cli_config = load_ovcli_config()
+ except ValueError:
+ return ""
+ if cli_config is None:
+ return ""
+ return str(getattr(cli_config, "api_key", "") or "").strip()
+
+
+def _bot_openviking_server_url(ov_server: dict[str, Any], server: dict[str, Any]) -> str:
+ configured_url = str(ov_server.get("server_url") or "").strip()
+ if configured_url:
+ return configured_url
+ return get_server_url_from_server_data(server)
+
+
+def check_vikingbot() -> CheckResult:
+ """Check VikingBot OpenViking Server auth config.
+
+ VikingBot is optional, so missing auth configuration is a warning rather
+ than a hard failure. In api_key mode VikingBot must use a User API key; in
+ trusted mode it uses a root API key through bot.ov_server.api_key plus
+ trusted identity headers.
+ """
+ config_path = _find_config()
+ if config_path is None:
+ return "warn", "Cannot check (no config file)", None
+
+ data = _load_config_json(config_path)
+ if data is None:
+ return "warn", "Cannot check (config unreadable)", None
+
+ server = data.get("server") if isinstance(data.get("server"), dict) else {}
+ auth_mode = ServerConfig(
+ auth_mode=server.get("auth_mode"),
+ root_api_key=server.get("root_api_key"),
+ ).get_effective_auth_mode()
+ server_root_api_key = str(server.get("root_api_key") or "").strip()
+
+ bot = data.get("bot")
+ if not isinstance(bot, dict):
+ bot = {}
+
+ ov_server = bot.get("ov_server")
+ if not isinstance(ov_server, dict):
+ ov_server = {}
+
+ api_key = str(ov_server.get("api_key") or "").strip()
+ root_api_key = str(ov_server.get("root_api_key") or "").strip()
+ explicit_api_key_type = str(ov_server.get("api_key_type") or "").strip().lower()
+ bot_server_url = _bot_openviking_server_url(ov_server, server)
+ bot_uses_current_server = not str(ov_server.get("server_url") or "").strip()
+ if explicit_api_key_type:
+ api_key_type = explicit_api_key_type
+ elif bot_uses_current_server:
+ api_key_type = "root" if auth_mode == "trusted" else "user"
+ else:
+ api_key_type = "user"
+
+ if api_key_type == "root":
+ if bot_uses_current_server and auth_mode != "trusted":
+ return (
+ "warn",
+ f"bot.ov_server targets {bot_server_url} with api_key_type=root, "
+ f"but that server is auth_mode={auth_mode}",
+ f"To use {bot_server_url}, set bot.ov_server.api_key_type to 'user' "
+ "and configure a User API key in bot.ov_server.api_key or ovcli.conf api_key.\n"
+ "To use root mode, change that OpenViking server to server.auth_mode='trusted'.\n"
+ "To use another trusted server, set bot.ov_server.server_url to that server "
+ "and keep api_key_type='root'.",
+ )
+ trusted_root_key = (
+ server_root_api_key if bot_uses_current_server and auth_mode == "trusted" else api_key
+ )
+ if _is_placeholder_secret(trusted_root_key):
+ if root_api_key:
+ return (
+ "warn",
+ "bot.ov_server.root_api_key is deprecated and ignored",
+ "Move the root API key to bot.ov_server.api_key and keep "
+ "bot.ov_server.api_key_type='root'",
+ )
+ if auth_mode == "trusted" and not ov_server:
+ return (
+ "warn",
+ "server.auth_mode=trusted without server.root_api_key",
+ "Configure server.root_api_key for VikingBot trusted OpenViking calls "
+ "outside localhost",
+ )
+ return (
+ "warn",
+ "bot.ov_server.api_key_type=root without root API key",
+ "Configure bot.ov_server.api_key with a root API key for trusted "
+ "OpenViking access",
+ )
+ return "pass", "bot.ov_server configured for trusted OpenViking auth", None
+
+ if bot_uses_current_server and auth_mode == "dev":
+ return "pass", "VikingBot aligned with dev OpenViking auth", None
+
+ ovcli_api_key = "" if not _is_placeholder_secret(api_key) else _load_ovcli_api_key_for_doctor()
+ if not _is_placeholder_secret(api_key):
+ return "pass", "bot.ov_server.api_key configured for api_key mode", None
+ if not _is_placeholder_secret(ovcli_api_key):
+ return "pass", "ovcli.conf api_key configured for VikingBot api_key mode", None
+
+ if _is_placeholder_secret(api_key):
+ if root_api_key:
+ return (
+ "warn",
+ "bot.ov_server.root_api_key is deprecated and ignored",
+ "Use bot.ov_server.api_key for the active key. In api_key mode configure "
+ "a User API key in bot.ov_server.api_key or ovcli.conf api_key.",
+ )
+ if not bot or not ov_server:
+ return (
+ "warn",
+ "bot.ov_server not configured and ovcli.conf api_key not configured",
+ "Configure bot.ov_server.api_key or ovcli.conf api_key with an "
+ "OpenViking User API key",
+ )
+ return (
+ "warn",
+ "bot.ov_server.api_key and ovcli.conf api_key not configured",
+ "Create an OpenViking User API key and set bot.ov_server.api_key or ovcli.conf api_key",
+ )
+ return "pass", "bot.ov_server.api_key configured for api_key mode", None
+
+
def check_disk() -> tuple[bool, str, Optional[str]]:
"""Check free disk space in the workspace directory."""
config_path = _find_config()
@@ -457,6 +618,7 @@ _CHECKS = [
("Embedding", check_embedding),
("VLM", check_vlm),
("Ollama", check_ollama),
+ ("VikingBot", check_vikingbot),
("Disk", check_disk),
]
@@ -469,18 +631,26 @@ def run_doctor() -> int:
print("\nOpenViking Doctor\n")
failed = 0
+ warned = 0
max_label = max(len(label) for label, _ in _CHECKS)
for label, check_fn in _CHECKS:
try:
- ok, detail, fix = check_fn()
+ status_key, detail, fix = _normalize_check_result(check_fn())
except Exception as exc:
- ok, detail, fix = False, f"Unexpected error: {type(exc).__name__}: {exc}", None
+ status_key, detail, fix = "fail", f"Unexpected error: {type(exc).__name__}: {exc}", None
pad = " " * (max_label - len(label) + 1)
- if ok:
+ if status_key == "pass":
status = _green("PASS")
print(f" {label}:{pad}{status} {detail}")
+ elif status_key == "warn":
+ status = _yellow("WARN")
+ print(f" {label}:{pad}{status} {detail}")
+ warned += 1
+ if fix:
+ for line in fix.split("\n"):
+ print(f" {' ' * (max_label + 2)}{_dim('Fix: ' + line)}")
else:
status = _red("FAIL")
print(f" {label}:{pad}{status} {detail}")
@@ -494,6 +664,10 @@ def run_doctor() -> int:
print(f" {_red(f'{failed} check(s) failed.')} See above for fix suggestions.\n")
return 1
+ if warned:
+ print(f" {_yellow(f'{warned} warning(s).')} Review the suggestions above.\n")
+ return 0
+
print(f" {_green('All checks passed.')}\n")
return 0
diff --git a/openviking_cli/utils/config/__init__.py b/openviking_cli/utils/config/__init__.py
index 3b760d7e8..81c17e564 100644
--- a/openviking_cli/utils/config/__init__.py
+++ b/openviking_cli/utils/config/__init__.py
@@ -49,6 +49,7 @@ from .consts import (
OPENVIKING_WRITE_CHECK_URI_ENV,
SYSTEM_CONFIG_DIR,
)
+from . import embedding_config
from .embedding_config import EmbeddingConfig
from .log_config import LogConfig
from .open_viking_config import (
diff --git a/tests/cli/test_doctor.py b/tests/cli/test_doctor.py
index 684cf0676..aad681983 100644
--- a/tests/cli/test_doctor.py
+++ b/tests/cli/test_doctor.py
@@ -9,8 +9,11 @@ import json
import os
import sys
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import patch
+import pytest
+
from openviking_cli.doctor import (
_probe_embedding_provider,
check_agfs,
@@ -20,6 +23,7 @@ from openviking_cli.doctor import (
check_native_engine,
check_ollama,
check_python,
+ check_vikingbot,
check_vlm,
run_doctor,
)
@@ -721,6 +725,277 @@ class TestCheckOllama:
assert "ollama serve" in fix
+class TestCheckVikingBot:
+ @pytest.fixture(autouse=True)
+ def _no_ovcli_config(self, monkeypatch):
+ monkeypatch.setattr("openviking_cli.doctor.load_ovcli_config", lambda: None)
+
+ def test_pass_with_user_api_key(self, tmp_path: Path):
+ config = tmp_path / "ov.conf"
+ config.write_text(
+ json.dumps(
+ {
+ "server": {"root_api_key": "root-key"},
+ "bot": {
+ "ov_server": {
+ "api_key": "user-key",
+ "api_key_type": "user",
+ }
+ }
+ }
+ )
+ )
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "pass"
+ assert "api_key mode" in detail
+ assert fix is None
+
+ def test_pass_dev_mode_without_bot_ov_server(self, tmp_path: Path):
+ config = tmp_path / "ov.conf"
+ config.write_text(json.dumps({"bot": {}}))
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "pass"
+ assert "dev OpenViking auth" in detail
+ assert fix is None
+
+ def test_pass_dev_mode_with_ignored_bot_api_key(self, tmp_path: Path):
+ config = tmp_path / "ov.conf"
+ config.write_text(
+ json.dumps({"bot": {"ov_server": {"api_key": "stale-key"}}})
+ )
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "pass"
+ assert "dev OpenViking auth" in detail
+ assert fix is None
+
+ def test_warn_when_bot_ov_server_missing_in_api_key_mode(self, tmp_path: Path):
+ config = tmp_path / "ov.conf"
+ config.write_text(json.dumps({"server": {"root_api_key": "root-key"}, "bot": {}}))
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "warn"
+ assert "bot.ov_server not configured" in detail
+ assert "bot.ov_server.api_key" in fix
+
+ def test_warn_when_user_api_key_missing(self, tmp_path: Path):
+ config = tmp_path / "ov.conf"
+ config.write_text(
+ json.dumps(
+ {
+ "server": {"root_api_key": "root-key"},
+ "bot": {"ov_server": {"api_key_type": "user"}},
+ }
+ )
+ )
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "warn"
+ assert "api_key" in detail
+ assert "ovcli.conf" in detail
+ assert "User API key" in fix
+
+ def test_pass_with_ovcli_user_api_key_fallback(self, tmp_path: Path, monkeypatch):
+ config = tmp_path / "ov.conf"
+ config.write_text(
+ json.dumps({"server": {"root_api_key": "root-key"}, "bot": {"ov_server": {}}})
+ )
+ monkeypatch.setattr(
+ "openviking_cli.doctor.load_ovcli_config",
+ lambda: SimpleNamespace(api_key="ovcli-user-key"),
+ )
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "pass"
+ assert "ovcli.conf api_key" in detail
+ assert "ovcli-user-key" not in detail
+ assert fix is None
+
+ def test_warn_with_legacy_root_api_key(self, tmp_path: Path):
+ config = tmp_path / "ov.conf"
+ config.write_text(
+ json.dumps(
+ {
+ "server": {"root_api_key": "server-root-key"},
+ "bot": {"ov_server": {"root_api_key": "root-key"}},
+ }
+ )
+ )
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "warn"
+ assert "root_api_key is deprecated and ignored" in detail
+ assert "bot.ov_server.api_key" in fix
+
+ def test_pass_with_root_api_key_type_for_explicit_server_url(self, tmp_path: Path):
+ config = tmp_path / "ov.conf"
+ config.write_text(
+ json.dumps(
+ {
+ "bot": {
+ "ov_server": {
+ "server_url": "https://trusted.example",
+ "api_key": "root-looking-key",
+ "api_key_type": "root",
+ }
+ }
+ }
+ )
+ )
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "pass"
+ assert "trusted OpenViking auth" in detail
+ assert fix is None
+
+ def test_warn_when_external_root_key_omits_root_api_key_type(self, tmp_path: Path):
+ config = tmp_path / "ov.conf"
+ config.write_text(
+ json.dumps(
+ {
+ "bot": {
+ "ov_server": {
+ "server_url": "https://trusted.example",
+ "root_api_key": "root-key",
+ }
+ }
+ }
+ )
+ )
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "warn"
+ assert "root_api_key is deprecated and ignored" in detail
+ assert "api_key_type=root" not in detail
+ assert "User API key" in fix
+
+ def test_warn_when_root_api_key_type_inherits_api_key_server(self, tmp_path: Path):
+ config = tmp_path / "ov.conf"
+ config.write_text(
+ json.dumps(
+ {
+ "server": {"root_api_key": "root-key"},
+ "bot": {
+ "ov_server": {
+ "api_key_type": "root",
+ "api_key": "root-key",
+ }
+ },
+ }
+ )
+ )
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "warn"
+ assert "api_key_type=root" in detail
+ assert "http://127.0.0.1:1933" in detail
+ assert "auth_mode=api_key" in detail
+ assert "To use http://127.0.0.1:1933" in fix
+ assert "bot.ov_server.api_key_type to 'user'" in fix
+ assert "User API key" in fix
+ assert "server.auth_mode='trusted'" in fix
+ assert "bot.ov_server.server_url" in fix
+ assert "api_key_type='root'" in fix
+
+ def test_pass_when_explicit_same_url_is_treated_as_external_server(self, tmp_path: Path):
+ config = tmp_path / "ov.conf"
+ config.write_text(
+ json.dumps(
+ {
+ "server": {"host": "127.0.0.1", "port": 1933, "root_api_key": "root-key"},
+ "bot": {
+ "ov_server": {
+ "server_url": "http://localhost:1933",
+ "api_key_type": "root",
+ "api_key": "root-key",
+ }
+ },
+ }
+ )
+ )
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "pass"
+ assert "trusted OpenViking auth" in detail
+ assert fix is None
+
+ def test_pass_with_trusted_root_api_key(self, tmp_path: Path):
+ config = tmp_path / "ov.conf"
+ config.write_text(
+ json.dumps(
+ {
+ "server": {
+ "auth_mode": "trusted",
+ "root_api_key": "root-key",
+ }
+ }
+ )
+ )
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "pass"
+ assert "trusted OpenViking auth" in detail
+ assert fix is None
+
+ def test_pass_current_trusted_prefers_server_root_key(self, tmp_path: Path):
+ config = tmp_path / "ov.conf"
+ config.write_text(
+ json.dumps(
+ {
+ "server": {
+ "auth_mode": "trusted",
+ "root_api_key": "server-root-key",
+ },
+ "bot": {"ov_server": {"api_key": "stale-bot-key"}},
+ }
+ )
+ )
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "pass"
+ assert "trusted OpenViking auth" in detail
+ assert fix is None
+
+ def test_warn_with_trusted_missing_root_api_key(self, tmp_path: Path):
+ config = tmp_path / "ov.conf"
+ config.write_text(json.dumps({"server": {"auth_mode": "trusted"}}))
+
+ with patch("openviking_cli.doctor._find_config", return_value=config):
+ status, detail, fix = check_vikingbot()
+
+ assert status == "warn"
+ assert "server.auth_mode=trusted" in detail
+ assert "server.root_api_key" in fix
+
+
class TestCheckDisk:
def test_pass_normal_disk(self):
ok, detail, fix = check_disk()
@@ -758,6 +1033,18 @@ class TestRunDoctor:
captured = capsys.readouterr()
assert "FAIL" in captured.out
+ def test_returns_zero_on_warning_only(self, capsys):
+ with patch(
+ "openviking_cli.doctor._CHECKS",
+ [("Warning", lambda: ("warn", "needs attention", "fix it"))],
+ ):
+ code = run_doctor()
+
+ assert code == 0
+ captured = capsys.readouterr()
+ assert "WARN" in captured.out
+ assert "1 warning(s)" in captured.out
+
def _import_fail(blocked_name: str):
"""Return an __import__ replacement that blocks one specific module."""
diff --git a/tests/server/test_bot_proxy_auth.py b/tests/server/test_bot_proxy_auth.py
index 67f4844a2..553517c59 100644
--- a/tests/server/test_bot_proxy_auth.py
+++ b/tests/server/test_bot_proxy_auth.py
@@ -10,6 +10,7 @@ import pytest
from fastapi import FastAPI
import openviking.server.routers.bot as bot_router_module
+from openviking.server.auth.plugins import DevAuthPlugin, TrustedAuthPlugin
from openviking.server.config import ServerConfig
from openviking.server.identity import AuthMode
@@ -63,6 +64,7 @@ async def test_feedback_proxy_forwards_request(monkeypatch):
app = FastAPI()
app.state.config = SimpleNamespace(get_effective_auth_mode=lambda: AuthMode.DEV)
+ app.state.auth_plugin = DevAuthPlugin()
app.include_router(bot_router_module.router, prefix="/bot/v1")
transport = httpx.ASGITransport(app=app)
@@ -117,7 +119,8 @@ async def test_chat_proxy_attaches_authenticated_openviking_connection(monkeypat
monkeypatch.setattr(bot_router_module, "_create_bot_proxy_client", lambda: FakeClient())
app = FastAPI()
- app.state.config = ServerConfig(auth_mode="trusted")
+ app.state.config = ServerConfig(auth_mode="trusted", host="127.0.0.1", port=1944)
+ app.state.auth_plugin = TrustedAuthPlugin()
app.include_router(bot_router_module.router, prefix="/bot/v1")
transport = httpx.ASGITransport(app=app)
@@ -140,6 +143,8 @@ async def test_chat_proxy_attaches_authenticated_openviking_connection(monkeypat
"user_id": "alice",
"agent_id": "web-playground",
"role": "user",
+ "api_key_type": "root",
+ "server_url": "http://127.0.0.1:1944",
"namespace_policy": {
"isolate_user_scope_by_agent": False,
"isolate_agent_scope_by_user": False,
@@ -150,7 +155,19 @@ async def test_chat_proxy_attaches_authenticated_openviking_connection(monkeypat
@pytest.mark.asyncio
-async def test_chat_proxy_rejects_authenticated_request_without_forwardable_api_key(monkeypatch):
+async def test_chat_proxy_forwards_trusted_request_without_root_api_key(monkeypatch):
+ forwarded = {}
+
+ class FakeResponse:
+ status_code = 200
+ text = '{"session_id": "session-1", "message": "ok"}'
+
+ def raise_for_status(self):
+ return None
+
+ def json(self):
+ return {"session_id": "session-1", "message": "ok"}
+
class FakeClient:
async def __aenter__(self):
return self
@@ -158,14 +175,20 @@ async def test_chat_proxy_rejects_authenticated_request_without_forwardable_api_
async def __aexit__(self, exc_type, exc, tb):
return None
- async def post(self, *args, **kwargs):
- raise AssertionError("bot gateway should not be called without a forwardable key")
+ async def post(self, url, json, headers, timeout):
+ forwarded["url"] = url
+ forwarded["json"] = json
+ forwarded["headers"] = headers
+ forwarded["timeout"] = timeout
+ return FakeResponse()
monkeypatch.setattr(bot_router_module, "BOT_API_URL", "http://127.0.0.1:18790")
+ monkeypatch.setattr(bot_router_module, "BOT_API_KEY", "")
monkeypatch.setattr(bot_router_module, "_create_bot_proxy_client", lambda: FakeClient())
app = FastAPI()
- app.state.config = ServerConfig(auth_mode="trusted")
+ app.state.config = ServerConfig(auth_mode="trusted", host="127.0.0.1", port=1955)
+ app.state.auth_plugin = TrustedAuthPlugin()
app.include_router(bot_router_module.router, prefix="/bot/v1")
transport = httpx.ASGITransport(app=app)
@@ -179,5 +202,20 @@ async def test_chat_proxy_rejects_authenticated_request_without_forwardable_api_
json={"message": "hello"},
)
- assert response.status_code == 401
- assert "forwardable OpenViking API key" in response.text
+ assert response.status_code == 200
+ assert forwarded["url"] == "http://127.0.0.1:18790/bot/v1/chat"
+ assert "api_key" not in forwarded["json"]["openviking_connection"]
+ assert forwarded["json"]["openviking_connection"] == {
+ "account_id": "acct",
+ "user_id": "alice",
+ "agent_id": "web-playground",
+ "role": "user",
+ "api_key_type": "root",
+ "server_url": "http://127.0.0.1:1955",
+ "namespace_policy": {
+ "isolate_user_scope_by_agent": False,
+ "isolate_agent_scope_by_user": False,
+ },
+ }
+ assert "X-Gateway-Token" not in forwarded["headers"]
+ assert forwarded["timeout"] == 300.0
diff --git a/tests/test_server_config_loader.py b/tests/test_server_config_loader.py
index 5ffb145c5..edd5a263a 100644
--- a/tests/test_server_config_loader.py
+++ b/tests/test_server_config_loader.py
@@ -5,7 +5,12 @@ import json
import pytest
-from openviking.server.config import load_bot_gateway_token, load_server_config
+from openviking.server.config import (
+ ServerConfig,
+ get_server_url_from_server_data,
+ load_bot_gateway_token,
+ load_server_config,
+)
def test_load_server_config_rejects_unknown_field(tmp_path):
@@ -93,6 +98,36 @@ def test_load_bot_gateway_token_reads_token_from_bot_gateway_section(tmp_path):
assert load_bot_gateway_token(str(config_path)) == "gateway-token"
+def test_server_config_get_effective_auth_mode():
+ assert ServerConfig(auth_mode="trusted").get_effective_auth_mode() == "trusted"
+ assert ServerConfig(root_api_key="root-key").get_effective_auth_mode() == "api_key"
+ assert ServerConfig().get_effective_auth_mode() == "dev"
+
+
+def test_get_server_url_from_server_data_uses_server_host_and_port():
+ server = {"host": "127.0.0.1", "port": 1933}
+
+ assert get_server_url_from_server_data(server) == "http://127.0.0.1:1933"
+
+
+def test_get_server_url_from_server_config_uses_runtime_host_and_port():
+ config = ServerConfig(host="127.0.0.1", port=1944)
+
+ assert get_server_url_from_server_data(config) == "http://127.0.0.1:1944"
+
+
+def test_get_server_url_from_server_data_brackets_ipv6_literal():
+ server = {"host": "::1", "port": 1933}
+
+ assert get_server_url_from_server_data(server) == "http://[::1]:1933"
+
+
+def test_get_server_url_from_server_config_brackets_ipv6_literal():
+ config = ServerConfig(host="::1", port=1944)
+
+ assert get_server_url_from_server_data(config) == "http://[::1]:1944"
+
+
def test_load_server_config_preserves_metrics_account_dimension_fields(tmp_path):
config_path = tmp_path / "ov.conf"
config_path.write_text(