From b47fb2eba3974138fc28c1d4123b6f32196fa983 Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Sun, 13 Sep 2026 13:35:46 -0700 Subject: [PATCH] fix(profiles): clone builds in a hidden staging dir, never writes through symlinks, refuses --clone-channels in core; channel inventory is ownership-based Post-merge review of #109502 (gaoanze888) on current main, findings 1-3 and 5-11 (finding 4, the migrate manifest ordering, was already fixed by f9e47aa6feed). Why: - `--clone-all` used copytree(symlinks=True); a symlinked source `.env` was then edited THROUGH the link by the channel strip, deleting the SOURCE's bot token. Root files the clone edits (.env, config.yaml, auth.json, SOUL.md) are now materialized as private copies before any write. - The final profiles/ existed during the copy; the multiplexer rescans profiles/ on create (#109239) and could adopt the half-copied tree and start adapters on credentials not yet stripped. Clones are built in profiles/..staging- (a leading dot never matches _PROFILE_ID_RE, so profiles_to_serve never lists it) and published with one os.rename after the strip; a failed create removes the staging tree. - The live-multiplexer refusal for --clone-channels lived only in the CLI; REST (POST /api/profiles) and the TUI (profiles.create) bypassed it. It now lives in create_profile as profile_channels.clone_channels_refusal, raising ValueError which every surface already maps to a 400 / 4062. --clone-channels without a clone flag is an error instead of a silent no-op. - Channel inventory is ownership-based, evaluated in the SOURCE profile's plugin scope: private platform plugins under /plugins/ contribute their keys (previously discovered under the ambient HERMES_HOME); GATEWAY_ALLOW_ALL_USERS / GATEWAY_ALLOWED_USERS and GATEWAY_RELAY_ID/SECRET/DELIVERY_KEY are channel settings; alias prefixes SUPPLEMENT the canonical _ prefix (WECOM_DM_POLICY, SMS_WEBHOOK_PORT now stripped). Prefixes shared with tools (HASS_, TWILIO_, EMAIL_) are stripped only when the source's gateway would run that adapter (enabled in config, or complete credentials and not explicitly disabled); their allowlist/port keys are always channel-only. - --clone-all state removal handled files only; Google Chat's directory-shaped google_chat_user_tokens/ survived. Directories are removed too, without following a copied symlink. --- hermes_cli/AGENTS.md | 9 +- hermes_cli/profile_channels.py | 267 +++++++++++++----- hermes_cli/profile_cmd.py | 29 -- hermes_cli/profiles.py | 101 +++++-- .../hermes_cli/test_profile_clone_channels.py | 90 ++++++ website/docs/user-guide/profiles.md | 32 ++- 6 files changed, 409 insertions(+), 119 deletions(-) diff --git a/hermes_cli/AGENTS.md b/hermes_cli/AGENTS.md index fba35ecf04..9743fab5e0 100644 --- a/hermes_cli/AGENTS.md +++ b/hermes_cli/AGENTS.md @@ -133,8 +133,13 @@ matchers; parser-derived flag sets; never blanket-exclude gateway ancestors, #87 `_apply_profile_override()` in `hermes_cli/main.py` sets `HERMES_HOME` before any module import, so every `get_hermes_home()` scopes to the active profile (rules in root). Profiles are independent islands by design — no live config inheritance; `--clone` copies at creation, minus messaging -channels (`profile_channels.py` derives the token/allowlist/platform-section key set from the adapter -registry + `gateway/config_env._ENV_STEPS`, never a hand list; `--clone-channels` opts in). Multiplex +channels (`profile_channels.py`: ownership-based inventory evaluated in the SOURCE's plugin scope — +adapter-declared keys + canonical/alias prefixes + `GATEWAY_ALLOW*`/`GATEWAY_RELAY_*`; prefixes shared +with tools (`HASS_`/`TWILIO_`/`EMAIL_`) are stripped only when the source runs that adapter; never a hand +list). `--clone-channels` opts in and its live-multiplexer refusal lives in `create_profile` (CLI, REST +and TUI all go through it). Clones are built in `profiles/..staging-` (hidden → invisible to +`_iter_named_profile_dirs` and the hot-serve rescan) and published by one `os.rename` after the strip; +symlinked `.env`/`config.yaml` are materialized first so a clone never writes through to its source. Multiplex (`gateway.multiplex_profiles`) secret-scope rules: `gateway/AGENTS.md`. The served set is `profiles.py::profiles_to_serve(multiplex=True)` = default + every live (non-tombstoned) dir under `profiles/` — there is no allowlist (`gateway.multiplex_profile_allowlist` was retired in config v43). diff --git a/hermes_cli/profile_channels.py b/hermes_cli/profile_channels.py index dbf81f8872..70c8f12c47 100644 --- a/hermes_cli/profile_channels.py +++ b/hermes_cli/profile_channels.py @@ -2,11 +2,19 @@ A ``--clone``d profile that keeps the source's bot tokens, allowlists and platform state makes two gateways fight over one bot (standalone) or blocks ``hermes gateway migrate --multiplex`` with a -duplicate-credential finding per platform. The key set is DERIVED from the platform adapters — the -``Platform`` enum + plugin registry (``required_env``, allowlist/allow-all/home-channel env names), -the gateway env-override table (``gateway.config_env._ENV_STEPS`` / ``_ENV_ENABLE_CREDENTIALS``) and -the ``_`` env prefix every adapter's keys share — so a new adapter is covered without a -hand-written list. Model/provider keys, tool keys, memory and general config are never touched. +duplicate-credential finding per platform. + +The inventory is OWNERSHIP-based and evaluated in the SOURCE profile's plugin scope: every adapter +(built-in ``Platform`` member or plugin registered under the source's ``HERMES_HOME``) owns the env +keys it declares outright (``required_env``, allowlist / allow-all / home-channel names, the gateway +env-override table ``gateway.config_env._ENV_STEPS`` / ``_ENV_ENABLE_CREDENTIALS``) plus every key +under its canonical ``_`` prefix and its historical alias prefixes. Gateway-wide channel +policy (``GATEWAY_ALLOW_ALL_USERS`` / ``GATEWAY_ALLOWED_USERS``) and relay enrollment identity +(``GATEWAY_RELAY_*``) are channel settings too. A prefix an adapter SHARES with a non-channel +capability (``HASS_*`` is also the Home Assistant tool, ``TWILIO_*`` the telephony skill, ``EMAIL_*`` +mail-sending scripts) is stripped only when the source actually runs that adapter — the credential is +then the bot's identity; otherwise it is a tool key and survives. Model/provider keys, tool keys, +memory and general config are never touched. """ from __future__ import annotations @@ -20,17 +28,30 @@ from typing import Dict, Iterable, List, Optional, Set, Tuple logger = logging.getLogger(__name__) -# Platforms whose env names do not share the ``_`` prefix of their config id. The -# dashboard Channels page uses the same table to decide which Keys-page fields a card owns. +# Historical env prefixes that do not match a platform's config id. They SUPPLEMENT the canonical +# ``_`` prefix (``WECOM_DM_POLICY`` and ``SMS_WEBHOOK_PORT`` are wecom / sms keys too). _PLATFORM_ENV_PREFIX_ALIASES: dict[str, tuple[str, ...]] = { "email": ("EMAIL_",), "homeassistant": ("HASS_",), - "qqbot": ("QQ_", "QQBOT_"), + "qqbot": ("QQ_",), + "relay": ("GATEWAY_RELAY_",), "sms": ("TWILIO_",), - "wecom": ("WECOM_BOT_", "WECOM_SECRET"), - "wecom_callback": ("WECOM_CALLBACK_",), } +# Pseudo-platform for gateway-wide channel policy: not an adapter, but a clone that inherits the +# source's allow-all / allowlist boundary hands a freshly configured bot the source's authorization. +GATEWAY_POLICY_ID = "gateway" +_GATEWAY_POLICY_KEYS = ("GATEWAY_ALLOW_ALL_USERS", "GATEWAY_ALLOWED_USERS") + +# Prefixes a messaging adapter shares with a NON-channel capability. Their credentials belong to the +# channel only while the source runs that adapter; the adapter's policy keys are channel-only always. +_SHARED_WITH_TOOLS: dict[str, tuple[str, ...]] = { + "homeassistant": ("HASS_",), # tools/homeassistant_tool.py reads HASS_TOKEN / HASS_URL + "sms": ("TWILIO_",), # telephony skill reads TWILIO_ACCOUNT_SID / TWILIO_AUTH_TOKEN + "email": ("EMAIL_",), # mail-sending skills read EMAIL_ADDRESS / EMAIL_PASSWORD / EMAIL_SMTP_* +} +_POLICY_MARKERS = ("_ALLOWED_USERS", "_ALLOW_ALL_USERS", "_ALLOWED_CHATS", "_HOME_CHANNEL", "_HOME_ADDRESS") + # Multiplexer-owner settings: a clone of the default that inherits them and is then started # standalone tries to be a second multiplexer for every profile on the host. _GATEWAY_OWNER_KEYS = ("multiplex_profiles", "profile_routes") @@ -38,20 +59,43 @@ _GATEWAY_OWNER_KEYS = ("multiplex_profiles", "profile_routes") _ENV_LINE_RE = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=") +@contextlib.contextmanager +def _plugin_scope(source_dir: Optional[Path]): + """Evaluate adapter discovery in ``source_dir``'s plugin scope (its private ``plugins/``), not the + ambient profile's. ``None`` keeps the ambient scope.""" + if source_dir is None: + yield + return + from hermes_constants import reset_hermes_home_override, set_hermes_home_override + token = set_hermes_home_override(str(source_dir)) + try: + yield + finally: + reset_hermes_home_override(token) + + def platform_env_prefixes(platform_id: str) -> tuple[str, ...]: - """Env-var prefixes owned by one messaging platform.""" - return _PLATFORM_ENV_PREFIX_ALIASES.get(platform_id, (platform_id.upper().replace("-", "_") + "_",)) + """Env-var prefixes owned by one messaging platform: canonical ``_`` plus aliases.""" + canonical = platform_id.upper().replace("-", "_") + "_" + return (canonical, *_PLATFORM_ENV_PREFIX_ALIASES.get(platform_id, ())) -def platform_ids() -> List[str]: - """Every messaging platform id: built-in ``Platform`` members plus registered plugin adapters.""" - from gateway.config import Platform - ids = {m.value for m in Platform.__members__.values() if m.value != "local"} +def _registry_entries() -> list: with contextlib.suppress(Exception): from hermes_cli.plugins import discover_plugins - discover_plugins() # idempotent + discover_plugins() # idempotent per profile scope from gateway.platform_registry import platform_registry - ids.update(entry.name for entry in platform_registry.all_entries()) + return list(platform_registry.all_entries()) + return [] + + +def platform_ids(source_dir: Optional[Path] = None) -> List[str]: + """Every messaging platform id: built-in ``Platform`` members plus the plugin adapters registered + in ``source_dir``'s scope (ambient scope when ``None``).""" + from gateway.config import Platform + ids = {m.value for m in Platform.__members__.values() if m.value != "local"} + with _plugin_scope(source_dir): + ids.update(entry.name for entry in _registry_entries()) return sorted(ids) @@ -78,15 +122,13 @@ def _cred_row_envs(row) -> Set[str]: return names -def declared_channel_env_keys() -> Dict[str, str]: +def declared_channel_env_keys(source_dir: Optional[Path] = None) -> Dict[str, str]: """``{ENV_KEY: platform_id}`` for every env name an adapter declares outright (registry entry - fields, the gateway env-override table). Prefix matching covers the rest.""" - keys: Dict[str, str] = {} - with contextlib.suppress(Exception): - from hermes_cli.plugins import discover_plugins - discover_plugins() - from gateway.platform_registry import platform_registry - for entry in platform_registry.all_entries(): + fields, the gateway env-override table) plus gateway-wide channel policy. Prefix matching covers + the rest.""" + keys: Dict[str, str] = dict.fromkeys(_GATEWAY_POLICY_KEYS, GATEWAY_POLICY_ID) + with _plugin_scope(source_dir): + for entry in _registry_entries(): for name in (*entry.required_env, entry.allowed_users_env, entry.allow_all_env, entry.cron_deliver_env_var): if name: keys[name] = entry.name @@ -105,6 +147,23 @@ def declared_channel_env_keys() -> Dict[str, str]: return keys +def _policy_env_keys(source_dir: Optional[Path] = None) -> Set[str]: + """Allowlist / allow-all / home-channel names adapters declare — channel-only by nature.""" + names: Set[str] = set(_GATEWAY_POLICY_KEYS) + with _plugin_scope(source_dir): + for entry in _registry_entries(): + names.update(n for n in (entry.allowed_users_env, entry.allow_all_env, entry.cron_deliver_env_var) if n) + with contextlib.suppress(Exception): + from gateway import config_env + for step in config_env._ENV_STEPS: + if isinstance(step, config_env._Cred) and step.home: + names.update({step.home, f"{step.home}_NAME", f"{step.home}_THREAD_ID"}) + elif isinstance(step, partial) and step.keywords.get("env_base"): + base = step.keywords["env_base"] + names.update({base, f"{base}_NAME", f"{base}_THREAD_ID"}) + return names + + _CREDENTIAL_SUFFIXES = ( "_TOKEN", "_SECRET", "_KEY", "_PASSWORD", "_APP_ID", "_CLIENT_ID", "_BOT_ID", "_ACCOUNT_SID", "_SERVICE_ACCOUNT_JSON", "_PROJECT_ID", @@ -117,12 +176,8 @@ def credential_env_keys() -> Dict[str, str]: flags, URLs and hosts are excluded: two profiles pointing at one Mattermost server collide only when they also share the token.""" keys: Dict[str, str] = {} - with contextlib.suppress(Exception): - from hermes_cli.plugins import discover_plugins - discover_plugins() - from gateway.platform_registry import platform_registry - for entry in platform_registry.all_entries(): - keys.update(dict.fromkeys(entry.required_env, entry.name)) + for entry in _registry_entries(): + keys.update(dict.fromkeys(entry.required_env, entry.name)) with contextlib.suppress(Exception): from gateway import config_env for platform, names in config_env._ENV_ENABLE_CREDENTIALS.items(): @@ -138,21 +193,88 @@ def credential_env_keys() -> Dict[str, str]: return {key: pid for key, pid in keys.items() if key.endswith(_CREDENTIAL_SUFFIXES)} -class ChannelKeyIndex: - """Resolves an env key to the messaging platform that owns it (``None`` = not a channel key).""" +def _env_values(env_path: Path, wanted: Optional[Dict[str, str]] = None) -> Dict[str, str]: + """Non-blank assignments in ``env_path`` (restricted to ``wanted`` keys when given).""" + values: Dict[str, str] = {} + if not env_path.is_file(): + return values + from dotenv import dotenv_values + with contextlib.suppress(Exception): + for key, value in (dotenv_values(env_path, encoding="utf-8-sig") or {}).items(): + if (wanted is None or key in wanted) and value and value.strip(): + values[key] = value.strip() + return values - def __init__(self) -> None: - self.platforms = platform_ids() - self.declared = declared_channel_env_keys() + +def _explicit_enabled(raw: dict, pid: str) -> Optional[bool]: + """``platforms..enabled`` (either nesting) when the source config states it, else None.""" + gateway = raw["gateway"] if isinstance(raw.get("gateway"), dict) else {} + for section in (raw.get("platforms"), gateway.get("platforms")): + block = section.get(pid) if isinstance(section, dict) else None + if isinstance(block, dict) and "enabled" in block: + return bool(block["enabled"]) + return None + + +def _shared_adapters_active(source_dir: Optional[Path]) -> Set[str]: + """Shared-prefix platforms the SOURCE runs as a channel: explicitly enabled in its config.yaml, or + auto-enabled by a complete credential set in its ``.env`` and not explicitly disabled — the same + gate ``gateway.config_env._Cred`` applies at gateway start.""" + if source_dir is None: + return set(_SHARED_WITH_TOOLS) # no source to consult: the historical (strip) behaviour + raw: dict = {} + if (source_dir / "config.yaml").is_file(): + from hermes_cli.config import read_user_config_raw + with contextlib.suppress(Exception): + raw = read_user_config_raw(source_dir / "config.yaml") or {} + env = _env_values(source_dir / ".env") + creds_by_platform: Dict[str, Set[str]] = {} + with contextlib.suppress(Exception): + from gateway import config_env + for platform, names in config_env._ENV_ENABLE_CREDENTIALS.items(): + creds_by_platform[platform.value] = set(names) + with _plugin_scope(source_dir): + for entry in _registry_entries(): + creds_by_platform.setdefault(entry.name, set(entry.required_env)) + active: Set[str] = set() + for pid in _SHARED_WITH_TOOLS: + explicit = _explicit_enabled(raw, pid) + if explicit is not None: + if explicit: + active.add(pid) + continue + creds = creds_by_platform.get(pid) or set() + if creds and all(env.get(name) for name in creds): + active.add(pid) + return active + + +class ChannelKeyIndex: + """Resolves an env key to the messaging platform that owns it (``None`` = not a channel key), + evaluated in ``source_dir``'s plugin scope with the ownership rule for shared prefixes.""" + + def __init__(self, source_dir: Optional[Path] = None) -> None: + self.source_dir = source_dir + self.platforms = platform_ids(source_dir) + self.declared = declared_channel_env_keys(source_dir) + self.policy = _policy_env_keys(source_dir) + self.shared_active = _shared_adapters_active(source_dir) self._prefixes: List[Tuple[str, str]] = sorted( ((prefix, pid) for pid in self.platforms for prefix in platform_env_prefixes(pid)), key=lambda item: -len(item[0]), # longest prefix wins: WECOM_CALLBACK_ before WECOM_ ) def platform_for(self, key: str) -> Optional[str]: - if key in self.declared: - return self.declared[key] - return next((pid for prefix, pid in self._prefixes if key.startswith(prefix)), None) + pid = self.declared.get(key) or next((pid for prefix, pid in self._prefixes if key.startswith(prefix)), None) + if pid is None: + return None + shared = _SHARED_WITH_TOOLS.get(pid) + if shared and key.startswith(shared) and pid not in self.shared_active and not self._is_policy(key): + return None # a tool credential the source never used as a bot: keep it + return pid + + def _is_policy(self, key: str) -> bool: + return key in self.policy or any(marker in key for marker in _POLICY_MARKERS) def _env_key_of_line(line: str) -> Optional[str]: @@ -229,23 +351,31 @@ def strip_channel_config(config_path: Path, index: Optional[ChannelKeyIndex] = N def channel_state_entries(root: Path, index: Optional[ChannelKeyIndex] = None) -> List[Path]: """Root entries of a profile that hold per-bot runtime identity: pairing approvals and the WhatsApp device session (``platforms/`` + legacy dirs), the gateway's per-platform ledgers, - channel directories and every ``_*`` state file an adapter writes beside config.yaml.""" + channel directories and every ``_*`` file OR directory an adapter writes beside + config.yaml (Google Chat keeps user tokens in ``google_chat_user_tokens/``).""" if not root.is_dir(): return [] index = index or ChannelKeyIndex() fixed = {"platforms", "pairing", "whatsapp", "gateway", "channel_directory.json", "channel_aliases.json"} prefixes = tuple(f"{pid}_" for pid in index.platforms) - return sorted( - entry for entry in root.iterdir() - if entry.name in fixed or (entry.is_file() and entry.name.startswith(prefixes)) - ) + return sorted(entry for entry in root.iterdir() if entry.name in fixed or entry.name.startswith(prefixes)) -def strip_channel_settings(profile_dir: Path, *, include_state: bool) -> Dict[str, List[str]]: - """Strip channel credentials/identity from a freshly cloned profile. ``include_state`` also - drops the runtime state ``--clone-all`` copied. Returns ``{platform|"config"|"state": [what]}``.""" +def _remove_entry(entry: Path) -> None: + """Remove a state entry without following symlinks (``rmtree`` refuses a symlinked dir and would + otherwise leave the copied link in place; unlinking the link never touches the source).""" import shutil - index = ChannelKeyIndex() + if entry.is_symlink() or not entry.is_dir(): + entry.unlink(missing_ok=True) + else: + shutil.rmtree(entry, ignore_errors=True) + + +def strip_channel_settings(profile_dir: Path, *, include_state: bool, source_dir: Optional[Path] = None) -> Dict[str, List[str]]: + """Strip channel credentials/identity from a freshly cloned profile, judged in ``source_dir``'s + plugin scope. ``include_state`` also drops the runtime state ``--clone-all`` copied. Returns + ``{platform|"config"|"state": [what]}``.""" + index = ChannelKeyIndex(source_dir) stripped: Dict[str, List[str]] = dict(strip_channel_env_file(profile_dir / ".env", index)) config_paths = strip_channel_config(profile_dir / "config.yaml", index) if config_paths: @@ -253,7 +383,7 @@ def strip_channel_settings(profile_dir: Path, *, include_state: bool) -> Dict[st if include_state: dropped = [] for entry in channel_state_entries(profile_dir, index): - shutil.rmtree(entry, ignore_errors=True) if entry.is_dir() else entry.unlink(missing_ok=True) + _remove_entry(entry) dropped.append(entry.name) if dropped: stripped["state"] = dropped @@ -262,15 +392,15 @@ def strip_channel_settings(profile_dir: Path, *, include_state: bool) -> Dict[st def channel_platforms_configured(profile_dir: Path) -> List[str]: """Platform ids with any channel setting in ``profile_dir`` (.env keys or config.yaml sections) — - what a channel-less clone of it leaves behind. Pure read.""" - index = ChannelKeyIndex() + what a channel-less clone of it leaves behind. Pure read, in ``profile_dir``'s plugin scope.""" + index = ChannelKeyIndex(profile_dir) found: Set[str] = set() env_path = profile_dir / ".env" if env_path.is_file(): for line in env_path.read_text(encoding="utf-8-sig", errors="replace").splitlines(): key = _env_key_of_line(line) platform = index.platform_for(key) if key else None - if platform: + if platform and platform != GATEWAY_POLICY_ID: found.add(platform) config_path = profile_dir / "config.yaml" if config_path.is_file(): @@ -287,16 +417,27 @@ def channel_platforms_configured(profile_dir: Path) -> List[str]: return sorted(found) -def _env_values(env_path: Path, wanted: Dict[str, str]) -> Dict[str, str]: - values: Dict[str, str] = {} - if not env_path.is_file(): - return values - from dotenv import dotenv_values - with contextlib.suppress(Exception): - for key, value in (dotenv_values(env_path, encoding="utf-8-sig") or {}).items(): - if key in wanted and value and value.strip(): - values[key] = value.strip() - return values +def clone_channels_refusal(source_dir: Path, source_label: str) -> Optional[str]: + """Why ``--clone-channels`` must be refused for ``source_dir``: a live multiplexer already serves + the source, so the copied bot would be parked as a duplicate credential at once (the same finding + the migrate preflight reports). ``None`` when the copy is allowed. Shared by CLI, REST and TUI + through :func:`hermes_cli.profiles.create_profile`.""" + from hermes_cli.gateway_multiplex_served import recorded_served_profiles + from hermes_cli.profiles import normalize_profile_name + served = recorded_served_profiles() + if not served or len(served) < 2 or normalize_profile_name(source_label) not in { + normalize_profile_name(p) for p in served + }: + return None + platforms = channel_platforms_configured(source_dir) + if not platforms: + return None + return ( + f"--clone-channels would copy {', '.join(platforms)} from '{source_label}', which the running " + "multiplexed gateway already serves: the bot can only belong to one profile, so the copy would be " + "parked as a duplicate credential. Clone without --clone-channels and give the new profile its own bot " + "(hermes -p setup), or route its chats with gateway.profile_routes instead." + ) def _config_platform_tokens(config_path: Path) -> Dict[str, str]: diff --git a/hermes_cli/profile_cmd.py b/hermes_cli/profile_cmd.py index 228b389647..d45e8f1d22 100644 --- a/hermes_cli/profile_cmd.py +++ b/hermes_cli/profile_cmd.py @@ -165,31 +165,6 @@ def _source_profile_dir(source_label: str) -> Path: return source_dir -def _clone_channels_refusal(source_label: str) -> Optional[str]: - """``--clone-channels`` is refused when a live multiplexer already serves the source: the - duplicate adapter would be parked at once (same explanation the migrate preflight gives).""" - from hermes_cli.gateway_multiplex_served import recorded_served_profiles - from hermes_cli.profile_channels import channel_platforms_configured - from hermes_cli.profiles import normalize_profile_name - served = recorded_served_profiles() - if not served or len(served) < 2 or normalize_profile_name(source_label) not in { - normalize_profile_name(p) for p in served - }: - return None - try: - platforms = channel_platforms_configured(_source_profile_dir(source_label)) - except FileNotFoundError: - return None - if not platforms: - return None - return ( - f"Error: --clone-channels would copy {', '.join(platforms)} from '{source_label}', which the running " - "multiplexed gateway already serves: the bot can only belong to one profile, so the copy would be " - "parked as a duplicate credential. Clone without --clone-channels and give the new profile its own bot " - "(hermes -p setup), or route its chats with gateway.profile_routes instead." - ) - - def _print_channel_clone_notice(name: str, source_label: str, clone_channels: bool, clone_flag: str) -> None: from hermes_cli.profile_channels import ( channel_platforms_configured, format_stripped_notice, shared_channel_credentials, @@ -224,10 +199,6 @@ def _profile_create(args): clone_config = clone or clone_from is not None cloned = clone_config or clone_all source_label = clone_from or get_active_profile_name() - if clone_channels and cloned: - refusal = _clone_channels_refusal(source_label) - if refusal: - _die(refusal) try: profile_dir = create_profile( name=name, clone_from=clone_from, clone_all=clone_all, clone_config=clone_config, diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py index 02384dba8a..cd8e2d1294 100644 --- a/hermes_cli/profiles.py +++ b/hermes_cli/profiles.py @@ -750,10 +750,36 @@ def _clone_file(source_dir: Path, profile_dir: Path, relpath: str) -> None: os.chmod(str(dst), 0o600) +# Files a clone edits in place after copying. A ``--clone-all`` copy preserves symlinks +# (``symlinks=True``), so a symlinked source ``.env`` would otherwise be edited THROUGH the link and +# the channel stripping would mutate the SOURCE profile. These are materialized as real files first. +_CLONE_MATERIALIZE = (".env", "config.yaml", "auth.json", "SOUL.md") + + +def _materialize_symlinked_files(profile_dir: Path) -> List[str]: + """Replace symlinked root files the clone will edit with private copies of their targets (a + dangling link is dropped). Returns the relative names materialized.""" + done: List[str] = [] + for name in _CLONE_MATERIALIZE: + path = profile_dir / name + if not path.is_symlink(): + continue + target = Path(os.path.realpath(path)) + path.unlink() + if target.is_file(): + shutil.copy2(target, path) + done.append(name) + return done + + def _clone_all_into(source_dir: Path, profile_dir: Path, canon: str) -> None: """--clone-all: full copytree minus infrastructure/history, then strip runtime files and cloned single-use OAuth grants.""" shutil.copytree(source_dir, profile_dir, symlinks=True, ignore=_clone_all_copytree_ignore(source_dir)) + materialized = _materialize_symlinked_files(profile_dir) + if materialized: + logger.info("profile %s: materialized symlinked %s so the clone never writes through to %s", + canon, materialized, source_dir) # Excluded history dirs (sessions/, cron/) must still exist as empty dirs so the clone runs. for subdir in _PROFILE_DIRS: (profile_dir / subdir).mkdir(parents=True, exist_ok=True) @@ -811,6 +837,9 @@ def create_profile( "--no-skills is mutually exclusive with --clone / --clone-from / --clone-all " "(cloning explicitly copies skills from the source profile)." ) + cloning = clone_from is not None or clone_all or clone_config + if clone_channels and not cloning: + raise ValueError("--clone-channels only applies to a clone (--clone, --clone-from or --clone-all).") canon = _canon_valid(name) if canon == "default": raise ValueError("Cannot create a profile named 'default' — it is the built-in profile (~/.hermes).") @@ -823,20 +852,59 @@ def create_profile( shutil.rmtree(profile_dir) if profile_dir.exists(): raise FileExistsError(f"Profile '{canon}' already exists at {profile_dir}") + source_dir = _resolve_clone_source(clone_from) if cloning else None + if source_dir is not None and clone_channels: + from hermes_cli.profile_channels import clone_channels_refusal + refusal = clone_channels_refusal(source_dir, clone_from or get_active_profile_name() or "default") + if refusal: + raise ValueError(refusal) clear_named_profile_deleted(profile_dir) - source_dir = None - if clone_from is not None or clone_all or clone_config: - source_dir = _resolve_clone_source(clone_from) - if clone_all and source_dir: - _clone_all_into(source_dir, profile_dir, canon) - else: - _bootstrap_profile_dir(profile_dir, source_dir) - if source_dir is not None and not clone_channels: - from hermes_cli.profile_channels import strip_channel_settings - stripped = strip_channel_settings(profile_dir, include_state=clone_all) - if stripped: - logger.info("profile %s: cloned without messaging channels %s", canon, stripped) + # Build in a hidden sibling and publish with one rename: a running multiplexer rescans profiles/ + # on every create and every 30 s, and ``_iter_named_profile_dirs`` only lists valid ids (no leading + # dot), so it can never adopt the half-copied tree and start adapters on credentials the strip + # below has not removed yet. + staging = _clone_staging_dir(profile_dir) + try: + if clone_all and source_dir: + _clone_all_into(source_dir, staging, canon) + else: + _bootstrap_profile_dir(staging, source_dir) + if source_dir is not None and not clone_channels: + from hermes_cli.profile_channels import strip_channel_settings + stripped = strip_channel_settings(staging, include_state=clone_all, source_dir=source_dir) + if stripped: + logger.info("profile %s: cloned without messaging channels %s", canon, stripped) + _finish_profile_layout(staging, no_skills=no_skills, clone_all=clone_all, description=description) + os.rename(staging, profile_dir) + except BaseException: + shutil.rmtree(staging, ignore_errors=True) + raise + # Inside a container under s6, register the gateway as a runtime s6 service so + # `hermes -p gateway start` supervises via `s6-svc -u` instead of a bare + # process. No-op on host (systemd/launchd/windows unit generation handles lifecycle). + _maybe_register_gateway_service(canon) + # A running multiplexer enumerates profiles/ at boot: ask it to serve this one now (it also + # rescans periodically, so a missed signal only delays serving). + _notify_multiplexer(canon) + return profile_dir + + +def _clone_staging_dir(profile_dir: Path) -> Path: + """Fresh ``profiles/..staging-`` beside the final dir (same filesystem, so the publish + rename is atomic). A leftover from a crashed create is discarded.""" + staging = profile_dir.parent / f".{profile_dir.name}.staging-{os.getpid()}" + profile_dir.parent.mkdir(parents=True, exist_ok=True) + if staging.is_symlink() or staging.is_file(): + staging.unlink() + elif staging.is_dir(): + shutil.rmtree(staging, ignore_errors=True) + return staging + + +def _finish_profile_layout(profile_dir: Path, *, no_skills: bool, clone_all: bool, + description: Optional[str]) -> None: + """Seed files a fresh profile owns from day one; runs on the staging tree before publish.""" # Seed an empty .env so the profile owns a credentials file from day one. Without it, # profile-scoped env writes (dashboard Channels/Keys pages, `hermes -p auth add`) # had no file until first write and the profile silently inherited shell API keys — @@ -868,15 +936,6 @@ def create_profile( with contextlib.suppress(Exception): # non-fatal — `hermes profile describe` works later write_profile_meta(profile_dir, description=description.strip(), description_auto=False) - # Inside a container under s6, register the gateway as a runtime s6 service so - # `hermes -p gateway start` supervises via `s6-svc -u` instead of a bare - # process. No-op on host (systemd/launchd/windows unit generation handles lifecycle). - _maybe_register_gateway_service(canon) - # A running multiplexer enumerates profiles/ at boot: ask it to serve this one now (it also - # rescans periodically, so a missed signal only delays serving). - _notify_multiplexer(canon) - return profile_dir - def _notify_multiplexer(canon: str) -> None: from hermes_cli.gateway_multiplex_served import notify_multiplexer_profiles_changed diff --git a/tests/hermes_cli/test_profile_clone_channels.py b/tests/hermes_cli/test_profile_clone_channels.py index f26a5e4d19..8c82eb2a0a 100644 --- a/tests/hermes_cli/test_profile_clone_channels.py +++ b/tests/hermes_cli/test_profile_clone_channels.py @@ -120,3 +120,93 @@ def test_strip_env_file_keeps_comments_and_unknown_keys_verbatim(tmp_path): removed = strip_channel_env_file(env) assert removed == {"telegram": ["TELEGRAM_BOT_TOKEN"]} assert env.read_text(encoding="utf-8") == "# header\nexport OPENAI_API_KEY=abc\n\nMY_CUSTOM_THING=1\n" + + +# --- post-merge review of #109502 (gaoanze888): clone safety + ownership-based inventory --------- + + +def test_clone_all_never_writes_through_a_symlinked_source_env(home, tmp_path): + """A source whose ``.env`` is a symlink (shared secrets file) must keep its bot token: the clone + materializes the link before stripping instead of editing the target through it.""" + shared = tmp_path / "shared-secrets.env" + shared.write_text(_SOURCE_ENV, encoding="utf-8") + (home / ".env").unlink() + (home / ".env").symlink_to(shared) + + profile_dir = create_profile("full", clone_all=True, no_alias=True) + + assert shared.read_text(encoding="utf-8") == _SOURCE_ENV + assert not (profile_dir / ".env").is_symlink() + assert "TELEGRAM_BOT_TOKEN" not in (profile_dir / ".env").read_text(encoding="utf-8") + + +def test_clone_is_published_atomically_after_stripping(home, monkeypatch): + """The multiplexer enumerates ``profiles/`` while a clone is built; the final directory must not + exist (and no listable profile may appear) until the channel strip has run.""" + from hermes_cli import profile_channels, profiles + seen = {} + real_strip = profile_channels.strip_channel_settings + + def _observing_strip(profile_dir, **kw): + seen["final_exists"] = (home / "profiles" / "bot2").exists() + seen["served"] = [n for n, _ in profiles.profiles_to_serve(multiplex=True)] + seen["work_dir_hidden"] = profile_dir.name.startswith(".") + return real_strip(profile_dir, **kw) + + monkeypatch.setattr(profile_channels, "strip_channel_settings", _observing_strip) + profile_dir = create_profile("bot2", clone_config=True, no_alias=True) + + assert seen == {"final_exists": False, "served": ["default"], "work_dir_hidden": True} + assert profile_dir.is_dir() and [n for n, _ in profiles.profiles_to_serve(multiplex=True)] == ["default", "bot2"] + assert not [p for p in (home / "profiles").iterdir() if p.name.startswith(".")] + + +def test_clone_channels_refusal_lives_in_create_profile(home, monkeypatch): + """REST/TUI call ``create_profile`` directly: the live-multiplexer refusal must fire there, not + only in the CLI, and ``--clone-channels`` without a clone source is an error, not a no-op.""" + from hermes_cli import gateway_multiplex_served as served_mod + monkeypatch.setattr(served_mod, "recorded_served_profiles", lambda root=None: ["default", "other"]) + with pytest.raises(ValueError, match="already serves"): + create_profile("twin", clone_config=True, no_alias=True, clone_channels=True) + assert not (home / "profiles" / "twin").exists() + with pytest.raises(ValueError, match="only applies to a clone"): + create_profile("plain", no_alias=True, clone_channels=True) + # Without --clone-channels the same clone succeeds (the refusal is about the copy, not the clone). + assert create_profile("twin", clone_config=True, no_alias=True).is_dir() + + +_SHARED_ENV = ( + "OPENAI_API_KEY=sk\n" + "GATEWAY_ALLOW_ALL_USERS=true\nGATEWAY_ALLOWED_USERS=1,2\n" + "GATEWAY_RELAY_ID=gw-1\nGATEWAY_RELAY_SECRET=s\nGATEWAY_RELAY_DELIVERY_KEY=k\n" + "WECOM_DM_POLICY=open\nSMS_WEBHOOK_PORT=8700\n" + "HASS_TOKEN=hass-tool-token\nHASS_URL=http://ha.local\n" + "TWILIO_ACCOUNT_SID=AC1\nTWILIO_AUTH_TOKEN=tw\nTWILIO_PHONE_NUMBER=+1\n" + "EMAIL_ADDRESS=a@b\nEMAIL_PASSWORD=p\nEMAIL_SMTP_HOST=smtp\nEMAIL_IMAP_HOST=imap\nEMAIL_ALLOWED_USERS=x@y\n" +) + + +def test_ownership_inventory_strips_policy_relay_and_aliases_but_keeps_tool_credentials(home): + """Gateway-wide policy, relay identity and alias-prefixed keys are channel settings. HASS/TWILIO/EMAIL + credentials are shared with tools: they leave with the channel only when the source's gateway would + run that adapter (email here — complete creds, not disabled); an explicitly disabled channel means + the key is a tool credential and stays. Its policy keys (allowlists, ports) go regardless.""" + (home / ".env").write_text(_SHARED_ENV, encoding="utf-8") + (home / "config.yaml").write_text( + yaml.safe_dump({"model": {"default": "gpt-5", "provider": "openai"}, + "platforms": {"homeassistant": {"enabled": False}, "sms": {"enabled": False}}}), + encoding="utf-8") + + profile_dir = create_profile("bot3", clone_config=True, no_alias=True) + + keys = {line.split("=", 1)[0] for line in (profile_dir / ".env").read_text(encoding="utf-8").splitlines() + if "=" in line and not line.startswith("#")} + assert keys == {"OPENAI_API_KEY", "HASS_TOKEN", "HASS_URL", + "TWILIO_ACCOUNT_SID", "TWILIO_AUTH_TOKEN", "TWILIO_PHONE_NUMBER"} + + +def test_clone_all_drops_directory_shaped_channel_state(home): + (home / "google_chat_user_tokens").mkdir() + (home / "google_chat_user_tokens" / "u@x.json").write_text("{}", encoding="utf-8") + profile_dir = create_profile("full", clone_all=True, no_alias=True) + assert not (profile_dir / "google_chat_user_tokens").exists() diff --git a/website/docs/user-guide/profiles.md b/website/docs/user-guide/profiles.md index e2d5da0d16..251de3a771 100644 --- a/website/docs/user-guide/profiles.md +++ b/website/docs/user-guide/profiles.md @@ -102,11 +102,35 @@ hermes profile create twin --clone --clone-channels # keep the source's bots a ``` `--clone-channels` is refused when a running multiplexed gateway already serves the source -(the copy would be parked immediately) and otherwise prints a warning naming the platforms -now shared with the source. `hermes profile list` prints the same warning for any existing +(the copy would be parked immediately) — from the CLI, the dashboard and the TUI alike — and +otherwise prints a warning naming the platforms now shared with the source. It is an error +without a clone flag. `hermes profile list` prints the same warning for any existing profile whose bot credential is byte-identical to the default's, so older clones surface -before they bite. The key set is derived from the platform adapters themselves (registry -entries and the gateway's env table), so a newly added platform is covered automatically. +before they bite. + +**What counts as a channel setting** — the inventory is ownership-based and is judged in the +*source* profile's plugin scope (its private `plugins/` adapters included): + +- every key an adapter declares (tokens, app/client ids, allowlists, allow-all switches, home + channels) and every key under its `_` prefix, including historical aliases + (`WECOM_*`, `SMS_*`/`TWILIO_*`, `QQ_*`, `HASS_*`, `EMAIL_*`); +- gateway-wide channel policy `GATEWAY_ALLOW_ALL_USERS` / `GATEWAY_ALLOWED_USERS` and the + relay enrollment identity `GATEWAY_RELAY_ID` / `GATEWAY_RELAY_SECRET` / `GATEWAY_RELAY_DELIVERY_KEY`; +- for `--clone-all`, per-bot state files **and directories** (`platforms/`, pairing ledgers, + `google_chat_user_tokens/`, `_*`). + +Credentials that a messaging adapter shares with a non-channel capability — `HASS_TOKEN`/`HASS_URL` +(also the Home Assistant tool), `TWILIO_*` (also the telephony skill), `EMAIL_*` (also +mail-sending scripts) — are stripped **only when the source's gateway would run that adapter** +(the platform is enabled in its `config.yaml`, or its credential set is complete and not +explicitly disabled). A source with `platforms.homeassistant.enabled: false` uses `HASS_TOKEN` +as a tool key, so the clone keeps it. Allowlists and ports under those prefixes are always +channel-only and always stripped. + +Clones are built in a hidden staging directory beside `profiles/` and published with one +rename after the strip, so a running multiplexer (which rescans `profiles/` on create) can +never start adapters on a half-copied tree. A symlinked source `.env`/`config.yaml` is +materialized as a private copy first — the clone never writes through to the source. :::tip Honcho memory + profiles When Honcho is enabled, clone operations automatically create a dedicated AI peer for the new profile while sharing the same user workspace. Each profile builds its own observations and identity. See [Honcho -- Multi-agent / Profiles](./features/memory-providers.md#honcho) for details.