404 lines
15 KiB
Python
404 lines
15 KiB
Python
"""F454 PMDB Connector Plugin — Profil-Config + Token-Aufloesung.
|
|
|
|
@implements: [F454]
|
|
@implements: [F590]
|
|
@implements: [F-621]
|
|
|
|
V1 (Option A): 1:1-Mapping Hermes-Profil = PMDB-Agent-Name. Das aktive Profil
|
|
wird via `hermes_cli.profiles.get_active_profile_name()` ermittelt (HERMES_HOME-
|
|
basiert). Der zugehoerige Bearer-Token liegt in der Profile-Config:
|
|
|
|
~/.hermes/profiles/<name>/config.yaml
|
|
pmdb_connector:
|
|
base_url: "https://pmdb.myowntools.org/mcp"
|
|
manager_profiles: [bernd, andreas]
|
|
auth_keys:
|
|
default: "mcp_bernd_<geheimnis>"
|
|
miguel: "mcp_miguel_<geheimnis>"
|
|
rainer: "mcp_rainer_<geheimnis>"
|
|
finn: "mcp_finn_<geheimnis>"
|
|
don: "mcp_don_<geheimnis>"
|
|
|
|
V2 Stufe 1 (Plaintext Config) ist der aktuelle Stand. Stufe 2 (Secret-Source)
|
|
ist als verbindliche Erweiterung eingeplant (Rainers Architektur §2.3).
|
|
|
|
F590 (Token-Sync): Die KANONISCHE Token-Quelle ist jetzt ``mcp_tokens.json``
|
|
(~/.hermes/mcp_tokens.json, F531-Bootstrap-Store). ``resolve_token()`` liest
|
|
den Bearer-Token ZUERST aus ``mcp_tokens.json`` (agenten[<profil>].token) und
|
|
faellt nur noch bei Nicht-Fund auf die config.yaml-``auth_keys`` zurueck
|
|
(backward-compat). Das beseitigt den Token-Drift zwischen zwei Quellen
|
|
(P-NEW-3 / Daily Note 04.10.).
|
|
|
|
Sicherheits-Garantien (P-191/P-219-Schutz):
|
|
- Token wird NIE geloggt (nur Prefix `mcp_<kuerzel>_***`).
|
|
- Token erscheint NIE in Tool-Responses oder Fehlermeldungen.
|
|
- Fehlender Token -> strukturierter Error `token_missing` (kein Crash).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import os
|
|
from pathlib import Path
|
|
from typing import Any, Optional
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
DEFAULT_BASE_URL = "https://pmdb.myowntools.org/mcp"
|
|
|
|
|
|
def get_active_profile_name() -> str:
|
|
"""Ermittelt das aktive Hermes-Profil (HERMES_HOME-basiert).
|
|
|
|
Fallback-Kette (P-191: nie still scheitern):
|
|
1. hermes_cli.profiles.get_active_profile_name() (offizielle API)
|
|
2. HERMES_HOME-Pfad-Analyse (falls hermes_cli nicht importierbar)
|
|
3. "default"
|
|
"""
|
|
try:
|
|
from hermes_cli.profiles import get_active_profile_name as _gapn
|
|
return _gapn()
|
|
except Exception:
|
|
pass
|
|
home = os.environ.get("HERMES_HOME", "")
|
|
if home:
|
|
p = Path(home)
|
|
# ~/.hermes/profiles/<name> -> <name>
|
|
if p.parent.name == "profiles":
|
|
return p.name
|
|
return "default"
|
|
|
|
|
|
def _profile_config_path(profile: str) -> Optional[Path]:
|
|
"""Pfad zur Profile-Config (HERMES_HOME-basiert, P-119/P-147-sicher).
|
|
|
|
Zwei Faelle (P-119/P-147-Klasse — HERMES_HOME-Dopplung):
|
|
1. HERMES_HOME zeigt auf ein PROFIL-Verzeichnis
|
|
(~/.hermes/profiles/<name>) -> die Config liegt DIREKT dort
|
|
(HERMES_HOME/config.yaml). Es darf NICHT erneut `profiles/<name>`
|
|
angehaengt werden, sonst entsteht die Dopplung
|
|
`.../profiles/<name>/profiles/<name>/config.yaml`.
|
|
2. HERMES_HOME zeigt auf das BASIS-Verzeichnis (~/.hermes) ->
|
|
default: <base>/config.yaml
|
|
benannt: <base>/profiles/<name>/config.yaml
|
|
|
|
Ohne HERMES_HOME: Fallback auf ~/.hermes (analog Fall 2).
|
|
"""
|
|
home = os.environ.get("HERMES_HOME")
|
|
if home:
|
|
base = Path(home)
|
|
# Fall 1: HERMES_HOME ist bereits ein Profil-Verzeichnis.
|
|
if base.parent.name == "profiles":
|
|
return base / "config.yaml"
|
|
# Fall 2: Basis-Verzeichnis.
|
|
if profile == "default":
|
|
return base / "config.yaml"
|
|
return base / "profiles" / profile / "config.yaml"
|
|
# Kein HERMES_HOME: Fallback auf ~/.hermes.
|
|
base = Path.home() / ".hermes"
|
|
if profile == "default":
|
|
return base / "config.yaml"
|
|
return base / "profiles" / profile / "config.yaml"
|
|
|
|
|
|
def _load_yaml(path: Path) -> dict:
|
|
try:
|
|
import yaml
|
|
with open(path, encoding="utf-8") as f:
|
|
data = yaml.safe_load(f) or {}
|
|
return data if isinstance(data, dict) else {}
|
|
except Exception:
|
|
return {}
|
|
|
|
|
|
def load_pmdb_config(profile: str) -> dict:
|
|
"""Liest die `pmdb_connector`-Sektion aus der Profile-Config.
|
|
|
|
Liefert {} wenn keine Sektion existiert (Plugin deaktiviert sich dann
|
|
sauber mit token_missing).
|
|
"""
|
|
path = _profile_config_path(profile)
|
|
if path is None or not path.exists():
|
|
return {}
|
|
data = _load_yaml(path)
|
|
section = data.get("pmdb_connector")
|
|
return section if isinstance(section, dict) else {}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# F590: Kanonische Token-Quelle mcp_tokens.json (F531-Bootstrap-Store)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _mcp_tokens_path() -> Optional[Path]:
|
|
"""@implements F-590 — Pfad zur kanonischen mcp_tokens.json.
|
|
|
|
mcp_tokens.json liegt IMMER auf der Basis-Ebene (~/.hermes/mcp_tokens.json),
|
|
NICHT pro Profil. Env ``HERMES_MCP_TOKENS`` ueberschreibt den Pfad (fuer
|
|
Tests + Betrieb).
|
|
|
|
HERMES_HOME-Aufloesung (analog _base_config_path):
|
|
1. HERMES_HOME zeigt auf ein Profil-Verzeichnis
|
|
(~/.hermes/profiles/<name>) -> Basis ist der Parent-Parent
|
|
(~/.hermes/mcp_tokens.json).
|
|
2. HERMES_HOME zeigt auf die Basis (~/.hermes) -> direkt dort.
|
|
3. Ohne HERMES_HOME -> ~/.hermes/mcp_tokens.json.
|
|
"""
|
|
env = os.environ.get("HERMES_MCP_TOKENS")
|
|
if env:
|
|
return Path(env)
|
|
home = os.environ.get("HERMES_HOME")
|
|
if home:
|
|
base = Path(home)
|
|
if base.parent.name == "profiles":
|
|
return base.parent.parent / "mcp_tokens.json"
|
|
return base / "mcp_tokens.json"
|
|
return Path.home() / ".hermes" / "mcp_tokens.json"
|
|
|
|
|
|
def load_mcp_tokens() -> dict:
|
|
"""@implements F-590 — liest die ``agenten``-Sektion aus mcp_tokens.json.
|
|
|
|
Liefert {} wenn die Datei fehlt oder unlesbar/korrupt ist (kein Crash —
|
|
der Aufrufer faellt dann auf die config.yaml-``auth_keys`` zurueck).
|
|
"""
|
|
path = _mcp_tokens_path()
|
|
if path is None or not path.exists():
|
|
return {}
|
|
try:
|
|
with open(path, encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
except (OSError, ValueError, json.JSONDecodeError):
|
|
return {}
|
|
if not isinstance(data, dict):
|
|
return {}
|
|
agenten = data.get("agenten")
|
|
return agenten if isinstance(agenten, dict) else {}
|
|
|
|
|
|
def resolve_token_from_mcp_tokens(profile: str) -> Optional[str]:
|
|
"""@implements F-590 — loest den Bearer-Token aus mcp_tokens.json auf.
|
|
|
|
Exakter Match ``agenten[<profil>].token``, dann case-insensitiver Match
|
|
(P-194: Profil-/Agent-Namen sind case-inkonsistent). Liefert None wenn
|
|
das Profil nicht in mcp_tokens.json steht (der Aufrufer faellt dann auf
|
|
die config.yaml-``auth_keys`` zurueck).
|
|
"""
|
|
tokens = load_mcp_tokens()
|
|
if not tokens:
|
|
return None
|
|
entry = tokens.get(profile)
|
|
if not isinstance(entry, dict):
|
|
lower = (profile or "").strip().lower()
|
|
for key, val in tokens.items():
|
|
if (key or "").strip().lower() == lower and isinstance(val, dict):
|
|
entry = val
|
|
break
|
|
if isinstance(entry, dict):
|
|
token = entry.get("token")
|
|
if token:
|
|
return str(token).strip()
|
|
return None
|
|
|
|
|
|
def _base_config_path() -> Optional[Path]:
|
|
"""Pfad zur Basis-Config (~/.hermes/config.yaml bzw. HERMES_HOME-Basis).
|
|
|
|
F526: Wenn HERMES_HOME auf das BASIS-Verzeichnis (~/.hermes) zeigt (CLI-
|
|
Kontext) und das Profil als 'default' aufgeloest wurde, liegt der
|
|
profilspezifische Token moeglicherweise in einer ANDEREN Profile-Config
|
|
(z.B. ~/.hermes/profiles/rainer/config.yaml). Diese Funktion liefert den
|
|
Basis-Pfad fuer den Fallback in resolve_token().
|
|
"""
|
|
home = os.environ.get("HERMES_HOME")
|
|
if home:
|
|
base = Path(home)
|
|
# HERMES_HOME zeigt auf ein Profil-Verzeichnis -> Basis ist der Parent
|
|
# (~/.hermes/profiles/<name> -> ~/.hermes).
|
|
if base.parent.name == "profiles":
|
|
return base.parent / "config.yaml"
|
|
# HERMES_HOME ist bereits die Basis.
|
|
return base / "config.yaml"
|
|
return Path.home() / ".hermes" / "config.yaml"
|
|
|
|
|
|
def _profile_auth_keys(profile: str) -> dict:
|
|
"""Liest auth_keys aus der Profile-Config (fuer den Fallback-Lookup).
|
|
|
|
F526 Layer 1: Wenn die AKTUELLE Config kein auth_keys fuer das Profil hat,
|
|
prueft der Fallback, ob eine Profile-Config (~/.hermes/profiles/<profile>/
|
|
config.yaml) den Token traegt. Das ist der Fall bei 'HERMES_HOME=Basis +
|
|
profile!=default' (P-119/P-147-Luecke).
|
|
"""
|
|
path = _profile_config_path(profile)
|
|
if path is None or not path.exists():
|
|
return {}
|
|
data = _load_yaml(path)
|
|
section = data.get("pmdb_connector")
|
|
if not isinstance(section, dict):
|
|
return {}
|
|
auth_keys = section.get("auth_keys")
|
|
return auth_keys if isinstance(auth_keys, dict) else {}
|
|
|
|
|
|
def resolve_token(profile: str, config: dict) -> Optional[str]:
|
|
"""Waehlt den Bearer-Token fuer das Profil.
|
|
|
|
F590 (Token-Sync, Single Source of Truth): Die KANONISCHE Quelle ist
|
|
``mcp_tokens.json`` (agenten[<profil>].token). Nur bei Nicht-Fund greift
|
|
der config.yaml-Fallback (F526-Drei-Schichten, backward-compat):
|
|
|
|
1. mcp_tokens.json (kanonisch, F590)
|
|
2. auth_keys[<profile>] (profile-spezifisch in der AKTUELLEN Config)
|
|
3. auth_keys["default"] (Default der AKTUELLEN Config)
|
|
4. Basis-Config (~/.hermes/config.yaml) auth_keys[<profile>|default]
|
|
5. Profile-Config (~/.hermes/profiles/<profile>/config.yaml)
|
|
auth_keys[<profile>|default] — deckt 'HERMES_HOME=Basis + profile!=
|
|
default' ab (P-119/P-147-Luecke).
|
|
|
|
Liefert None, wenn kein Token gefunden wird (der Aufrufer meldet dann
|
|
strukturiert token_not_found_for_profile mit probierte_pfade).
|
|
"""
|
|
# 0. F590: kanonische Quelle mcp_tokens.json (beseitigt Token-Drift).
|
|
token = resolve_token_from_mcp_tokens(profile)
|
|
if token:
|
|
return token
|
|
|
|
auth_keys = config.get("auth_keys")
|
|
if not isinstance(auth_keys, dict):
|
|
auth_keys = {}
|
|
|
|
# 1. profile-spezifisch in der aktuellen Config.
|
|
token = auth_keys.get(profile)
|
|
if token:
|
|
return str(token).strip()
|
|
|
|
# 2. profile-spezifisch in der PROFILE-Config (HERMES_HOME=Basis + profile
|
|
# != default, P-119/P-147-Luecke). VOR dem 'default'-Fallback, damit bei
|
|
# profile='rainer' + Basis-Config ohne 'rainer'-Key der richtige Token
|
|
# aus ~/.hermes/profiles/rainer/config.yaml gewinnt (statt faelschlich
|
|
# den 'default'-Token eines ANDEREN Agenten zu laden).
|
|
if profile != "default":
|
|
prof_keys = _profile_auth_keys(profile)
|
|
if prof_keys.get(profile):
|
|
return str(prof_keys[profile]).strip()
|
|
|
|
# 3. default der aktuellen Config.
|
|
token = auth_keys.get("default")
|
|
if token:
|
|
return str(token).strip()
|
|
|
|
# 4. Basis-Config (auth_keys[<profile>|default]).
|
|
base_path = _base_config_path()
|
|
if base_path is not None and base_path.exists():
|
|
base_cfg = _load_yaml(base_path)
|
|
base_section = base_cfg.get("pmdb_connector")
|
|
if isinstance(base_section, dict):
|
|
base_keys = base_section.get("auth_keys")
|
|
if isinstance(base_keys, dict):
|
|
token = base_keys.get(profile) or base_keys.get("default")
|
|
if token:
|
|
return str(token).strip()
|
|
|
|
# 5. Profile-Config (auth_keys[<profile>|default]).
|
|
prof_keys = _profile_auth_keys(profile)
|
|
if prof_keys:
|
|
token = prof_keys.get(profile) or prof_keys.get("default")
|
|
if token:
|
|
return str(token).strip()
|
|
|
|
return None
|
|
|
|
|
|
def probierte_pfade(profile: str, config: dict) -> list[str]:
|
|
"""Liste der probierten Token-Pfade (fuer die strukturierte Diagnose).
|
|
|
|
F590: mcp_tokens.json steht an ERSTER Stelle (kanonische Quelle), danach
|
|
die config.yaml-Pfade (Fallback).
|
|
"""
|
|
pfade = []
|
|
mcp = _mcp_tokens_path()
|
|
if mcp is not None:
|
|
pfade.append(str(mcp))
|
|
path = _profile_config_path(profile)
|
|
if path is not None:
|
|
pfade.append(str(path))
|
|
base = _base_config_path()
|
|
if base is not None:
|
|
pfade.append(str(base))
|
|
return pfade
|
|
|
|
|
|
def token_prefix(token: str) -> str:
|
|
"""Maskierter Token-Prefix fuer Logs (P-191: nie Klartext loggen)."""
|
|
if not token:
|
|
return "<none>"
|
|
parts = token.split("_")
|
|
if len(parts) >= 2 and parts[0] == "mcp":
|
|
return f"mcp_{parts[1]}_***"
|
|
return token[:8] + "***"
|
|
|
|
|
|
def manager_profiles(config: dict) -> list:
|
|
"""Liste der Manager-Profile (Defense-in-Depth fuer Manager-only-Tools)."""
|
|
mp = config.get("manager_profiles")
|
|
if isinstance(mp, list):
|
|
return [str(x).strip().lower() for x in mp if x]
|
|
return ["bernd", "andreas"]
|
|
|
|
|
|
def base_url(config: dict) -> str:
|
|
url = config.get("base_url")
|
|
return str(url).rstrip("/") if url else DEFAULT_BASE_URL
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# F-621: SSE-Task-Dispatch-Stream-Konfiguration (opt-in, Stufe 1 Default aus)
|
|
# ---------------------------------------------------------------------------
|
|
DEFAULT_STREAM_BASE_URL = "http://192.168.180.49:8099"
|
|
|
|
# F-719: Interne Basis-URL fuer Anlagen-Endpunkte (gleiche IPv4 wie Stream).
|
|
DEFAULT_INTERNAL_BASE_URL = "http://192.168.180.49:8099"
|
|
|
|
|
|
def stream_enabled(config: dict) -> bool:
|
|
"""F-621: SSE-Stream-Listener aktivieren (opt-in).
|
|
|
|
Stufe 1 Default ist AUS (``False``) — das Polling bleibt das
|
|
Sicherheitsnetz. Erst Stufe 2 (persistente Verbindung + Cron-Fallback)
|
|
schaltet auf True als Default um (F-621 Architektur, 3-Stufen-Migration).
|
|
"""
|
|
v = config.get("stream_enabled")
|
|
if isinstance(v, bool):
|
|
return v
|
|
if isinstance(v, str):
|
|
return v.strip().lower() in ("1", "true", "yes", "on")
|
|
return False
|
|
|
|
|
|
def stream_base_url(config: dict) -> str:
|
|
"""F-621: Stream-Basis-URL (intern 192.168.180.49:8099).
|
|
|
|
Pitfall (F-621): Der Openresty-Proxy (pmdb.myowntools.org) blockt
|
|
Bearer-Stream mit 401 — der Stream MUSS intern via 192.168.180.49:8099
|
|
laufen. Config kann ``stream_url``/``stream_base_url`` ueberschreiben.
|
|
"""
|
|
url = config.get("stream_url") or config.get("stream_base_url")
|
|
if url:
|
|
return str(url).rstrip("/")
|
|
return DEFAULT_STREAM_BASE_URL
|
|
|
|
|
|
def internal_base_url(config: dict) -> str:
|
|
"""F-719: Interne Basis-URL fuer Anlagen-Endpunkte (192.168.180.49:8099).
|
|
|
|
Upload/Liste/Download von Task-Anlagen laufen IMMER ueber die direkte
|
|
IPv4 — der Openresty-Proxy blockt Bearer-Tokens (401, P-NEW-F563-PMDB-AUTH).
|
|
Config kann ``internal_base_url`` (oder ``attachment_base_url``) setzen;
|
|
Default ist die interne IPv4.
|
|
"""
|
|
url = config.get("internal_base_url") or config.get("attachment_base_url")
|
|
if url:
|
|
return str(url).rstrip("/")
|
|
return DEFAULT_INTERNAL_BASE_URL
|