session_identity.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. """One frozen routing identity per inbound gateway event.
  2. A multiplexed gateway answers three questions about every event, and until now answered them in
  3. three places that only agreed because they read the same fallback chain: WHICH bot received it
  4. (``_transport_owner``), WHO may admit it (``_authorization_home_for_source``) and WHERE the turn
  5. runs (``_resolve_profile_home_for_source`` / ``_session_key_profile``). :func:`resolve_identity`
  6. answers all three once and pins the result on the source as a wire-invisible dynamic attribute
  7. (like ``_transport_adapter_ref``); the existing helpers read it when present and keep their
  8. fallback chain when absent, so a source built outside the runner still resolves as before.
  9. ``SessionSource.profile`` stays the serialized runtime profile — ``None`` on the wire means the
  10. receiving bot's own profile — so nothing here changes the wire format or any historical
  11. ``agent:main`` key.
  12. """
  13. from __future__ import annotations
  14. import dataclasses
  15. import hashlib
  16. import json
  17. import logging
  18. from contextlib import suppress
  19. import weakref
  20. from dataclasses import dataclass, field
  21. from pathlib import Path
  22. from typing import TYPE_CHECKING, Any, Optional
  23. if TYPE_CHECKING:
  24. from gateway.session import SessionSource
  25. logger = logging.getLogger(__name__)
  26. _IDENTITY_ATTR = "_identity"
  27. # Wire-invisible provenance copied alongside the identity when a source is duplicated.
  28. _PROVENANCE_ATTRS = ("_transport_adapter_ref", "_authorization_profile_home", _IDENTITY_ATTR)
  29. class IdentityUnresolved(RuntimeError):
  30. """Under multiplexing the event's runtime profile could not be established (an explicit
  31. ``profile_routes`` entry targets a profile this gateway does not serve). Callers drop the
  32. event; it must never fall through to the default profile."""
  33. @dataclass(frozen=True)
  34. class RoutingIdentity:
  35. """Everything a turn needs to know about who it is, resolved once at ingress.
  36. ``transport_profile`` owns the receiving adapter (its credential and allowlist);
  37. ``runtime_profile`` is the profile that executes the turn — the same name unless a
  38. ``profile_routes`` entry re-homed the event. Both are explicit (``"default"`` is spelled out);
  39. ``None`` never means default here. ``multiplexed`` is False for a standalone gateway, whose
  40. keys stay in the legacy ``agent:main`` namespace whatever profile it was launched with.
  41. """
  42. transport_profile: str
  43. runtime_profile: str
  44. authorization_home: Path
  45. runtime_home: Path
  46. multiplexed: bool = True
  47. # Receiving adapter; None for restored/synthetic sources (no live provenance → fail closed).
  48. # Provenance, not identity: two events from the same bot share one identity.
  49. transport: Optional[weakref.ref] = field(default=None, compare=False, hash=False)
  50. # True when nothing named the receiving bot (no live adapter, no persisted transport_profile,
  51. # no explicit hint) and ``transport_profile`` is the primary by default. A hand-built or
  52. # pre-column source. Delivery may still fall back to the runtime profile's unique adapter for
  53. # these; an identity whose transport is KNOWN (live or restored) never does.
  54. transport_inferred: bool = field(default=False, compare=False, hash=False)
  55. @property
  56. def namespace(self) -> str:
  57. """``agent:<ns>`` prefix for this identity's session keys — byte-identical to
  58. :func:`gateway.session._session_key_namespace` for every historical key."""
  59. from gateway.session import _session_key_namespace
  60. return _session_key_namespace(self.session_key_profile)
  61. @property
  62. def store_path(self) -> Path:
  63. return self.runtime_home / "state.db"
  64. @property
  65. def session_key_profile(self) -> Optional[str]:
  66. """The ``profile=`` argument :func:`gateway.session.build_session_key` expects for this
  67. identity: the runtime profile under multiplexing, else ``None`` (legacy namespace)."""
  68. return self.runtime_profile if self.multiplexed else None
  69. def adapter(self) -> Any:
  70. """The live receiving adapter, or None when it is gone or was never known."""
  71. return self.transport() if self.transport is not None else None
  72. def identity_of(source: Any) -> Optional[RoutingIdentity]:
  73. """The identity pinned on *source* by :func:`resolve_identity`, if any."""
  74. identity = getattr(source, _IDENTITY_ATTR, None)
  75. return identity if isinstance(identity, RoutingIdentity) else None
  76. def clear_identity(source: Any) -> None:
  77. """Drop the pinned identity AND the routed runtime profile so the next :func:`canonical_identity`
  78. re-routes from scratch — for sources a caller reuses across events whose routing may differ (a
  79. guild's cached voice source is shared by every speaker, and ``profile_routes[].user_id`` routes
  80. per speaker). ``source.profile`` is the previous event's routing *result*; left in place it
  81. short-circuits the route and the new speaker runs as the old one."""
  82. for attr in (_IDENTITY_ATTR, "profile_route_rejected", "_authorization_profile_home", "_rejected_route_profile"):
  83. with suppress(AttributeError):
  84. delattr(source, attr)
  85. with suppress(AttributeError):
  86. source.profile = None
  87. def transport_profile_of(source: Any) -> Optional[str]:
  88. """The receiving bot's profile to persist alongside a routing entry (``SessionEntry.transport_profile``,
  89. ``sessions.transport_profile``): the bot a live adapter or a persisted record named. None outside
  90. multiplexing, when nothing resolved the source, or when a messaging transport was only inferred:
  91. a restored row is trusted as the receiving bot, so the primary-profile guess must never be saved.
  92. A LOCAL chat has no bot; its inferred transport is the launch profile's authority (#139060), a fact."""
  93. from gateway.config import Platform
  94. identity = identity_of(source)
  95. if identity is None or not identity.multiplexed:
  96. return None
  97. if identity.transport_inferred and getattr(source, "platform", None) != Platform.LOCAL:
  98. return None
  99. return identity.transport_profile
  100. def replace_source(source: SessionSource, **changes: Any) -> SessionSource:
  101. """:func:`dataclasses.replace` that keeps the wire-invisible provenance (transport ref,
  102. authorization home, identity). A plain ``replace`` silently produces a source the runner
  103. can only route through heuristics."""
  104. copied = dataclasses.replace(source, **changes)
  105. for name in _PROVENANCE_ATTRS:
  106. value = getattr(source, name, None)
  107. if value is not None:
  108. setattr(copied, name, value)
  109. return copied
  110. def _name(value: Any) -> Optional[str]:
  111. text = value.strip() if isinstance(value, str) else ""
  112. return text or None
  113. def canonical_identity(
  114. source: SessionSource, *, runner: Any, adapter: Any = None,
  115. transport_profile: Optional[str] = None, primary_home: Optional[Path] = None,
  116. ) -> Optional[RoutingIdentity]:
  117. """The identity already pinned on *source*, else :func:`resolve_identity` — the one call every
  118. ingress path makes FIRST, before any key is derived. ``None`` = unresolved under multiplexing
  119. (``source.profile_route_rejected`` is set): the caller drops the event and says so once; it
  120. must never fall through to ``agent:main``."""
  121. identity = identity_of(source)
  122. if identity is not None:
  123. return identity
  124. try:
  125. return resolve_identity(
  126. source, runner=runner, adapter=adapter, transport_profile=transport_profile,
  127. primary_home=primary_home)
  128. except IdentityUnresolved as exc:
  129. logger.debug("identity unresolved: %s", exc)
  130. return None
  131. def restore_identity(
  132. source: SessionSource, *, runner: Any, transport_profile: Optional[str],
  133. ) -> Optional[RoutingIdentity]:
  134. """Pin the identity of a source rebuilt from durable state (``SessionEntry.origin``, a
  135. ``sessions`` row, a cached copy) — no live adapter, so ``transport=None``: the restored row of the
  136. transport matrix, where delivery goes through the persisted transport owner or fails closed.
  137. *transport_profile* is what the routing index persisted at ingress (``SessionEntry.transport_profile``);
  138. ``None`` = a row written before the column existed, whose transport is unknown → nothing is pinned
  139. and the legacy heuristics (``_is_shared_bot_satellite``) keep deciding. Standalone gateways have
  140. nothing to restore (one bot, one home).
  141. """
  142. transport_name = _name(transport_profile)
  143. if transport_name is None:
  144. return None
  145. if not bool(getattr(getattr(runner, "config", None), "multiplex_profiles", False)):
  146. return None
  147. existing = identity_of(source)
  148. if existing is not None:
  149. return existing
  150. from hermes_cli.profiles import get_profile_dir
  151. from hermes_constants import get_process_hermes_home
  152. primary_profile = _name(getattr(runner, "_primary_profile_name", None)) or "default"
  153. runtime_name = _name(getattr(source, "profile", None)) or primary_profile
  154. authorization_home = (
  155. Path(get_process_hermes_home()) if transport_name == primary_profile
  156. else get_profile_dir(transport_name))
  157. runtime_home = (
  158. authorization_home if runtime_name == transport_name
  159. else Path(runner._resolve_profile_home_for_source(source)))
  160. source._authorization_profile_home = authorization_home
  161. identity = RoutingIdentity(
  162. transport_profile=transport_name, runtime_profile=runtime_name,
  163. authorization_home=authorization_home, runtime_home=runtime_home,
  164. multiplexed=True, transport=None)
  165. setattr(source, _IDENTITY_ATTR, identity)
  166. return identity
  167. def resolve_identity(
  168. source: SessionSource, *, runner: Any, adapter: Any = None,
  169. transport_profile: Optional[str] = None, primary_home: Optional[Path] = None,
  170. ) -> RoutingIdentity:
  171. """Resolve and pin the :class:`RoutingIdentity` of an inbound *source*.
  172. *adapter* is the receiving adapter when the caller holds it; otherwise the source's own
  173. transport provenance is consulted. *transport_profile* names the receiving bot's owning
  174. profile when the caller knows it by construction (the runner's per-profile handlers);
  175. ``None`` = derive it from the adapter registry, primary when unknown. *primary_home* is the
  176. primary bot's home for authorization (default: the process home, never a per-turn override).
  177. Stamps ``source.profile`` the way the ingress handlers always did (routed name, else a
  178. secondary's own name; ``None`` stays ``None`` for the primary so the wire is unchanged) and
  179. ``_authorization_profile_home`` for the existing authorization readers.
  180. Raises :class:`IdentityUnresolved` under multiplexing when the route is rejected.
  181. """
  182. from gateway.profile_routing import ProfileRouteRejected
  183. from hermes_constants import get_hermes_home, get_process_hermes_home
  184. multiplexed = bool(getattr(getattr(runner, "config", None), "multiplex_profiles", False))
  185. primary_profile = _name(getattr(runner, "_primary_profile_name", None))
  186. if primary_profile is None:
  187. active = getattr(runner, "_active_profile_name", None)
  188. primary_profile = (_name(active()) if callable(active) else None) or "default"
  189. platform = getattr(source, "platform", None)
  190. owner_profile: Optional[str] = None
  191. if adapter is None:
  192. owner = runner._transport_owner(source)
  193. if owner is not None:
  194. adapter, owner_profile = owner
  195. else:
  196. if getattr(source, "_transport_adapter_ref", None) is None:
  197. source._transport_adapter_ref = weakref.ref(adapter)
  198. _registered, owner_profile = runner._owning_profile(adapter, platform)
  199. transport_name = _name(transport_profile) or _name(owner_profile) or primary_profile
  200. transport_inferred = adapter is None and _name(transport_profile) is None and _name(owner_profile) is None
  201. transport_ref = weakref.ref(adapter) if adapter is not None else None
  202. if not multiplexed:
  203. home = Path(get_hermes_home())
  204. identity = RoutingIdentity(
  205. transport_profile=primary_profile, runtime_profile=primary_profile,
  206. authorization_home=home, runtime_home=home, multiplexed=False, transport=transport_ref)
  207. setattr(source, _IDENTITY_ATTR, identity)
  208. return identity
  209. if transport_name == primary_profile:
  210. authorization_home = Path(primary_home) if primary_home is not None else Path(get_process_hermes_home())
  211. else:
  212. from hermes_cli.profiles import get_profile_dir
  213. authorization_home = get_profile_dir(transport_name)
  214. source._authorization_profile_home = authorization_home
  215. where = f"{getattr(platform, 'value', platform)}/{getattr(source, 'chat_id', '')}"
  216. if getattr(source, "profile_route_rejected", False) is True:
  217. raise IdentityUnresolved(f"{where}: profile route rejected")
  218. if _name(getattr(source, "profile", None)) is None:
  219. adapter_profile = None if transport_name == primary_profile else transport_name
  220. try:
  221. # The primary keeps the historical one-argument call (its adapter profile is None).
  222. routed = (
  223. runner._profile_name_for_source(source) if adapter_profile is None
  224. else runner._profile_name_for_source(source, adapter_profile=adapter_profile))
  225. except ProfileRouteRejected as exc:
  226. source.profile_route_rejected = True
  227. source._rejected_route_profile = exc.profile # a parked target is retried (producer_scope)
  228. raise IdentityUnresolved(f"{where}: {exc}") from exc
  229. source.profile = routed or adapter_profile
  230. runtime_name = _name(source.profile) or primary_profile
  231. # A routed runtime goes through the runner's resolver (missing-profile fallback + warning);
  232. # a bot serving its own profile runs where it authorizes.
  233. runtime_home = (
  234. authorization_home if runtime_name == transport_name
  235. else Path(runner._resolve_profile_home_for_source(source)))
  236. identity = RoutingIdentity(
  237. transport_profile=transport_name, runtime_profile=runtime_name,
  238. authorization_home=authorization_home, runtime_home=runtime_home,
  239. multiplexed=True, transport=transport_ref, transport_inferred=transport_inferred)
  240. setattr(source, _IDENTITY_ATTR, identity)
  241. return identity
  242. AUTH_SUBJECT_PREFIX = 'auth:v1:'
  243. def parse_authenticated_subject(subject):
  244. """``(provider, issuer, user)`` of an :func:`authenticated_subject` login form
  245. ``auth:v1:[provider, issuer, user]``, else None. The one parser for that format: callers
  246. apply their own policy (which logins may be forwarded, which map to a label) to the result."""
  247. if not isinstance(subject, str) or not subject.startswith(AUTH_SUBJECT_PREFIX):
  248. return None
  249. try:
  250. parts = json.loads(subject[len(AUTH_SUBJECT_PREFIX):])
  251. except ValueError:
  252. return None
  253. if not (isinstance(parts, list) and len(parts) == 3 and all(isinstance(p, str) for p in parts)):
  254. return None
  255. return tuple(parts)
  256. def authenticated_subject(identity):
  257. """Keep private native receipts stable; namespace every dashboard identity.
  258. Only the private bootstrap stamps profile/instance/capabilities. A dashboard
  259. provider named 'local' (or a subject resembling a UID) is not native provenance.
  260. Historical remote bare-subject receipts cannot be assigned to a first caller.
  261. """
  262. subject = str(identity.get('user_id') or 'unbound')
  263. if (identity.get('provider') == 'local' and identity.get('profile_id')
  264. and identity.get('instance_id') and 'capabilities' in identity):
  265. return subject
  266. return AUTH_SUBJECT_PREFIX + json.dumps(
  267. [identity.get('provider') or '', identity.get('issuer') or '', subject],
  268. separators=(',', ':'), ensure_ascii=True)
  269. def is_authenticated_identity(identity: object) -> bool:
  270. """True for a server-minted, non-internal ``{user_id, provider}`` WS-upgrade identity."""
  271. from hermes_cli.dashboard_auth.ws_tickets import INTERNAL_PROVIDER, INTERNAL_USER_ID
  272. if not isinstance(identity, dict):
  273. return False
  274. user_id, provider = identity.get("user_id"), identity.get("provider")
  275. if not isinstance(user_id, str) or not user_id.strip():
  276. return False
  277. if not isinstance(provider, str) or not provider.strip():
  278. return False
  279. return not (user_id == INTERNAL_USER_ID and provider == INTERNAL_PROVIDER)
  280. def authenticated_principal_digest(identity: dict) -> str:
  281. """Server-derived principal id: stable per login, unspoofable without the minted identity."""
  282. raw = authenticated_subject(identity)
  283. return f"principal:dashboard:{hashlib.sha256(raw.encode('utf-8')).hexdigest()[:32]}"