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
feat(hermes-plugin): support extra HTTP headers (ovcli.conf `extra_headers` / `OPENVIKING_EXTRA_HEADERS`) (#5884)
xiebaiyuanba335574f44d
diff --git a/examples/hermes-plugin/CONFIGURATION.md b/examples/hermes-plugin/CONFIGURATION.mdindex 7d7d991e3..cf749967f 100644--- a/examples/hermes-plugin/CONFIGURATION.md+++ b/examples/hermes-plugin/CONFIGURATION.md@@ -101,6 +101,7 @@ home address requires OpenViking 0.4.16 or newer for user and admin keys, or| `OPENVIKING_ACCOUNT` | `default` | Tenant account for local/trusted mode || `OPENVIKING_USER` | `default` | Tenant user for local/trusted mode || `OPENVIKING_AGENT` | (none) | Optional peer ID for separate assistant context |+| `OPENVIKING_EXTRA_HEADERS` | (none) | JSON object of extra HTTP headers (e.g. gateway service tokens); overrides `extra_headers` from the linked `ovcli.conf` |User and admin API keys let OpenViking derive account/user identity from the key.In trusted deployments, set `OPENVIKING_API_KEY` to the server's root API key;@@ -110,6 +111,38 @@ Hermes also sends `User-Agent: openviking-memory-hermes/<version>` onOpenViking requests. This header contains the Hermes version. It does notcontain a user identifier or require an extra request.+### Extra HTTP headers (authenticating gateways)++A server published behind an authenticating gateway (Cloudflare Access,+oauth2-proxy, an mTLS-terminating proxy) needs a client header on every request,+including the startup health check.++`extra_headers` is the documented client contract: it sits in the linked+`ovcli.conf` next to `url`/`api_key` and is what the CLI and the Python/Rust/Go+clients read. Hermes consumes the same key, so a deployment that already carries+it needs nothing else:++```json+{+ "url": "https://ov.example.com",+ "api_key": "<user key>",+ "extra_headers": {+ "CF-Access-Client-Id": "<service token id>",+ "CF-Access-Client-Secret": "<service token secret>"+ }+}+```++`OPENVIKING_EXTRA_HEADERS` (a JSON object, read from the profile `.env`) is an+explicit override for deployment secrets that should not live in a file. It wins+when both are set, so the resolution order is: profile `OPENVIKING_EXTRA_HEADERS`+→ linked `ovcli.conf` `extra_headers` → none.++Values must be scalars. `X-OpenViking-*` names are dropped, so an operator-supplied+map can never assert tenant identity, and the plugin's own headers (authentication,+tenant, actor) take precedence over the map. The client snapshots the map when it+is built, so the headers also cover the startup `/health` probe.+### Optional peer identityNew connections use the OpenViking user's memory directory by default. Setupdiff --git a/examples/hermes-plugin/__init__.py b/examples/hermes-plugin/__init__.pyindex 2d6b4fd86..18ede0808 100644--- a/examples/hermes-plugin/__init__.py+++ b/examples/hermes-plugin/__init__.py@@ -69,6 +69,51 @@ _OVCLI_SAVED_PREFIX = "ovcli.conf."_CONNECTION_KEYS = ("endpoint", "api_key", "account", "user", "agent")_IDENTITY_UNSET = object()_OPENVIKING_ENV_KEYS = tuple(f"OPENVIKING_{key.upper()}" for key in _CONNECTION_KEYS)+_EXTRA_HEADERS_ENV = "OPENVIKING_EXTRA_HEADERS"+_RESERVED_HEADER_PREFIX = "x-openviking-"+++def _parse_extra_headers(raw) -> dict:+ """Extra HTTP headers to send on every OpenViking request.++ Mirrors the JS layer (memory-plugin-shared/lib/mcp-proxy-config.mjs): a JSON+ object whose values are scalars. Reserved X-OpenViking-* names are dropped so a+ caller-supplied map can never assert tenant identity (trusted mode reads those+ as identity, so allowing them would be an impersonation vector).+ """+ data = raw+ if isinstance(data, str):+ text = data.strip()+ if not text:+ return {}+ try:+ data = json.loads(text)+ except (ValueError, TypeError):+ logger.warning("%s is not valid JSON; ignoring", _EXTRA_HEADERS_ENV)+ return {}+ if data is None:+ return {}+ if not isinstance(data, dict):+ logger.warning("extra headers must be a JSON object of string values; ignoring")+ return {}+ parsed = {}+ for name, value in data.items():+ if not isinstance(name, str) or not name.strip():+ continue+ key = name.strip()+ if key.lower().startswith(_RESERVED_HEADER_PREFIX):+ logger.warning("extra headers: ignoring reserved header %r", key)+ continue+ if isinstance(value, bool) or not isinstance(value, (str, int, float)):+ logger.warning("extra headers: header %r must be a scalar; ignoring", key)+ continue+ parsed[key] = str(value)+ return parsed+++def _extra_headers_key(headers) -> str:+ """Stable fingerprint so a changed map refreshes the cached client."""+ return json.dumps(headers or {}, sort_keys=True, separators=(",", ":"))_TIMEOUT = 30.0_SESSION_DRAIN_TIMEOUT = 10.0_DEFERRED_COMMIT_TIMEOUT = (_TIMEOUT * 2) + 5.0@@ -287,7 +332,8 @@ class _VikingClient:def __init__(self, endpoint: str, api_key: str = "",account: Optional[str] | object = _IDENTITY_UNSET,user: Optional[str] | object = _IDENTITY_UNSET,- agent: Optional[str] | object = _IDENTITY_UNSET):+ agent: Optional[str] | object = _IDENTITY_UNSET,+ extra_headers: Optional[dict] | object = _IDENTITY_UNSET):self._endpoint = endpoint.rstrip("/")self._api_key = api_key# Account/user are local/trusted-mode tenant identity. API-key requests@@ -297,7 +343,17 @@ class _VikingClient:self._account = (get_secret("OPENVIKING_ACCOUNT", "") if account is _IDENTITY_UNSET or account is None else account) or "default"self._user = (get_secret("OPENVIKING_USER", "") if user is _IDENTITY_UNSET or user is None else user) or "default"self._agent = (get_secret("OPENVIKING_AGENT", "") or _DEFAULT_AGENT) if agent is _IDENTITY_UNSET or agent is None else agent+ # Extra HTTP headers (e.g. Cloudflare Access service tokens) — same resolution+ # shape as the identity fields above: an explicit value wins, otherwise the+ # profile's OPENVIKING_EXTRA_HEADERS.+ self._extra_headers = (+ _parse_extra_headers(get_secret(_EXTRA_HEADERS_ENV))+ if extra_headers is _IDENTITY_UNSET or extra_headers is None+ else _parse_extra_headers(extra_headers)+ )# Every client owns its resolved identity, including clients retained across reloads.+ # The snapshot stays a 5-tuple on purpose: it is unpacked positionally in several+ # places, so extra headers ride beside it (self._extra_headers) instead.self._conn_snapshot = (self._endpoint, self._api_key, self._account, self._user, self._agent)self._httpx = _get_httpx()if self._httpx is None:@@ -313,6 +369,10 @@ class _VikingClient:h.update({k: v for k, v in (("X-OpenViking-Account", self._account), ("X-OpenViking-User", self._user)) if v})if self._api_key:h.update({"X-API-Key": self._api_key, "Authorization": "Bearer " + self._api_key})+ if self._extra_headers:+ # Operator-supplied headers fill gaps; ours win, so a stray entry can never+ # override authentication or tenant identity.+ return {**self._extra_headers, **h}return h@staticmethod@@ -650,6 +710,7 @@ def _connection_values_from_ovcli(data: dict) -> dict:"account": _clean_config_value(data.get("account") or data.get("account_id")) if send_identity else "","user": _clean_config_value(data.get("user") or data.get("user_id")) if send_identity else "","agent": _clean_config_value(data.get("actor_peer_id") or data.get("agent_id")),+ "extra_headers": _parse_extra_headers(data.get("extra_headers")),}@@ -901,7 +962,9 @@ def _resolve_connection_settings(provider_config: Optional[dict] = None, *, env:except quick_local.QuickLocalSetupError as exc:raise _OpenVikingEndpointError(str(exc)) from excvalues = _connection_values_from_ovcli(profile)- return {key: values[key] or ("default" if key in ("account", "user") else _DEFAULT_AGENT if key == "agent" else "") for key in _CONNECTION_KEYS}+ resolved = {key: values[key] or ("default" if key in ("account", "user") else _DEFAULT_AGENT if key == "agent" else "") for key in _CONNECTION_KEYS}+ resolved["extra_headers"] = values.get("extra_headers") or {}+ return resolvedovcli_values = _ovcli_values_for(provider_config, env=env)def layered(key: str, default: str = "", *, env_authoritative: bool = False) -> str:@@ -917,12 +980,14 @@ def _resolve_connection_settings(provider_config: Optional[dict] = None, *, env:account = layered("account", env_authoritative=True)user = layered("user", env_authoritative=True)account, user = account or "default", user or "default"+ extra_headers_raw = get_secret(_EXTRA_HEADERS_ENV) if env is None else env.get(_EXTRA_HEADERS_ENV)return {"endpoint": _normalize_openviking_url(layered("endpoint", _DEFAULT_ENDPOINT)),"api_key": api_key,"account": account,"user": user,"agent": layered("agent", _DEFAULT_AGENT),+ "extra_headers": _parse_extra_headers(extra_headers_raw) or ovcli_values.get("extra_headers") or {},}@@ -1457,6 +1522,7 @@ class OpenVikingMemoryProvider(MemoryProvider):self._commit_scope: Optional[_CommitScope] = Noneself._profile_prefetched_sessions: Set[str] = set()self._conn_snapshot: Optional[tuple] = None+ self._extra_headers: dict = {}self._failed_refresh: Optional[tuple] = Noneself._runtime_start_thread: Optional[threading.Thread] = Noneself._runtime_start_pending = False@@ -1558,7 +1624,8 @@ class OpenVikingMemoryProvider(MemoryProvider):def _build_client(self, endpoint: Optional[str] = None) -> _VikingClient:endpoint, api_key, account, user, agent = self._settings_tuple(endpoint)- return _VikingClient(endpoint, api_key, account=account, user=user, agent=agent)+ return _VikingClient(endpoint, api_key, account=account, user=user, agent=agent,+ extra_headers=self._extra_headers)def _publish_client(self, client: _VikingClient, endpoint: str) -> None:with self._session_state_lock:@@ -1706,8 +1773,14 @@ class OpenVikingMemoryProvider(MemoryProvider):settings = self._resolve_bound_connection_settings(config, env)except _OpenVikingEndpointError as exc:connection_error = str(exc)- settings = dict.fromkeys(_CONNECTION_KEYS, "")+ settings: dict = dict.fromkeys(_CONNECTION_KEYS, "")self._endpoint, self._api_key, self._account, self._user, self._agent = (settings[k] for k in _CONNECTION_KEYS)+ # Resolve extra headers BEFORE any client is built. _VikingClient snapshots them at+ # construction, and the startup /health probe goes through that client: a gateway that+ # protects every route (Cloudflare Access, oauth2-proxy) rejects a header-less probe,+ # which would drop the client and leave the provider unusable until a config change+ # forced a rebuild. See tests/test_extra_headers.py::test_startup_health_probe_carries_extra_headers.+ self._extra_headers = _parse_extra_headers(settings.get("extra_headers"))# Baseline established — set here, not at the end, so an exception in the# connection attempt (swallowed by MemoryManager) can't leave the provider# stuck in never-refresh mode.@@ -1814,7 +1887,8 @@ class OpenVikingMemoryProvider(MemoryProvider):self._failed_refresh = (("quick-local-restart",), time.monotonic())return Nonesettings_key = tuple(settings[k] for k in _CONNECTION_KEYS)- if settings_key == self._settings_tuple():+ extra_key = _extra_headers_key(settings.get("extra_headers"))+ if settings_key == self._settings_tuple() and extra_key == _extra_headers_key(self._extra_headers):if self._client is not None:if managed:from .local_server import LocalServer@@ -1835,6 +1909,9 @@ class OpenVikingMemoryProvider(MemoryProvider):return Noneself._endpoint, self._api_key, self._account, self._user, self._agent = settings_key+ # Same ordering rule as initialize(): the client snapshots extra headers at build time,+ # so refresh them before rebuilding + probing.+ self._extra_headers = _parse_extra_headers(settings.get("extra_headers"))try:client = self._build_client()except ImportError:@@ -1875,7 +1952,8 @@ class OpenVikingMemoryProvider(MemoryProvider):if not isinstance(snapshot, tuple):snapshot = self._conn_snapshot or self._settings_tuple()endpoint, api_key, account, user, agent = snapshot- return _VikingClient(endpoint, api_key, account=account, user=user, agent=agent)+ return _VikingClient(endpoint, api_key, account=account, user=user, agent=agent,+ extra_headers=self._extra_headers)# -- prompt / prefetch ---------------------------------------------------@@ -1989,7 +2067,8 @@ class OpenVikingMemoryProvider(MemoryProvider):if scope in ("shared", "peer"):endpoint, api_key, account, user, _agent = client._conn_snapshotclient = _VikingClient(endpoint, api_key, account=account, user=user,- agent=sender_peer if scope == "peer" else "")+ agent=sender_peer if scope == "peer" else "",+ extra_headers=self._extra_headers)if scope == "peer":# Explicit roots also constrain fallback searches when there is# no sender. An actor-less user-root search includes all peers.diff --git a/examples/hermes-plugin/tests/test_extra_headers.py b/examples/hermes-plugin/tests/test_extra_headers.pynew file mode 100644index 000000000..de79c8597--- /dev/null+++ b/examples/hermes-plugin/tests/test_extra_headers.py@@ -0,0 +1,150 @@+"""Extra HTTP headers (e.g. Cloudflare Access service tokens) reach the wire.++An OpenViking server published behind an authenticating gateway (Cloudflare Access,+oauth2-proxy, an mTLS-terminating proxy) requires a client header on every request.+The JS side has carried this for a while (``OPENVIKING_EXTRA_HEADERS`` in+``memory-plugin-shared/lib/mcp-proxy-config.mjs``, plus ``extra_headers`` in the+linked ``ovcli.conf``); these tests pin the same behaviour for this plugin.+"""++import json+import threading+from http.server import BaseHTTPRequestHandler, HTTPServer+++def _start_server(records, *, require_header=None):+ class Handler(BaseHTTPRequestHandler):+ def do_GET(self):+ records.append(dict(self.headers))+ if require_header and not self.headers.get(require_header):+ status, payload = 403, {"error": "blocked at edge"}+ else:+ status, payload = 200, {"status": "ok", "healthy": True,+ "version": "0.4.18", "auth_mode": "api_key"}+ raw = json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(raw)))+ self.end_headers()+ self.wfile.write(raw)++ def log_message(self, *_args):+ pass++ server = HTTPServer(("127.0.0.1", 0), Handler)+ worker = threading.Thread(target=server.serve_forever, daemon=True)+ worker.start()+ return server, worker+++def test_extra_headers_from_env_reach_every_request(external_provider):+ _, _, module, _ = external_provider("extra-headers")+ records = []+ server, worker = _start_server(records, require_header="CF-Access-Client-Id")+ endpoint = f"http://127.0.0.1:{server.server_port}"+ try:+ settings = module._resolve_connection_settings({}, env={+ "OPENVIKING_API_KEY": "test-key",+ "OPENVIKING_EXTRA_HEADERS": json.dumps({+ "CF-Access-Client-Id": "id.access",+ "CF-Access-Client-Secret": "gateway-secret",+ }),+ })+ assert settings["extra_headers"] == {+ "CF-Access-Client-Id": "id.access",+ "CF-Access-Client-Secret": "gateway-secret",+ }+ client = module._VikingClient(endpoint, settings["api_key"],+ extra_headers=settings["extra_headers"])+ assert client.get("/health")["status"] == "ok"+ assert records[-1]["CF-Access-Client-Id"] == "id.access"+ assert records[-1]["CF-Access-Client-Secret"] == "gateway-secret"+ finally:+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)+++def test_extra_headers_are_read_from_linked_ovcli_conf():+ """The documented client file already carries extra_headers; do not drop it."""+ import importlib.util+ import sys+ from pathlib import Path++ here = Path(__file__).resolve().parents[1]+ spec = importlib.util.spec_from_file_location("openviking_under_test", here / "__init__.py")+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)++ values = module._connection_values_from_ovcli({+ "url": "https://ov.example.com",+ "api_key": "user-key",+ "extra_headers": {"CF-Access-Client-Id": "id.access"},+ })+ assert values["extra_headers"] == {"CF-Access-Client-Id": "id.access"}+++def test_extra_headers_cannot_forge_identity(external_provider):+ _, _, module, _ = external_provider("extra-headers-identity")+ parsed = module._parse_extra_headers(json.dumps({+ "X-OpenViking-Account": "someone-else",+ "X-OpenViking-User": "root",+ "CF-Access-Client-Id": "id.access",+ }))+ assert parsed == {"CF-Access-Client-Id": "id.access"}++ client = module._VikingClient("http://127.0.0.1:1", "real-key", extra_headers={+ "X-API-Key": "not-mine",+ "Authorization": "Bearer not-mine",+ "X-OpenViking-Actor-Peer": "not-mine",+ "CF-Access-Client-Id": "id.access",+ })+ headers = client._headers()+ assert headers["X-API-Key"] == "real-key"+ assert headers["Authorization"] == "Bearer real-key"+ assert "X-OpenViking-Account" not in headers+ assert headers["CF-Access-Client-Id"] == "id.access"+++def test_extra_headers_invalid_input_is_ignored(external_provider):+ _, _, module, _ = external_provider("extra-headers-invalid")+ assert module._parse_extra_headers("not json") == {}+ assert module._parse_extra_headers("") == {}+ assert module._parse_extra_headers(None) == {}+ assert module._parse_extra_headers("[1, 2]") == {}+ assert module._parse_extra_headers({"A": {"nested": 1}, "B": 2, "C": True}) == {"B": "2"}+ settings = module._resolve_connection_settings({}, env={"OPENVIKING_EXTRA_HEADERS": "not json"})+ assert settings["extra_headers"] == {}+++def test_startup_health_probe_carries_extra_headers(external_provider):+ """The startup health check must use the resolved extra headers.++ A gateway that protects every route (Cloudflare Access, oauth2-proxy) rejects a+ header-less probe. ``_VikingClient`` snapshots the map at construction, so the+ provider has to resolve it *before* the first client is built — otherwise the+ probe is refused, the client is dropped, and the provider stays unusable until+ some unrelated config change forces a rebuild.+ """+ records = []+ server, worker = _start_server(records, require_header="CF-Access-Client-Id")+ endpoint = "http://127.0.0.1:%d" % server.server_port+ try:+ home, provider, _module, _settings = external_provider("extra-headers-startup")+ (home / ".env").write_text(+ "OPENVIKING_ENDPOINT=%s\nOPENVIKING_API_KEY=test-key\nOPENVIKING_EXTRA_HEADERS=%s\n"+ % (endpoint, json.dumps({"CF-Access-Client-Id": "id.access"})),+ encoding="utf-8",+ )+ provider.initialize(session_id="startup-health", hermes_home=str(home), platform="cli")+ assert records, "startup should have probed /health"+ assert any(r.get("CF-Access-Client-Id") == "id.access" for r in records), (+ "every probe went out without the resolved headers: a gateway would refuse them all"+ )+ assert provider._client is not None, "provider dropped the client after a refused probe"+ assert provider._client._extra_headers == {"CF-Access-Client-Id": "id.access"}+ finally:+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)diff --git a/examples/hermes-plugin/tests/test_quick_local.py b/examples/hermes-plugin/tests/test_quick_local.pyindex 7afa3b0ab..af79b0d1e 100644--- a/examples/hermes-plugin/tests/test_quick_local.py+++ b/examples/hermes-plugin/tests/test_quick_local.py@@ -1069,6 +1069,7 @@ def test_managed_connection_ignores_foreign_env_and_saved_paths(tmp_path, monkey"account": "default","user": "default","agent": "hermes",+ "extra_headers": {},}assert (openviking_module._provider_ovcli_config_path({"deployment": quick_local.DEPLOYMENT})diff --git a/examples/hermes-plugin/tests/test_standalone.py b/examples/hermes-plugin/tests/test_standalone.pyindex 089fc672d..6ba9c798f 100644--- a/examples/hermes-plugin/tests/test_standalone.py+++ b/examples/hermes-plugin/tests/test_standalone.py@@ -1033,7 +1033,8 @@ def reload_provider(external_provider, monkeypatch):backend.post.return_value = {"result": {}}class Client:- def __init__(self, endpoint, api_key="", *, account="", user="", agent=""):+ def __init__(self, endpoint, api_key="", *, account="", user="", agent="", extra_headers=None):+ self._extra_headers = extra_headers or {}self._conn_snapshot = (endpoint, api_key, account, user, agent)self.get = backends[user].getself.post = backends[user].post