Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(bot):Fix bot api-channel auth check (#1640)
yeshion2333331c33d7ce985
diff --git a/bot/demo/werewolf/README.md b/bot/demo/werewolf/README.mdindex da0435202..3be8b2fc2 100644--- a/bot/demo/werewolf/README.md+++ b/bot/demo/werewolf/README.md@@ -61,7 +61,7 @@ openviking-server \--host 127.0.0.1 \--port 1933 \--with-bot \- --bot-url http://localhost:18790+ --bot-port 18790```### 3.2 启动狼人杀 UI 服务diff --git a/bot/demo/werewolf/start_werewolf_demo.py b/bot/demo/werewolf/start_werewolf_demo.pyindex 5084749ce..85771cfac 100644--- a/bot/demo/werewolf/start_werewolf_demo.py+++ b/bot/demo/werewolf/start_werewolf_demo.py@@ -4,6 +4,7 @@ import argparseimport jsonimport osimport shutil+from urllib.parse import urlparseimport subprocessimport sysimport time@@ -253,8 +254,8 @@ def start_processes(args: argparse.Namespace, config_path: Path) -> int:"--port",str(args.server_port),"--with-bot",- "--bot-url",- args.vikingbot_url,+ "--bot-port",+ str(urlparse(args.vikingbot_url).port or 18790),]werewolf_cmd = [sys.executable,diff --git a/bot/docs/rfc-openviking-cli-ov-chat.md b/bot/docs/rfc-openviking-cli-ov-chat.mdindex 0e43f620e..309e45dff 100644--- a/bot/docs/rfc-openviking-cli-ov-chat.md+++ b/bot/docs/rfc-openviking-cli-ov-chat.md@@ -329,8 +329,8 @@ Vikingbot 的配置项统一放在 `ov.conf` 的 `bot` 字段下:# Enable Bot API proxyopenviking-server --with-bot-# Custom bot URL-openviking-server --with-bot --bot-url http://localhost:8080+# Custom bot port+openviking-server --with-bot --bot-port 8080# With config fileopenviking-server --config /path/to/ov.confdiff --git a/bot/scripts/restart_openviking_server.sh b/bot/scripts/restart_openviking_server.shindex 167d5a0a7..38171f9ef 100755--- a/bot/scripts/restart_openviking_server.sh+++ b/bot/scripts/restart_openviking_server.sh@@ -1,13 +1,13 @@#!/bin/bash# Restart OpenViking Server with Bot API enabled-# Usage: ./restart_openviking_server.sh [--port PORT] [--bot-url URL]+# Usage: ./restart_openviking_server.sh [--port PORT] [--bot-port PORT]set -e# Default valuesPORT="1933"-BOT_URL="http://localhost:18790"+BOT_PORT="18790"# Parse argumentswhile [[ $# -gt 0 ]]; do@@ -16,29 +16,22 @@ while [[ $# -gt 0 ]]; doPORT="$2"shift 2;;- --bot-url)- BOT_URL="$2"+ --bot-port)+ BOT_PORT="$2"shift 2;;*)echo "Unknown option: $1"- echo "Usage: $0 [--port PORT] [--bot-url URL]"+ echo "Usage: $0 [--port PORT] [--bot-port PORT]"exit 1;;esacdone-# Parse Bot URL to extract port-BOT_PORT=$(echo "$BOT_URL" | sed -n 's/.*:\([0-9]*\).*/\1/p')-if [ -z "$BOT_PORT" ]; then- BOT_PORT="18790"-fi-echo "=========================================="echo "Restarting OpenViking Server with Bot API"echo "=========================================="echo "OpenViking Server Port: $PORT"-echo "Bot URL: $BOT_URL"echo "Bot Port: $BOT_PORT"echo ""@@ -88,20 +81,20 @@ echo " ✓ Port $PORT is free"# Step 2: Start openviking-server with --with-botecho ""echo "Step 2: Starting openviking-server with Bot API..."-echo " Command: openviking-server --with-bot --port $PORT --bot-url $BOT_URL"+echo " Command: openviking-server --with-bot --port $PORT --bot-port $BOT_PORT"echo ""# Start in background and log to file#nohup openviking-server \- --with-bot \- --port "$PORT" \- --bot-url "$BOT_URL" \- > /tmp/openviking-server.log 2>&1 &+# --with-bot \+# --port "$PORT" \+# --bot-port "$BOT_PORT" \+# > /tmp/openviking-server.log 2>&1 &openviking-server \--with-bot \--port "$PORT" \- --bot-url "$BOT_URL"+ --bot-port "$BOT_PORT"SERVER_PID=$!@@ -147,7 +140,7 @@ tail -20 /tmp/openviking-server.log 2>/dev/null || echo "(No logs available)"echo ""echo "Troubleshooting:"echo " 1. Check if port $PORT is in use: lsof -i :$PORT"-echo " 2. Check Vikingbot is running on $BOT_URL"+echo " 2. Check Vikingbot is running on port $BOT_PORT"echo " 3. Check logs: tail -f /tmp/openviking-server.log"echo ""exit 1diff --git a/bot/scripts/test_restart_openviking_server.sh b/bot/scripts/test_restart_openviking_server.shindex 547d62a6d..7b6396beb 100755--- a/bot/scripts/test_restart_openviking_server.sh+++ b/bot/scripts/test_restart_openviking_server.sh@@ -1,13 +1,13 @@#!/bin/bash# Restart OpenViking Server with Test Config (~/.openviking_test/ov.conf)-# Usage: ./test_restart_openviking_server.sh [--port PORT] [--bot-url URL]+# Usage: ./test_restart_openviking_server.sh [--port PORT] [--bot-port PORT]set -e# Default valuesPORT="1934"-BOT_URL="http://localhost:18790"+BOT_PORT="18790"TEST_CONFIG="$HOME/.openviking_test/ov.conf"TEST_DATA_DIR="$HOME/.openviking_test/data"@@ -18,29 +18,22 @@ while [[ $# -gt 0 ]]; doPORT="$2"shift 2;;- --bot-url)- BOT_URL="$2"+ --bot-port)+ BOT_PORT="$2"shift 2;;*)echo "Unknown option: $1"- echo "Usage: $0 [--port PORT] [--bot-url URL]"+ echo "Usage: $0 [--port PORT] [--bot-port PORT]"exit 1;;esacdone-# Parse Bot URL to extract port-BOT_PORT=$(echo "$BOT_URL" | sed -n 's/.*:\([0-9]*\).*/\1/p')-if [ -z "$BOT_PORT" ]; then- BOT_PORT="18790"-fi-echo "=========================================="echo "Restarting OpenViking Server (TEST MODE)"echo "=========================================="echo "OpenViking Server Port: $PORT"-echo "Bot URL: $BOT_URL"echo "Bot Port: $BOT_PORT"echo "Config File: $TEST_CONFIG"echo "Data Dir: $TEST_DATA_DIR"@@ -107,14 +100,14 @@ echo " ✓ Using config: $TEST_CONFIG"echo ""echo "Step 5: Starting openviking-server with TEST config..."echo " Config: $TEST_CONFIG"-echo " Command: OPENVIKING_CONFIG_FILE=$TEST_CONFIG openviking-server --with-bot --port $PORT --bot-url $BOT_URL"+echo " Command: OPENVIKING_CONFIG_FILE=$TEST_CONFIG openviking-server --with-bot --port $PORT --bot-port $BOT_PORT"echo ""# Set environment variable to use test configexport OPENVIKING_CONFIG_FILE="$TEST_CONFIG"# Start server-openviking-server --port "$PORT"+openviking-server --with-bot --port "$PORT" --bot-port "$BOT_PORT"SERVER_PID=$!echo " Server PID: $SERVER_PID"@@ -160,7 +153,7 @@ echo "Data dir: $TEST_DATA_DIR"echo ""echo "Troubleshooting:"echo " 1. Check if port $PORT is in use: lsof -i :$PORT"-echo " 2. Check Vikingbot is running on $BOT_URL"+echo " 2. Check Vikingbot is running on port $BOT_PORT"echo " 3. Verify config file exists: $TEST_CONFIG"echo ""exit 1diff --git a/bot/tests/test_gateway_startup_security.py b/bot/tests/test_gateway_startup_security.pynew file mode 100644index 000000000..9d5ee7656--- /dev/null+++ b/bot/tests/test_gateway_startup_security.py@@ -0,0 +1,43 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++from types import SimpleNamespace++import pytest+from vikingbot.cli import commands+++class _AbortCalled(RuntimeError):+ pass+++def test_gateway_rejects_non_localhost_without_token(monkeypatch):+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="0.0.0.0", port=18790, token=""),+ )++ monkeypatch.setattr(commands, "ensure_config", lambda _: config)++ def _abort(*args, **kwargs):+ raise AssertionError("_abort_if_port_in_use should not be reached")++ monkeypatch.setattr(commands, "_abort_if_port_in_use", _abort)++ with pytest.raises(SystemExit):+ commands.gateway(port=None, host=None, verbose=False, config_path=None)+++def test_gateway_allows_non_localhost_with_token(monkeypatch):+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="0.0.0.0", port=18790, token="secret"),+ )++ monkeypatch.setattr(commands, "ensure_config", lambda _: config)++ def _abort(*args, **kwargs):+ raise _AbortCalled++ monkeypatch.setattr(commands, "_abort_if_port_in_use", _abort)++ with pytest.raises(_AbortCalled):+ commands.gateway(port=None, host=None, verbose=False, config_path=None)diff --git a/bot/tests/test_openapi_auth.py b/bot/tests/test_openapi_auth.pyindex d01e53b8a..5fe659010 100644--- a/bot/tests/test_openapi_auth.py+++ b/bot/tests/test_openapi_auth.py@@ -4,6 +4,7 @@import tempfilefrom pathlib import Path+from types import SimpleNamespaceimport pytestfrom fastapi import FastAPI@@ -34,7 +35,7 @@ def _make_client(channel: OpenAPIChannel) -> TestClient:class TestOpenAPIAuth:def test_health_remains_available_without_api_key(self, message_bus, temp_workspace):channel = OpenAPIChannel(- OpenAPIChannelConfig(api_key=""),+ OpenAPIChannelConfig(),message_bus,workspace_path=temp_workspace,)@@ -44,26 +45,33 @@ class TestOpenAPIAuth:assert response.status_code == 200- def test_chat_rejects_requests_when_api_key_not_configured(self, message_bus, temp_workspace):+ def test_chat_accepts_requests_when_api_key_not_configured(self, message_bus, temp_workspace, monkeypatch):channel = OpenAPIChannel(- OpenAPIChannelConfig(api_key=""),+ OpenAPIChannelConfig(),message_bus,workspace_path=temp_workspace,)+ async def fake_handle_chat(request):+ return ChatResponse(+ session_id=request.session_id or "default", message="ok", events=None+ )++ monkeypatch.setattr(channel, "_handle_chat", fake_handle_chat)client = _make_client(channel)response = client.post("/bot/v1/chat", json={"message": "hello"})- assert response.status_code == 503- assert response.json()["detail"] == "OpenAPI channel API key is not configured"+ assert response.status_code == 200+ assert response.json()["message"] == "ok"def test_chat_accepts_request_with_configured_valid_api_key(self, message_bus, temp_workspace, monkeypatch):channel = OpenAPIChannel(- OpenAPIChannelConfig(api_key="secret123"),+ OpenAPIChannelConfig(),message_bus,workspace_path=temp_workspace,+ global_config=SimpleNamespace(gateway=SimpleNamespace(token="secret123")),)async def fake_handle_chat(request):@@ -76,22 +84,45 @@ class TestOpenAPIAuth:response = client.post("/bot/v1/chat",- headers={"X-API-Key": "secret123"},+ headers={"X-Gateway-Token": "secret123"},json={"message": "hello"},)assert response.status_code == 200assert response.json()["message"] == "ok"- def test_bot_channel_rejects_requests_when_channel_api_key_not_configured(+ def test_chat_rejects_when_non_localhost_and_token_not_configured(self, message_bus, temp_workspace):channel = OpenAPIChannel(- OpenAPIChannelConfig(api_key="gateway-secret"),+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=SimpleNamespace(gateway=SimpleNamespace(host="0.0.0.0", token="")),+ )+ client = _make_client(channel)++ response = client.post("/bot/v1/chat", json={"message": "hello"})++ assert response.status_code == 503+ assert response.json()["detail"] == "OpenAPI gateway token is required when host is non-localhost"++ def test_bot_channel_accepts_requests_without_channel_api_key(+ self, message_bus, temp_workspace, monkeypatch+ ):+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),message_bus,workspace_path=temp_workspace,)channel._bot_configs["alpha"] = BotChannelConfig(id="alpha", api_key="")++ async def fake_handle_bot_chat(channel_id, request):+ return ChatResponse(+ session_id=request.session_id or "default", message=f"ok:{channel_id}"+ )++ monkeypatch.setattr(channel, "_handle_bot_chat", fake_handle_bot_chat)client = _make_client(channel)response = client.post(@@ -99,16 +130,17 @@ class TestOpenAPIAuth:json={"message": "hello", "channel_id": "alpha"},)- assert response.status_code == 503- assert response.json()["detail"] == "Bot channel 'alpha' API key is not configured"+ assert response.status_code == 200+ assert response.json()["message"] == "ok:alpha"- def test_bot_channel_accepts_request_with_valid_api_key(+ def test_bot_channel_requires_global_gateway_token_when_configured(self, message_bus, temp_workspace, monkeypatch):channel = OpenAPIChannel(- OpenAPIChannelConfig(api_key="gateway-secret"),+ OpenAPIChannelConfig(),message_bus,workspace_path=temp_workspace,+ global_config=SimpleNamespace(gateway=SimpleNamespace(token="secret123")),)channel._bot_configs["alpha"] = BotChannelConfig(id="alpha", api_key="bot-secret")@@ -120,11 +152,17 @@ class TestOpenAPIAuth:monkeypatch.setattr(channel, "_handle_bot_chat", fake_handle_bot_chat)client = _make_client(channel)- response = client.post(+ unauthorized = client.post("/bot/v1/chat/channel",- headers={"X-API-Key": "bot-secret"},json={"message": "hello", "channel_id": "alpha"},)+ assert unauthorized.status_code == 401+ assert unauthorized.json()["detail"] == "X-Gateway-Token header required"- assert response.status_code == 200- assert response.json()["message"] == "ok:alpha"+ authorized = client.post(+ "/bot/v1/chat/channel",+ headers={"X-Gateway-Token": "secret123"},+ json={"message": "hello", "channel_id": "alpha"},+ )+ assert authorized.status_code == 200+ assert authorized.json()["message"] == "ok:alpha"diff --git a/bot/vikingbot/channels/openapi.py b/bot/vikingbot/channels/openapi.pyindex 16d3b305b..8ee5ae87c 100644--- a/bot/vikingbot/channels/openapi.py+++ b/bot/vikingbot/channels/openapi.py@@ -31,6 +31,7 @@ from vikingbot.config.schema import (BotChannelConfig,Config,SessionKey,+ requires_gateway_token,)@@ -64,7 +65,6 @@ class OpenAPIChannelConfig(BaseChannelConfig):enabled: bool = Truetype: str = "cli"- api_key: str = "" # If empty, no auth requiredallow_from: list[str] = []max_concurrent_requests: int = 100_channel_id: str = "default"@@ -230,17 +230,27 @@ class OpenAPIChannel(BaseChannel):router = APIRouter()channel = self # Capture for closures- async def verify_api_key(x_api_key: Optional[str] = Header(None)) -> bool:+ async def verify_api_key(+ x_gateway_token: Optional[str] = Header(None, alias="X-Gateway-Token")+ ) -> bool:"""Verify API key for privileged HTTP chat/session routes."""- if not channel.config.api_key:- raise HTTPException(- status_code=503,- detail="OpenAPI channel API key is not configured",- )- if not x_api_key:- raise HTTPException(status_code=401, detail="X-API-Key header required")+ gateway_token = ""+ gateway_host = "127.0.0.1"+ if channel._global_config is not None:+ gateway = getattr(channel._global_config, "gateway", None)+ gateway_host = getattr(gateway, "host", "127.0.0.1") or "127.0.0.1"+ gateway_token = getattr(gateway, "token", "") or ""+ if not gateway_token:+ if requires_gateway_token(gateway_host, gateway_token):+ raise HTTPException(+ status_code=503,+ detail="OpenAPI gateway token is required when host is non-localhost",+ )+ return True+ if not x_gateway_token:+ raise HTTPException(status_code=401, detail="X-Gateway-Token header required")# Use secrets.compare_digest for timing-safe comparison- if not secrets.compare_digest(x_api_key, channel.config.api_key):+ if not secrets.compare_digest(x_gateway_token, gateway_token):raise HTTPException(status_code=403, detail="Invalid API key")return True@@ -340,29 +350,10 @@ class OpenAPIChannel(BaseChannel):# ========== Bot Channel Routes ==========- async def verify_bot_channel_api_key(- x_api_key: Optional[str] = Header(None),- ) -> Optional[str]:- """Capture the raw bot-channel API key header for per-channel verification."""- return x_api_key-- def ensure_bot_channel_api_key(channel_id: str, x_api_key: Optional[str]) -> None:- """Require an explicit per-channel API key for privileged bot HTTP routes."""- bot_config = channel._bot_configs[channel_id]- if not bot_config.api_key:- raise HTTPException(- status_code=503,- detail=f"Bot channel '{channel_id}' API key is not configured",- )- if not x_api_key:- raise HTTPException(status_code=401, detail="X-API-Key header required")- if not secrets.compare_digest(x_api_key, bot_config.api_key):- raise HTTPException(status_code=403, detail="Invalid API key")-@router.post("/chat/channel", response_model=ChatResponse)async def chat_channel(request: ChatRequest,- x_api_key: Optional[str] = Depends(verify_bot_channel_api_key),+ authorized: bool = Depends(verify_api_key),):"""Send a chat message to a specific bot channel and get a response."""channel_id = request.channel_id@@ -371,14 +362,12 @@ class OpenAPIChannel(BaseChannel):if channel_id not in channel._bot_configs:raise HTTPException(status_code=404, detail=f"Channel '{channel_id}' not found")- ensure_bot_channel_api_key(channel_id, x_api_key)-return await channel._handle_bot_chat(channel_id, request)@router.post("/chat/channel/stream")async def chat_channel_stream(request: ChatRequest,- x_api_key: Optional[str] = Depends(verify_bot_channel_api_key),+ authorized: bool = Depends(verify_api_key),):"""Send a chat message to a specific bot channel and get a streaming response."""channel_id = request.channel_id@@ -387,8 +376,6 @@ class OpenAPIChannel(BaseChannel):if channel_id not in channel._bot_configs:raise HTTPException(status_code=404, detail=f"Channel '{channel_id}' not found")- ensure_bot_channel_api_key(channel_id, x_api_key)-if not request.stream:request.stream = Truereturn await channel._handle_bot_chat_stream(channel_id, request)diff --git a/bot/vikingbot/cli/commands.py b/bot/vikingbot/cli/commands.pyindex 431e62361..61c270c97 100644--- a/bot/vikingbot/cli/commands.py+++ b/bot/vikingbot/cli/commands.py@@ -9,6 +9,7 @@ import sysimport timeimport warningsfrom pathlib import Path+from typing import Optionalimport typerfrom loguru import logger@@ -26,7 +27,7 @@ from vikingbot.agent.loop import AgentLoopfrom vikingbot.bus.queue import MessageBusfrom vikingbot.channels.manager import ChannelManagerfrom vikingbot.config.loader import ensure_config, get_config_path, get_data_dir, load_config-from vikingbot.config.schema import SessionKey+from vikingbot.config.schema import SessionKey, requires_gateway_tokenfrom vikingbot.cron.service import CronServicefrom vikingbot.cron.types import CronJobfrom vikingbot.heartbeat.service import HeartbeatService@@ -110,6 +111,12 @@ def _abort_if_port_in_use(port: int, label: str) -> None:sys.exit(1)+def _get_gateway_token(config) -> str:+ gateway = getattr(config, "gateway", None)+ if gateway is None:+ return ""+ return getattr(gateway, "token", "") or ""+# ---------------------------------------------------------------------------# CLI input: prompt_toolkit for editing, paste, history, and display# ---------------------------------------------------------------------------@@ -263,21 +270,13 @@ def _make_provider(config, langfuse_client: None = None):@app.command()def gateway(- port: int = typer.Option(18790, "--port", "-p", help="Gateway port"),- # console_port: int = typer.Option(18791, "--console-port", help="Console web UI port"),- enable_console: bool = typer.Option(- True, "--console/--no-console", help="Enable console web UI"- ),- agent: bool = typer.Option(- True, "--agent/--no-agent", help="Enable agent loop for OpenAPI/chat"- ),+ port: Optional[int] = typer.Option(None, "--port", "-p", help="Gateway port"),+ host: Optional[str] = typer.Option(None, "--host", help="Gateway host"),verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),config_path: str = typer.Option(None, "--config", "-c", help="ov.conf path"),):"""Start the vikingbot gateway with OpenAPI chat enabled by default."""- _abort_if_port_in_use(port, "vikingbot gateway")-if verbose:import logging@@ -286,6 +285,19 @@ def gateway(bus = MessageBus()path = Path(config_path).expanduser() if config_path is not None else Noneconfig = ensure_config(path)+ effective_host = host if host is not None else config.gateway.host+ effective_port = port if port is not None else config.gateway.port+ gateway_token = _get_gateway_token(config)+ if requires_gateway_token(effective_host, gateway_token):+ print(+ "SECURITY: bot.gateway.token is required when gateway.host is non-localhost.\n"+ "Set bot.gateway.token in ov.conf, or bind gateway.host to 127.0.0.1/localhost.",+ file=sys.stderr,+ )+ sys.exit(1)+ config.gateway.host = effective_host+ config.gateway.port = effective_port+ _abort_if_port_in_use(effective_port, "vikingbot gateway")_init_bot_data(config)session_manager = SessionManager(config.bot_data_path)@@ -300,7 +312,11 @@ def gateway(cron = prepare_cron(bus)channels = prepare_channel(- config, bus, fastapi_app=fastapi_app, enable_openapi=True, openapi_port=port+ config,+ bus,+ fastapi_app=fastapi_app,+ enable_openapi=True,+ openapi_port=effective_port,)agent_loop = prepare_agent_loop(config, bus, session_manager, cron)heartbeat = prepare_heartbeat(config, agent_loop, session_manager)@@ -311,18 +327,13 @@ def gateway(# Start uvicorn server for OpenAPIconfig_uvicorn = uvicorn.Config(fastapi_app,- host="0.0.0.0",- port=port,+ host=effective_host,+ port=effective_port,log_level="info",)server = uvicorn.Server(config_uvicorn)- tasks = []- tasks.append(cron.start())- tasks.append(heartbeat.start())- tasks.append(channels.start_all())- tasks.append(agent_loop.run())- tasks.append(server.serve()) # Start HTTP server+ tasks = [cron.start(), heartbeat.start(), channels.start_all(), agent_loop.run(), server.serve()]# if enable_console:# tasks.append(start_console(console_port))@@ -466,8 +477,6 @@ def prepare_channel(openapi_config = OpenAPIChannelConfig(enabled=True,- port=openapi_port,- api_key="",)openapi_channel = OpenAPIChannel(openapi_config,@@ -476,9 +485,7 @@ def prepare_channel(global_config=config,)channels.add_channel(openapi_channel)- logger.info(- f"OpenAPI channel enabled on port {openapi_port}; configure an API key before using HTTP chat endpoints"- )+ logger.info(f"OpenAPI channel enabled on port {openapi_port}")if channels.enabled_channels:console.print(f"[green]✓[/green] Channels enabled: {', '.join(channels.enabled_channels)}")diff --git a/bot/vikingbot/config/schema.py b/bot/vikingbot/config/schema.pyindex 9400a5ab2..07ef73b25 100644--- a/bot/vikingbot/config/schema.py+++ b/bot/vikingbot/config/schema.py@@ -272,7 +272,6 @@ class OpenAPIChannelConfig(BaseChannelConfig):type: ChannelType = ChannelType.OPENAPIenabled: bool = True- api_key: str = "" # Empty disables privileged HTTP routes until configuredallow_from: list[str] = Field(default_factory=list)max_concurrent_requests: int = 100_channel_id: str = "default"@@ -477,11 +476,25 @@ class HeartbeatConfig(BaseModel):interval_seconds: int = 10 * 60 # Default: 5 minutes+LOCALHOST_HOSTS = {"127.0.0.1", "localhost", "::1"}+++def is_localhost_host(host: str) -> bool:+ return host in LOCALHOST_HOSTS+++def requires_gateway_token(host: str, token: str) -> bool:+ return not is_localhost_host(host) and not token++class GatewayConfig(BaseModel):"""Gateway/server configuration."""- host: str = "0.0.0.0"+ host: str = "127.0.0.1"port: int = 18790+ token: str = ""+ # 已废弃,使用token替代+ api_key: str = ""class WebSearchConfig(BaseModel):diff --git a/bot/vikingbot/heartbeat/service.py b/bot/vikingbot/heartbeat/service.pyindex 96cb0e450..b2a2cb10d 100644--- a/bot/vikingbot/heartbeat/service.py+++ b/bot/vikingbot/heartbeat/service.py@@ -124,13 +124,9 @@ class HeartbeatService:metadata = session_info.get("metadata", {})if metadata.get("skip_heartbeat"):- logger.debug(- f"Heartbeat: skipping session {session_key} (marked as skip_heartbeat)"- )continueif self._is_session_stale(session_info):- logger.debug(f"Heartbeat: skipping session {session_key} (inactive > 2 days)")continueif self.sandbox_mode == "shared":diff --git a/openviking/server/app.py b/openviking/server/app.pyindex 32b0fb597..a7d444239 100644--- a/openviking/server/app.py+++ b/openviking/server/app.py@@ -12,7 +12,12 @@ from fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponsefrom openviking.server.api_keys import APIKeyManager-from openviking.server.config import ServerConfig, load_server_config, validate_server_config+from openviking.server.config import (+ ServerConfig,+ load_bot_gateway_token,+ load_server_config,+ validate_server_config,+)from openviking.server.dependencies import set_servicefrom openviking.server.error_mapping import map_exceptionfrom openviking.server.identity import AuthMode@@ -236,6 +241,7 @@ def create_app(import openviking.server.routers.bot as bot_modulebot_module.set_bot_api_url(config.bot_api_url)+ bot_module.set_bot_api_key(load_bot_gateway_token())logger.info(f"Bot API proxy enabled, forwarding to {config.bot_api_url}")else:logger.info("Bot API proxy disabled (use --with-bot to enable)")diff --git a/openviking/server/bootstrap.py b/openviking/server/bootstrap.pyindex 0eda1ee61..415d6ee09 100644--- a/openviking/server/bootstrap.py+++ b/openviking/server/bootstrap.py@@ -3,6 +3,7 @@"""Bootstrap script for OpenViking HTTP Server."""import argparse+import jsonimport osimport shutilimport socket@@ -10,6 +11,7 @@ import subprocessimport sysimport timefrom dataclasses import dataclass+from pathlib import Pathfrom typing import Optionalimport uvicorn@@ -17,6 +19,8 @@ import uvicornfrom openviking.server.app import create_appfrom openviking.server.config import load_server_configfrom openviking_cli.utils.config import OPENVIKING_CONFIG_ENV+from openviking_cli.utils.config.config_loader import resolve_config_path+from openviking_cli.utils.config.consts import DEFAULT_CONFIG_DIR, DEFAULT_OV_CONFfrom openviking_cli.utils.logger import configure_uvicorn_logging@@ -35,6 +39,7 @@ def _get_version() -> str:return "unknown"+VIKINGBOT_DEFAULT_HOST = "127.0.0.1"VIKINGBOT_DEFAULT_PORT = 18790@@ -72,6 +77,28 @@ def _normalize_host_arg(host: Optional[str]) -> Optional[str]:return host+def _resolve_default_bot_log_dir(config_path: Optional[str]) -> str:+ """Resolve default bot log directory from current ov.conf storage.workspace."""+ default_storage = DEFAULT_CONFIG_DIR / "data"+ default_log_dir = default_storage / "bot" / "logs"++ resolved_path = resolve_config_path(config_path, OPENVIKING_CONFIG_ENV, DEFAULT_OV_CONF)+ if resolved_path is None:+ return str(default_log_dir)++ try:+ with open(resolved_path, "r", encoding="utf-8-sig") as f:+ raw = os.path.expandvars(f.read())+ data = json.loads(raw)+ storage = data.get("storage", {})+ workspace = storage.get("workspace") if isinstance(storage, dict) else None+ if not workspace:+ return str(default_log_dir)+ return str(Path(workspace).expanduser().resolve() / "bot" / "logs")+ except Exception:+ return str(default_log_dir)++def main():"""Main entry point for openviking-server command."""parser = argparse.ArgumentParser(@@ -119,10 +146,11 @@ def main():help="Enable Bot API proxy to Vikingbot (requires Vikingbot running)",)parser.add_argument(- "--bot-url",- default="http://localhost:18790",- dest="bot_url",- help="Vikingbot OpenAPIChannel URL (default: http://localhost:18790)",+ "--bot-port",+ type=int,+ default=VIKINGBOT_DEFAULT_PORT,+ dest="bot_port",+ help=f"Vikingbot gateway port (default: {VIKINGBOT_DEFAULT_PORT})",)parser.add_argument("--enable-bot-logging",@@ -140,8 +168,8 @@ def main():parser.add_argument("--bot-log-dir",type=str,- default=os.path.expanduser("~/.openviking/data/bot/logs"),- help="Directory to store vikingbot log files",+ default=None,+ help="Directory to store vikingbot log files (default: {storage.workspace or ~/.openviking/data}/bot/logs)",)args = parser.parse_args()@@ -191,22 +219,27 @@ def main():config.workers = args.workersif args.with_bot:config.with_bot = True- if args.bot_url:- config.bot_api_url = args.bot_url# Configure logging for Uvicornconfigure_uvicorn_logging()bot_process: Optional[BotProcess] = Noneif config.with_bot:- _abort_if_port_in_use(VIKINGBOT_DEFAULT_PORT, "vikingbot gateway")+ bot_port = args.bot_port+ config.bot_api_url = f"http://{VIKINGBOT_DEFAULT_HOST}:{bot_port}"+ _abort_if_port_in_use(bot_port, "vikingbot gateway")print(f"Bot API proxy enabled, forwarding to {config.bot_api_url}")# Determine if bot logging should be enabledenable_bot_logging = args.enable_bot_loggingif enable_bot_logging is None:enable_bot_logging = args.with_bot+ bot_log_dir = args.bot_log_dir or _resolve_default_bot_log_dir(args.config)# Start vikingbot gateway if --with-bot is set- bot_process = _start_vikingbot_gateway(enable_bot_logging, args.bot_log_dir)+ bot_process = _start_vikingbot_gateway(+ enable_bot_logging,+ bot_log_dir,+ bot_port,+ )# Create and run server appapp = create_app(config)@@ -255,7 +288,11 @@ def _handle_vikingbot_failure(output: str, returncode: int) -> None:print(f"\nDetailed error:\n{output}", file=sys.stderr)-def _start_vikingbot_gateway(enable_logging: bool, log_dir: str) -> Optional[BotProcess]:+def _start_vikingbot_gateway(+ enable_logging: bool,+ log_dir: str,+ port: int = VIKINGBOT_DEFAULT_PORT,+) -> Optional[BotProcess]:"""Start vikingbot gateway as a subprocess."""print("Starting vikingbot gateway...")@@ -280,6 +317,8 @@ def _start_vikingbot_gateway(enable_logging: bool, log_dir: str) -> Optional[Botprint(" uv pip install -e '.[bot,dev]'")return None+ vikingbot_cmd.extend(["--host", VIKINGBOT_DEFAULT_HOST, "--port", str(port)])+# Prepare logginglog_file = Nonestdout_handler = subprocess.PIPEdiff --git a/openviking/server/config.py b/openviking/server/config.pyindex 6a6b96f7d..c48bb8daa 100644--- a/openviking/server/config.py+++ b/openviking/server/config.py@@ -152,6 +152,22 @@ def _is_localhost(host: str) -> bool:return host in _LOCALHOST_HOSTS+def load_bot_gateway_token(config_path: Optional[str] = None) -> str:+ """Load bot gateway token from ov.conf bot.gateway.token."""+ path = resolve_config_path(config_path, OPENVIKING_CONFIG_ENV, DEFAULT_OV_CONF)+ if path is None:+ return ""++ data = load_json_config(path)+ bot_config = data.get("bot", {})+ if not isinstance(bot_config, dict):+ return ""+ gateway_config = bot_config.get("gateway", {})+ if not isinstance(gateway_config, dict):+ return ""+ return gateway_config.get("token", "") or ""++def validate_server_config(config: ServerConfig) -> None:"""Validate server config for safe startup.diff --git a/openviking/server/routers/bot.py b/openviking/server/routers/bot.pyindex 5423d6169..d16fef03f 100644--- a/openviking/server/routers/bot.py+++ b/openviking/server/routers/bot.py@@ -21,6 +21,7 @@ logger = get_logger(__name__)# Bot API configuration - set when --with-bot is enabledBOT_API_URL: Optional[str] = None # e.g., "http://localhost:18791"+BOT_API_KEY: str = ""def set_bot_api_url(url: str) -> None:@@ -29,6 +30,12 @@ def set_bot_api_url(url: str) -> None:BOT_API_URL = url+def set_bot_api_key(api_key: str) -> None:+ """Set the Bot API key used by proxy requests to bot gateway."""+ global BOT_API_KEY+ BOT_API_KEY = api_key or ""++def get_bot_url() -> str:"""Get the Bot API URL, raising 503 if not configured."""if BOT_API_URL is None:@@ -71,21 +78,6 @@ async def health_check(request: Request):)-def extract_auth_token(request: Request) -> Optional[str]:- """Extract and return authorization token from request."""- # Try X-API-Key header first- api_key = request.headers.get("X-API-Key")- if api_key:- return api_key-- # Try Authorization header (Bearer token)- auth_header = request.headers.get("Authorization")- if auth_header and auth_header.startswith("Bearer "):- return auth_header[7:] # Remove "Bearer " prefix-- return None--@router.post("/chat")async def chat(request: Request,@@ -96,7 +88,6 @@ async def chat(Proxies the request to Vikingbot OpenAPIChannel."""bot_url = get_bot_url()- auth_token = extract_auth_token(request)# Read request bodytry:@@ -109,10 +100,10 @@ async def chat(try:async with httpx.AsyncClient() as client:- # Build headers - only include X-API-Key if provided+ # Build headers for bot gatewayheaders = {"Content-Type": "application/json"}- if auth_token:- headers["X-API-Key"] = auth_token+ if BOT_API_KEY:+ headers["X-Gateway-Token"] = BOT_API_KEY# Forward to Vikingbot OpenAPIChannel chat endpointresponse = await client.post(@@ -153,7 +144,6 @@ async def chat_stream(Proxies the request to Vikingbot OpenAPIChannel with SSE streaming."""bot_url = get_bot_url()- auth_token = extract_auth_token(request)# Read request bodytry:@@ -168,10 +158,10 @@ async def chat_stream("""Generate SSE events from bot response stream."""try:async with httpx.AsyncClient() as client:- # Build headers - only include X-API-Key if provided+ # Build headers for bot gatewayheaders = {"Content-Type": "application/json"}- if auth_token:- headers["X-API-Key"] = auth_token+ if BOT_API_KEY:+ headers["X-Gateway-Token"] = BOT_API_KEY# Forward to Vikingbot OpenAPIChannel stream endpointasync with client.stream(diff --git a/tests/server/test_bot_proxy_auth.py b/tests/server/test_bot_proxy_auth.pyindex 291326c5b..b5855d1e6 100644--- a/tests/server/test_bot_proxy_auth.py+++ b/tests/server/test_bot_proxy_auth.py@@ -3,35 +3,12 @@"""Regression tests for bot proxy endpoint auth enforcement."""-import pytest-from fastapi import Request-import openviking.server.routers.bot as bot_router_module-def make_request(headers: dict[str, str]) -> Request:- """Create a minimal request object with the provided headers."""- return Request(- {- "type": "http",- "method": "POST",- "path": "/",- "headers": [- (key.lower().encode("latin-1"), value.encode("latin-1"))- for key, value in headers.items()- ],- "query_string": b"",- }- )-+def test_set_bot_api_key_updates_module_state():+ bot_router_module.set_bot_api_key("gateway-secret")+ assert bot_router_module.BOT_API_KEY == "gateway-secret"- ("headers", "expected"),- [- ({"X-API-Key": "test-key"}, "test-key"),- ({"Authorization": "Bearer test-token"}, "test-token"),- ],-)-def test_extract_auth_token(headers: dict[str, str], expected: str):- """Accepted auth header formats should both produce a token."""- assert bot_router_module.extract_auth_token(make_request(headers)) == expected+ bot_router_module.set_bot_api_key("")+ assert bot_router_module.BOT_API_KEY == ""diff --git a/tests/test_server_config_loader.py b/tests/test_server_config_loader.pyindex 5f85b232f..155c95dd0 100644--- a/tests/test_server_config_loader.py+++ b/tests/test_server_config_loader.py@@ -5,7 +5,7 @@ import jsonimport pytest-from openviking.server.config import load_server_config+from openviking.server.config import load_bot_gateway_token, load_server_configdef test_load_server_config_rejects_unknown_field(tmp_path):@@ -69,6 +69,23 @@ def test_load_server_config_preserves_supported_fields(tmp_path):assert config.encryption_enabled is True+def test_load_bot_gateway_token_reads_token_from_bot_gateway_section(tmp_path):+ config_path = tmp_path / "ov.conf"+ config_path.write_text(+ json.dumps(+ {+ "bot": {+ "gateway": {+ "token": "gateway-token"+ }+ }+ }+ )+ )++ assert load_bot_gateway_token(str(config_path)) == "gateway-token"++def test_load_server_config_preserves_metrics_account_dimension_fields(tmp_path):config_path = tmp_path / "ov.conf"config_path.write_text(diff --git a/tests/unit/test_server_bootstrap_bot_gateway.py b/tests/unit/test_server_bootstrap_bot_gateway.pynew file mode 100644index 000000000..19063fbd8--- /dev/null+++ b/tests/unit/test_server_bootstrap_bot_gateway.py@@ -0,0 +1,58 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++import openviking.server.bootstrap as bootstrap+++class _FakeProcess:+ pid = 12345++ def poll(self):+ return None+++def test_start_vikingbot_gateway_forces_localhost_host(monkeypatch):+ captured = {}++ monkeypatch.setattr(bootstrap.shutil, "which", lambda name: "/usr/bin/vikingbot")++ def _fake_popen(cmd, stdout=None, stderr=None, text=None, env=None):+ captured["cmd"] = cmd+ return _FakeProcess()++ monkeypatch.setattr(bootstrap.subprocess, "Popen", _fake_popen)+ monkeypatch.setattr(bootstrap.time, "sleep", lambda _: None)++ process = bootstrap._start_vikingbot_gateway(enable_logging=False, log_dir="/tmp/logs")++ assert process is not None+ assert captured["cmd"][:2] == ["vikingbot", "gateway"]+ assert "--host" in captured["cmd"]+ assert captured["cmd"][captured["cmd"].index("--host") + 1] == "127.0.0.1"+ assert "--port" in captured["cmd"]+ assert captured["cmd"][captured["cmd"].index("--port") + 1] == str(+ bootstrap.VIKINGBOT_DEFAULT_PORT+ )+++def test_start_vikingbot_gateway_uses_custom_port(monkeypatch):+ captured = {}++ monkeypatch.setattr(bootstrap.shutil, "which", lambda name: "/usr/bin/vikingbot")++ def _fake_popen(cmd, stdout=None, stderr=None, text=None, env=None):+ captured["cmd"] = cmd+ return _FakeProcess()++ monkeypatch.setattr(bootstrap.subprocess, "Popen", _fake_popen)+ monkeypatch.setattr(bootstrap.time, "sleep", lambda _: None)++ process = bootstrap._start_vikingbot_gateway(+ enable_logging=False,+ log_dir="/tmp/logs",+ port=19990,+ )++ assert process is not None+ assert captured["cmd"][captured["cmd"].index("--host") + 1] == "127.0.0.1"+ assert captured["cmd"][captured["cmd"].index("--port") + 1] == "19990"