api_server_profile_prefix.py 3.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """``/p/<profile>/`` prefix resolution for the shared api_server listener."""
  2. import logging
  3. from typing import Any
  4. logger = logging.getLogger(__name__)
  5. # The @handle Bot Mode advertises a host's default profile under (apps/desktop hermes-bots
  6. # ``botHandle``). New profiles cannot take the name, but a pre-reservation profiles/hermes can exist.
  7. DEFAULT_PROFILE_HANDLE = "hermes"
  8. # 404 body for a prefix naming no profile here. Older gateways also send it for a 'hermes' profile
  9. # they do not serve, so peer clients treat it as ambiguous and never reroute @hermes on it.
  10. UNKNOWN_PROFILE_ERROR = "Unknown or unconfigured profile"
  11. def _handle_is_free() -> bool:
  12. """The handle aliases the default profile only on a host with no profile of that name: a
  13. pre-reservation ``profiles/hermes`` (served, parked or standalone) keeps it, so its traffic is
  14. never answered by the default profile. Fail closed: unknown counts as taken."""
  15. try:
  16. from hermes_cli.profiles import profile_exists
  17. return not profile_exists(DEFAULT_PROFILE_HANDLE)
  18. except Exception:
  19. logger.warning("Cannot check for a '%s' profile", DEFAULT_PROFILE_HANDLE, exc_info=True)
  20. return False
  21. def _prefix_profile(request: Any) -> str:
  22. """The prefix as a canonical profile id. Profile ids are lowercase on disk and every other
  23. reader (``get_profile_dir``, ``profile_exists``, the peer client) normalizes case, so
  24. ``/p/Hermes/`` must name the same profile ``/p/hermes/`` does, never fall to the alias."""
  25. raw = (request.match_info.get("profile") or "").strip()
  26. if not raw:
  27. return ""
  28. from hermes_cli.profiles import normalize_profile_name
  29. return normalize_profile_name(raw)
  30. def rejection_response(request: Any):
  31. """The 404 for a rejected prefix. A 'hermes' profile this gateway does not serve gets its own
  32. body, so a peer reads it as "exists elsewhere", never as "no such profile, use default"."""
  33. from aiohttp import web
  34. if _prefix_profile(request) == DEFAULT_PROFILE_HANDLE and not _handle_is_free():
  35. return web.json_response({"error": {
  36. "message": f"Profile '{DEFAULT_PROFILE_HANDLE}' exists on this host but this gateway does not serve it",
  37. "code": "profile_not_served"}}, status=404)
  38. return web.json_response({"error": UNKNOWN_PROFILE_ERROR}, status=404)
  39. def resolve_request_profile(adapter: Any, request: Any):
  40. """Resolve + validate the /p/<profile>/ prefix: ``None`` (no prefix, or multiplexing off and the
  41. prefix names this gateway's own profile), the served profile name, or ``_PROFILE_REJECTED``
  42. (-> 404). Fail closed: a foreign prefix must never be ignored. The default profile's handle
  43. ``hermes`` reaches the default profile, because peers address the mirror by the handle their
  44. roster shows (#118076), unless the host has a profile literally named ``hermes``."""
  45. from gateway.platforms.api_server import _PROFILE_REJECTED, _prefix_names_served_profile
  46. profile = _prefix_profile(request)
  47. if not profile:
  48. return None
  49. alias = profile == DEFAULT_PROFILE_HANDLE
  50. cfg = getattr(adapter.gateway_runner, "config", None)
  51. if not getattr(cfg, "multiplex_profiles", False):
  52. served = _prefix_names_served_profile(profile) or (
  53. alias and _prefix_names_served_profile("default") and _handle_is_free())
  54. return None if served else _PROFILE_REJECTED
  55. try:
  56. from hermes_cli.profiles import profiles_to_serve
  57. served = {name for name, _ in profiles_to_serve(multiplex=True)}
  58. except Exception:
  59. # Fail closed: a prefix this gateway cannot prove it serves is a 404.
  60. logger.warning("Cannot list served profiles for /p/%s/", profile, exc_info=True)
  61. return _PROFILE_REJECTED
  62. if profile in served:
  63. return profile
  64. if alias and "default" in served and _handle_is_free():
  65. return "default"
  66. return _PROFILE_REJECTED