The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): detect cross-profile credential collisions
KoNit-K54817f463b55
diff --git a/hermes_cli/doctor.py b/hermes_cli/doctor.pyindex 107b563b63a..1fcea9dac03 100644--- a/hermes_cli/doctor.py+++ b/hermes_cli/doctor.py@@ -49,6 +49,7 @@ from hermes_cli.doctor_tools import ()from hermes_cli.doctor_state import (_check_checkpoint_store,+ _check_cross_profile_gateway_credentials,_check_directory_structure,_check_memory_provider,_check_profiles,@@ -119,7 +120,7 @@ DOCTOR_CHECKS = (('External Tools', _check_git_and_rg), (None, _check_terminal_backend), (None, _check_node_and_browser),(None, _check_npm_audit), ('API Connectivity', _check_api_connectivity),('Tool Availability', _check_tool_availability), ('Skills Hub', _check_skills_hub),- ('Memory Provider', _check_memory_provider), (None, _check_profiles),+ ('Memory Provider', _check_memory_provider), (None, _check_profiles), (None, _check_cross_profile_gateway_credentials),)diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.pyindex df3c8f49316..349a290ef32 100644--- a/hermes_cli/doctor_state.py+++ b/hermes_cli/doctor_state.py@@ -572,3 +572,27 @@ def _check_profiles(should_fix: bool, f: Finding) -> None:_m = _re.search(r"hermes -p (\S+)", wrapper.read_text(encoding="utf-8"))if _m and not profile_exists(_m.group(1)):check_warn(f"Orphan alias: {wrapper.name} → profile '{_m.group(1)}' no longer exists")+++@doctor_check("") # Diagnostics must still finish if one profile's files are unreadable.+def _check_cross_profile_gateway_credentials(should_fix: bool, f: Finding) -> None:+ """Report bot credentials that would make local profile gateways fight each other."""+ from hermes_cli.profile_channels import scan_local_profile_credential_collisions++ report = scan_local_profile_credential_collisions()+ if not report.collisions and not report.unreadable_paths:+ return+ _section("Gateway Profile Credentials")+ if report.collisions:+ check_warn("Duplicate platform credentials across local profile homes", f"({report.format_for_display()})")+ f.manual_issues.append(+ "Duplicate gateway platform credentials across local profiles — give each profile its own bot "+ "credential or stop/remove the other profile gateway before starting it."+ )+ if report.unreadable_paths:+ paths = ", ".join(str(path) for path in report.unreadable_paths)+ check_warn("Could not inspect gateway credentials in local profile homes", f"({paths})")+ f.manual_issues.append(+ "Could not inspect one or more local profile homes for duplicate gateway credentials; "+ "check their path permissions and configuration files."+ )diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex e9bb7cc6c88..26e4db2d44d 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -1600,6 +1600,25 @@ def _print_other_profiles_gateway_status() -> None:pass+def _print_cross_profile_credential_warnings() -> None:+ """Surface bot-token collisions even when profile gateways run standalone."""+ try:+ from hermes_cli.profile_channels import scan_local_profile_credential_collisions++ report = scan_local_profile_credential_collisions()+ except Exception:+ return+ if not report.collisions and not report.unreadable_paths:+ return+ print()+ if report.collisions:+ print("⚠ Duplicate platform credentials across local profile homes")+ print(f" {report.format_for_display()}")+ print(" Give each profile its own bot credential, or stop/remove the other profile gateway.")+ if report.unreadable_paths:+ print("⚠ Could not inspect gateway credentials in: " + ", ".join(map(str, report.unreadable_paths)))++def _gateway_list() -> None:"""List every profile and whether its gateway is running."""try:@@ -5021,6 +5040,7 @@ def _cmd_status(args):print(" hermes gateway run # Run in foreground")_print_lines(*_STATUS_STOPPED_HINTS[_status_host_kind()])+ _print_cross_profile_credential_warnings()_print_other_profiles_gateway_status()diff --git a/hermes_cli/profile_channels.py b/hermes_cli/profile_channels.pyindex 70c8f12c476..41d8d35be2c 100644--- a/hermes_cli/profile_channels.py+++ b/hermes_cli/profile_channels.py@@ -22,6 +22,7 @@ from __future__ import annotationsimport contextlibimport loggingimport re+from dataclasses import dataclassfrom functools import partialfrom pathlib import Pathfrom typing import Dict, Iterable, List, Optional, Set, Tuple@@ -482,6 +483,87 @@ def shared_credential_warning(profile: str, platforms: List[str], source: str =)+@dataclass(frozen=True)+class ProfileCredentialCollision:+ """One platform credential claimed by more than one local profile home.++ ``paths`` intentionally names homes, not the credential or its fingerprint: doctor and+ gateway status must make the operator's next action clear without leaking a secret.+ """++ platform: str+ paths: tuple[Path, ...]+++@dataclass(frozen=True)+class LocalProfileCredentialCollisionReport:+ """Best-effort credential scan used by non-mutating diagnostic commands."""++ collisions: tuple[ProfileCredentialCollision, ...] = ()+ unreadable_paths: tuple[Path, ...] = ()++ def format_for_display(self) -> str:+ """Render only platform names and paths; never expose credentials or fingerprints."""+ return "; ".join(+ f"{collision.platform}: {', '.join(str(path) for path in collision.paths)}"+ for collision in self.collisions+ )+++def _local_profile_homes() -> tuple[tuple[str, Path], ...]:+ """Distinct default/named homes rooted at the local Hermes installation."""+ from hermes_cli.profiles import profiles_to_serve++ homes: list[tuple[str, Path]] = []+ seen: set[Path] = set()+ for name, home in profiles_to_serve(multiplex=True):+ try:+ key = home.resolve(strict=False)+ except OSError:+ key = home+ if key not in seen:+ seen.add(key)+ homes.append((name, home))+ return tuple(homes)+++def _profile_credential_claims(home: Path) -> set[tuple[str, str]]:+ """Read claims through the migration preflight's gateway fingerprint implementation."""+ from hermes_cli import gateway_migrate++ with gateway_migrate._multiplex_read_mode():+ return set(gateway_migrate._credential_claims(gateway_migrate._profile_gateway_config(home)))+++def scan_local_profile_credential_collisions() -> LocalProfileCredentialCollisionReport:+ """Find duplicate enabled platform credentials across local profile homes.++ The gateway migration preflight is the canonical source for both enabled-platform+ resolution and credential fingerprints. This scan deliberately uses the same path so a+ diagnostic warning agrees with the gateway's collision behaviour. A malformed or unreadable+ profile is reported separately while healthy homes continue to be scanned.+ """+ owners: dict[tuple[str, str], list[Path]] = {}+ unreadable: list[Path] = []+ for _name, home in _local_profile_homes():+ try:+ claims = _profile_credential_claims(home)+ except (OSError, ValueError, RuntimeError):+ unreadable.append(home)+ continue+ for claim in claims:+ owners.setdefault(claim, []).append(home)+ collisions = tuple(+ ProfileCredentialCollision(platform=platform, paths=tuple(paths))+ for (platform, _fingerprint), paths in sorted(owners.items())+ if len(paths) > 1+ )+ return LocalProfileCredentialCollisionReport(+ collisions=collisions,+ unreadable_paths=tuple(unreadable),+ )++def format_stripped_notice(profile: str, platforms: List[str], clone_flag: str = "--clone") -> List[str]:"""Lines printed after a channel-less clone so the user knows what was left behind and how toconfigure the new profile's own bots."""diff --git a/tests/hermes_cli/test_profile_credential_collisions.py b/tests/hermes_cli/test_profile_credential_collisions.pynew file mode 100644index 00000000000..776ca62a8b9--- /dev/null+++ b/tests/hermes_cli/test_profile_credential_collisions.py@@ -0,0 +1,94 @@+"""Regression coverage for cross-profile gateway credential diagnostics (#118388)."""++from __future__ import annotations++import io+from contextlib import redirect_stdout+from pathlib import Path++import hermes_constants+from hermes_cli import doctor_state, profile_channels+++def _profile_home(root: Path, name: str, token: str) -> Path:+ home = root if name == "default" else root / "profiles" / name+ home.mkdir(parents=True, exist_ok=True)+ (home / ".env").write_text(f"TELEGRAM_BOT_TOKEN={token}\n", encoding="utf-8")+ return home+++def test_scan_reports_duplicate_platform_credential_with_paths_not_secret(monkeypatch, tmp_path):+ root = tmp_path / ".hermes"+ default = _profile_home(root, "default", "123:shared-secret")+ worker = _profile_home(root, "worker", "123:shared-secret")+ monkeypatch.setenv("HERMES_HOME", str(root))+ monkeypatch.setattr(hermes_constants, "_default_hermes_root_memo", None)++ report = profile_channels.scan_local_profile_credential_collisions()++ assert [(collision.platform, collision.paths) for collision in report.collisions] == [+ ("telegram", (default, worker)),+ ]+ assert "shared-secret" not in report.format_for_display()+ assert str(default) in report.format_for_display()+ assert str(worker) in report.format_for_display()+++def test_scan_ignores_distinct_platform_credentials(monkeypatch, tmp_path):+ root = tmp_path / ".hermes"+ _profile_home(root, "default", "123:default-secret")+ _profile_home(root, "worker", "123:worker-secret")+ monkeypatch.setenv("HERMES_HOME", str(root))+ monkeypatch.setattr(hermes_constants, "_default_hermes_root_memo", None)++ report = profile_channels.scan_local_profile_credential_collisions()++ assert report.collisions == ()+ assert report.unreadable_paths == ()+++def test_scan_reports_unreadable_profile_without_hiding_other_collisions(monkeypatch, tmp_path):+ default = tmp_path / ".hermes"+ worker = default / "profiles" / "worker"+ broken = default / "profiles" / "broken"+ monkeypatch.setattr(+ profile_channels,+ "_local_profile_homes",+ lambda: (("default", default), ("worker", worker), ("broken", broken)),+ )+ monkeypatch.setattr(+ profile_channels,+ "_profile_credential_claims",+ lambda home: (+ {("telegram", "fingerprint")} if home != broken else (_ for _ in ()).throw(OSError("denied"))+ ),+ )++ report = profile_channels.scan_local_profile_credential_collisions()++ assert report.collisions[0].platform == "telegram"+ assert report.unreadable_paths == (broken,)+++def test_doctor_and_gateway_status_surface_collision_without_secret(monkeypatch, tmp_path):+ default = tmp_path / ".hermes"+ worker = default / "profiles" / "worker"+ report = profile_channels.LocalProfileCredentialCollisionReport(+ collisions=(profile_channels.ProfileCredentialCollision("telegram", (default, worker)),),+ )+ monkeypatch.setattr(profile_channels, "scan_local_profile_credential_collisions", lambda: report)++ doctor_output = io.StringIO()+ with redirect_stdout(doctor_output):+ findings = doctor_state._check_cross_profile_gateway_credentials(False)+ assert "Duplicate platform credentials" in doctor_output.getvalue()+ assert str(worker) in doctor_output.getvalue()+ assert findings.manual_issues++ from hermes_cli import gateway++ status_output = io.StringIO()+ with redirect_stdout(status_output):+ gateway._print_cross_profile_credential_warnings()+ assert "Duplicate platform credentials" in status_output.getvalue()+ assert "shared-secret" not in status_output.getvalue()