diff --git a/hermes_cli/config.py b/hermes_cli/config.py index 2e497b12d8e67..898ebaf30c598 100644 --- a/hermes_cli/config.py +++ b/hermes_cli/config.py @@ -3005,6 +3005,17 @@ def _ensure_hermes_home_managed(home: Path): }, }, + # Generic trusted-edge observability correlation. The secret key remains in + # HERMES_OBSERVABILITY_CORRELATION_HMAC_K1; config.yaml only controls which + # consumers may emit or persist the derived identifier. + "observability": { + "correlation": { + "scheme": "hmac-sha256-v1:k1", + "emitter_metadata_enabled": False, + "history_execution_writer_enabled": False, + }, + }, + # Real-time token streaming to messaging platforms (Telegram, Discord, # Slack, etc.). Read at the top level by the gateway; absent this block the # gateway falls back to these same defaults, so adding it here only makes @@ -4125,6 +4136,14 @@ def _ensure_hermes_home_managed(home: Path): "category": "tool", "advanced": True, }, + "HERMES_OBSERVABILITY_CORRELATION_HMAC_K1": { + "description": "K1 HMAC secret for trusted observability correlation (base64:)", + "prompt": "Observability correlation K1 HMAC secret", + "url": None, + "password": True, + "category": "tool", + "advanced": True, + }, # ── Messaging platforms ── "TELEGRAM_BOT_TOKEN": { @@ -5272,7 +5291,7 @@ def check_config_version() -> Tuple[int, int]: "fallback_providers", "credential_pool_strategies", "toolsets", "agent", "terminal", "display", "compression", "delegation", "auxiliary", "moa", "custom_providers", "context", "memory", "gateway", - "sessions", "streaming", "updates", "mcp_servers", + "observability", "sessions", "streaming", "updates", "mcp_servers", } # Valid fields inside a custom_providers list entry diff --git a/plugins/observability/langfuse/README.md b/plugins/observability/langfuse/README.md index 864735d968846..cc823b849f7e8 100644 --- a/plugins/observability/langfuse/README.md +++ b/plugins/observability/langfuse/README.md @@ -46,6 +46,43 @@ HERMES_LANGFUSE_MAX_CHARS=12000 # max chars per field (default: 12000) HERMES_LANGFUSE_DEBUG=true # verbose plugin logging ``` +## Trusted-edge correlation + +Correlation metadata is disabled by default. To emit a pseudonymous identifier +on Langfuse root traces, enable the generic observability gate in +`~/.hermes/config.yaml`: + +```yaml +observability: + correlation: + scheme: hmac-sha256-v1:k1 + emitter_metadata_enabled: true +``` + +Store the secret only in `~/.hermes/.env`: + +```bash +HERMES_OBSERVABILITY_CORRELATION_HMAC_K1=base64: +``` + +The decoded key must be 32–64 bytes. The payload accepts only `A-Z`, `a-z`, +`0-9`, `_`, and `-`; padding, whitespace, `+`, and `/` are rejected. Restart +Hermes after changing the gate or secret because the plugin loads this +configuration once when it registers. + +When enabled with a valid key, root metadata gains +`correlation_scheme: hmac-sha256-v1:k1` and a lowercase 64-hex +`correlation_id`. Missing or invalid configuration emits neither field and +leaves all existing Langfuse tracing behavior unchanged. + +### Privacy + +The HMAC key is never sent to Langfuse or written to `config.yaml`, and the +plugin does not log the key, task identifier, or derived digest. The digest is +a pseudonymous join key, not encryption; access to it should be limited to the +trusted observability systems that need correlation. Existing `task_id` +metadata remains in Langfuse for dashboard compatibility. + ## Disable ```bash diff --git a/plugins/observability/langfuse/__init__.py b/plugins/observability/langfuse/__init__.py index 31904d47e3052..83d15f0798474 100644 --- a/plugins/observability/langfuse/__init__.py +++ b/plugins/observability/langfuse/__init__.py @@ -19,9 +19,15 @@ HERMES_LANGFUSE_SAMPLE_RATE - sampling rate 0.0–1.0 (default: 1.0) HERMES_LANGFUSE_MAX_CHARS - max chars per field (default: 12000) HERMES_LANGFUSE_DEBUG - set to "true" for verbose logging + HERMES_OBSERVABILITY_CORRELATION_HMAC_K1 + - K1 HMAC key as base64: """ from __future__ import annotations +import base64 +import binascii +import hashlib +import hmac import json import logging import os @@ -52,6 +58,22 @@ class TraceState: last_updated_at: float = field(default_factory=time.time) +_CORRELATION_SCHEME = "hmac-sha256-v1:k1" +_CORRELATION_SECRET_ENV = "HERMES_OBSERVABILITY_CORRELATION_HMAC_K1" +_CORRELATION_MESSAGE_PREFIX = b"hermes-observability-correlation-hmac-v1\x00" +_CORRELATION_KEY_PAYLOAD_RE = re.compile(r"^[A-Za-z0-9_-]+$") + + +@dataclass(frozen=True) +class CorrelationConfig: + scheme: str = _CORRELATION_SCHEME + emitter_metadata_enabled: bool = False + hmac_key: Optional[bytes] = field(default=None, repr=False) + + +_CORRELATION_CONFIG = CorrelationConfig() + + _STATE_LOCK = threading.Lock() _TRACE_STATE: Dict[str, TraceState] = {} # Hard cap on live trace state. Each turn keys _TRACE_STATE by a unique @@ -92,6 +114,93 @@ def _env_bool(*names: str) -> bool: return False +def _parse_correlation_hmac_k1(value: Any) -> Optional[bytes]: + """Parse the strict, unpadded base64url K1 secret format.""" + if not isinstance(value, str) or not value.startswith("base64:"): + return None + + payload = value[len("base64:"):] + if not _CORRELATION_KEY_PAYLOAD_RE.fullmatch(payload): + return None + if len(payload) % 4 == 1: + return None + + try: + decoded = base64.b64decode( + payload + ("=" * (-len(payload) % 4)), + altchars=b"-_", + validate=True, + ) + except (binascii.Error, ValueError): + return None + + canonical = base64.urlsafe_b64encode(decoded).decode("ascii").rstrip("=") + if canonical != payload or not 32 <= len(decoded) <= 64: + return None + return decoded + + +def _load_correlation_config() -> CorrelationConfig: + """Load the immutable trusted-edge config once during plugin registration.""" + try: + from hermes_cli.config import load_config_readonly + + config = load_config_readonly() + except Exception: + return CorrelationConfig() + if not isinstance(config, dict): + return CorrelationConfig() + + observability = config.get("observability") + if not isinstance(observability, dict): + return CorrelationConfig() + + correlation = observability.get("correlation") + if not isinstance(correlation, dict): + return CorrelationConfig() + + scheme = correlation.get("scheme") + if not isinstance(scheme, str): + scheme = "" + enabled = correlation.get("emitter_metadata_enabled") is True + key = None + if enabled and scheme == _CORRELATION_SCHEME: + key = _parse_correlation_hmac_k1(os.environ.get(_CORRELATION_SECRET_ENV)) + return CorrelationConfig( + scheme=scheme, + emitter_metadata_enabled=enabled, + hmac_key=key, + ) + + +def _derive_correlation_id( + task_id: Any, + config: Optional[CorrelationConfig] = None, +) -> Optional[str]: + """Derive the K1 correlation digest without coercing or normalizing task IDs.""" + correlation = config if config is not None else _CORRELATION_CONFIG + key = correlation.hmac_key + if ( + correlation.emitter_metadata_enabled is not True + or correlation.scheme != _CORRELATION_SCHEME + or not isinstance(key, bytes) + or not 32 <= len(key) <= 64 + or not isinstance(task_id, str) + or not task_id + or task_id != task_id.strip() + or "\x00" in task_id + ): + return None + + try: + task_bytes = task_id.encode("utf-8", errors="strict") + except UnicodeEncodeError: + return None + + message = _CORRELATION_MESSAGE_PREFIX + task_bytes + return hmac.new(key, message, hashlib.sha256).hexdigest() + + def _debug_enabled() -> bool: return _env_bool("HERMES_LANGFUSE_DEBUG") @@ -615,6 +724,10 @@ def _start_root_trace(task_key: str, *, task_id: str, session_id: str, platform: "model": model, "api_mode": api_mode, } + correlation_id = _derive_correlation_id(task_id) + if correlation_id is not None: + metadata["correlation_scheme"] = _CORRELATION_SCHEME + metadata["correlation_id"] = correlation_id # session_id must be passed in trace_context for Langfuse session grouping. trace_ctx: Dict[str, Any] = {"trace_id": trace_id} @@ -663,7 +776,7 @@ def _start_root_trace(task_key: str, *, task_id: str, session_id: str, platform: except Exception: pass - _debug(f"started trace {trace_id} for {task_key}") + _debug(f"started trace {trace_id}") return TraceState(trace_id=trace_id, root_ctx=root_ctx, root_span=root_span) @@ -1126,6 +1239,8 @@ def on_post_tool_call(*, tool_name: str = "", args: Any = None, result: Any = No def register(ctx) -> None: + global _CORRELATION_CONFIG + _CORRELATION_CONFIG = _load_correlation_config() # Register for both hook name variants so the plugin works across # Hermes versions. pre_api_request / post_api_request fire per API # call (preferred); pre_llm_call / post_llm_call fire once per turn. diff --git a/tests/plugins/test_langfuse_plugin.py b/tests/plugins/test_langfuse_plugin.py index dd58149eba2e5..cfb616dfa934c 100644 --- a/tests/plugins/test_langfuse_plugin.py +++ b/tests/plugins/test_langfuse_plugin.py @@ -1,6 +1,7 @@ """Tests for the bundled observability/langfuse plugin.""" from __future__ import annotations +import base64 import importlib import logging import sys @@ -146,6 +147,251 @@ def test_get_langfuse_does_not_import_hermes_config(self, monkeypatch): ) +class TestTrustedEdgeCorrelation: + @staticmethod + def _fresh_plugin(): + mod_name = "plugins.observability.langfuse" + sys.modules.pop(mod_name, None) + return importlib.import_module(mod_name) + + @staticmethod + def _secret(key: bytes) -> str: + payload = base64.urlsafe_b64encode(key).decode("ascii").rstrip("=") + return f"base64:{payload}" + + @staticmethod + def _enabled_config(mod, key: bytes): + return mod.CorrelationConfig( + scheme="hmac-sha256-v1:k1", + emitter_metadata_enabled=True, + hmac_key=key, + ) + + @staticmethod + def _root_metadata(mod, monkeypatch, correlation_config, task_id="task-123"): + class FakeSpan: + def set_trace_io(self, **_kwargs): + return None + + class FakeContext: + def __init__(self): + self.span = FakeSpan() + + def __enter__(self): + return self.span + + class FakeClient: + def __init__(self): + self.root_calls = [] + + def create_trace_id(self, *, seed): + self.seed = seed + return "trace-1" + + def start_as_current_observation(self, **kwargs): + self.root_calls.append(kwargs) + return FakeContext() + + client = FakeClient() + monkeypatch.setattr(mod, "propagate_attributes", None) + monkeypatch.setattr(mod, "_CORRELATION_CONFIG", correlation_config) + mod._start_root_trace( + "task-key", + task_id=task_id, + session_id="session-1", + platform="cli", + provider="openrouter", + model="test-model", + api_mode="chat_completions", + messages=[{"role": "user", "content": "hello"}], + client=client, + ) + return client.root_calls[0] + + def test_strict_k1_secret_parser_accepts_canonical_32_to_64_byte_keys(self): + mod = self._fresh_plugin() + + for key in (b"3" * 32, b"6" * 64): + assert mod._parse_correlation_hmac_k1(self._secret(key)) == key + + def test_strict_k1_secret_parser_rejects_invalid_encodings_and_lengths(self): + mod = self._fresh_plugin() + canonical_32 = self._secret(b"6" * 32) + payload_32 = canonical_32.removeprefix("base64:") + noncanonical_32 = f"base64:{payload_32[:-1]}h" + + invalid = [ + None, + b"not-a-string", + "", + "base64:", + canonical_32 + "=", + canonical_32 + " ", + " " + canonical_32, + "base64:AA+_", + "base64:AA/_", + "base64:A", + self._secret(b"3" * 31), + self._secret(b"7" * 65), + noncanonical_32, + ] + for value in invalid: + assert mod._parse_correlation_hmac_k1(value) is None + + def test_frozen_k1_vector(self): + mod = self._fresh_plugin() + config = self._enabled_config(mod, b"6" * 64) + + assert mod._derive_correlation_id("task-123", config) == ( + "dcceed6ab66a3b83dffcb3487ec7b84761456033dd804ce5f14709279ebdcb4c" + ) + assert mod._derive_correlation_id("TASK-123", config) != ( + mod._derive_correlation_id("task-123", config) + ) + + @pytest.mark.parametrize( + "task_id", + [None, 123, "", " ", " task-123", "task-123 ", "task\x00-123", "\ud800"], + ) + def test_invalid_task_ids_do_not_derive(self, task_id): + mod = self._fresh_plugin() + config = self._enabled_config(mod, b"6" * 64) + + assert mod._derive_correlation_id(task_id, config) is None + + def test_disabled_missing_key_and_wrong_scheme_do_not_derive(self): + mod = self._fresh_plugin() + key = b"6" * 64 + + configs = [ + mod.CorrelationConfig( + scheme="hmac-sha256-v1:k1", + emitter_metadata_enabled=False, + hmac_key=key, + ), + mod.CorrelationConfig( + scheme="hmac-sha256-v1:k1", + emitter_metadata_enabled=True, + hmac_key=None, + ), + mod.CorrelationConfig( + scheme="HMAC-SHA256-V1:K1", + emitter_metadata_enabled=True, + hmac_key=key, + ), + ] + assert all( + mod._derive_correlation_id("task-123", config) is None + for config in configs + ) + + def test_valid_k1_adds_only_generic_correlation_metadata(self, monkeypatch): + mod = self._fresh_plugin() + call = self._root_metadata( + mod, + monkeypatch, + self._enabled_config(mod, b"6" * 64), + ) + + assert call["trace_context"]["session_id"] == "session-1" + assert call["metadata"]["task_id"] == "task-123" + assert call["metadata"]["correlation_scheme"] == "hmac-sha256-v1:k1" + assert call["metadata"]["correlation_id"] == ( + "dcceed6ab66a3b83dffcb3487ec7b84761456033dd804ce5f14709279ebdcb4c" + ) + assert not any("zebi" in key.lower() for key in call["metadata"]) + assert "history_execution_writer_enabled" not in call["metadata"] + + def test_invalid_or_disabled_config_omits_both_metadata_fields(self, monkeypatch): + mod = self._fresh_plugin() + configs = [ + mod.CorrelationConfig(), + mod.CorrelationConfig( + scheme="hmac-sha256-v1:k1", + emitter_metadata_enabled=True, + hmac_key=None, + ), + ] + + for config in configs: + call = self._root_metadata(mod, monkeypatch, config) + assert "correlation_scheme" not in call["metadata"] + assert "correlation_id" not in call["metadata"] + call = self._root_metadata( + mod, + monkeypatch, + self._enabled_config(mod, b"6" * 64), + task_id=" task-123", + ) + assert "correlation_scheme" not in call["metadata"] + assert "correlation_id" not in call["metadata"] + + def test_register_loads_and_caches_correlation_config_once(self, monkeypatch): + mod = self._fresh_plugin() + config_mod = importlib.import_module("hermes_cli.config") + + loads = {"count": 0} + + def fake_load_config(): + loads["count"] += 1 + return { + "observability": { + "correlation": { + "scheme": "hmac-sha256-v1:k1", + "emitter_metadata_enabled": True, + }, + }, + } + + class FakeContext: + def __init__(self): + self.hooks = {} + + def register_hook(self, name, hook): + self.hooks[name] = hook + + monkeypatch.setattr(config_mod, "load_config_readonly", fake_load_config) + monkeypatch.setenv( + "HERMES_OBSERVABILITY_CORRELATION_HMAC_K1", + self._secret(b"6" * 64), + ) + ctx = FakeContext() + mod.register(ctx) + + monkeypatch.setenv( + "HERMES_OBSERVABILITY_CORRELATION_HMAC_K1", + self._secret(b"7" * 64), + ) + assert mod._derive_correlation_id("task-123") == ( + "dcceed6ab66a3b83dffcb3487ec7b84761456033dd804ce5f14709279ebdcb4c" + ) + assert loads["count"] == 1 + assert set(ctx.hooks) == { + "pre_api_request", + "post_api_request", + "pre_llm_call", + "post_llm_call", + "pre_tool_call", + "post_tool_call", + } + + def test_config_defaults_schema_and_secret_metadata(self): + from hermes_cli.config import ( + DEFAULT_CONFIG, + OPTIONAL_ENV_VARS, + _KNOWN_ROOT_KEYS, + ) + + correlation = DEFAULT_CONFIG["observability"]["correlation"] + assert correlation == { + "scheme": "hmac-sha256-v1:k1", + "emitter_metadata_enabled": False, + "history_execution_writer_enabled": False, + } + assert "observability" in _KNOWN_ROOT_KEYS + secret = OPTIONAL_ENV_VARS["HERMES_OBSERVABILITY_CORRELATION_HMAC_K1"] + assert secret["password"] is True + # --------------------------------------------------------------------------- # Hooks are inert when the client is unavailable. # ---------------------------------------------------------------------------