hosted_room_peer.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. """Typed contracts for autonomous cross-gateway hosted-room members.
  2. The Desktop may bootstrap an invitation but is never the issuer or runtime courier: the target gateway
  3. verifies a scoped grant and the full task coordinates before admitting any model or tool work.
  4. """
  5. from __future__ import annotations
  6. import base64
  7. import hashlib
  8. import hmac
  9. import ipaddress
  10. import json
  11. import math
  12. import os
  13. import re
  14. import stat
  15. import urllib.parse
  16. from dataclasses import asdict, dataclass
  17. from functools import lru_cache, partial
  18. from pathlib import Path
  19. from typing import Any, Callable, Iterable, Literal, Mapping
  20. from gateway.hosted_room_execution_policy import RoomExecutionPolicy, execution_policy_mapping
  21. from gateway.hosted_rooms_common import bounded_int, clock, compact_json, exact_fields, identifier, text
  22. # v2 adds authority/member lineage to scoped grants and is deliberately not wire-compatible with the
  23. # unpublished v1 draft; mixed gateways fall back to Desktop-driven rooms rather than accept a weaker token.
  24. PROTOCOL_VERSION = 2
  25. MAX_TOKEN_BYTES = 16 * 1024
  26. MAX_PROMPT_BYTES = 256 * 1024
  27. _IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$")
  28. _DIGEST_RE = re.compile(r"^[0-9a-f]{64}$")
  29. _LINK_MODES = frozenset({"direct", "overlay", "relay", "pull", "desktop"})
  30. LinkMode = Literal["direct", "overlay", "relay", "pull", "desktop"]
  31. TransportSecurity = Literal["tls", "loopback"]
  32. class HostedRoomPeerError(ValueError): """Base error for malformed or unauthorized peer-room input."""
  33. class HostedRoomGrantError(HostedRoomPeerError): """Raised when a room-scoped grant is invalid or expired."""
  34. _ROOM_GRANT_SECRET_FILE = ".room-link-grant-secret"
  35. @lru_cache(maxsize=32)
  36. def _gateway_room_grant_secret_for_home(home_value: str) -> bytes:
  37. """Load one restart-scoped grant secret for an exact installation root."""
  38. from utils import fsync_directory
  39. (home := Path(home_value)).mkdir(parents=True, exist_ok=True)
  40. path = home / _ROOM_GRANT_SECRET_FILE
  41. def _read() -> bytes:
  42. if len(data := path.read_bytes()) != 32:
  43. raise HostedRoomGrantError("gateway RoomLink secret is invalid")
  44. if stat.S_IMODE(path.stat().st_mode) & 0o077:
  45. path.chmod(0o600)
  46. return data
  47. try:
  48. material = _read()
  49. except FileNotFoundError:
  50. # Atomic create: O_EXCL temp file, hard-link into place (loser re-reads the winner's secret),
  51. # fsync the directory, always drop the temp name.
  52. material = os.urandom(32)
  53. temporary = home / f".{_ROOM_GRANT_SECRET_FILE}.{os.getpid()}.{os.urandom(8).hex()}"
  54. fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
  55. try:
  56. with os.fdopen(fd, "wb", closefd=True) as stream:
  57. stream.write(material)
  58. stream.flush()
  59. os.fsync(stream.fileno())
  60. try:
  61. os.link(temporary, path)
  62. except FileExistsError:
  63. material = _read()
  64. else:
  65. fsync_directory(home)
  66. finally:
  67. temporary.unlink(missing_ok=True)
  68. return hmac.new(material, b"hermes-hosted-room-installation-grant-v1", hashlib.sha256).digest()
  69. def gateway_room_grant_secret(root: Path | str | None = None) -> bytes:
  70. """Load or atomically mint the gateway-only RoomLink signing secret.
  71. API keys are client-known, possibly profile-scoped bearer credentials and must never become
  72. grant-signing authority; this secret lives in the installation root, is never exposed by config
  73. or capability RPCs, and is shared only by this installation's gateway processes.
  74. """
  75. if root is None:
  76. from hermes_constants import get_hermes_home
  77. # Profile routing uses a context-local HERMES_HOME override; the process environment
  78. # retains the installation root and is the authority here.
  79. root = os.environ.get("HERMES_HOME") or get_hermes_home()
  80. return _gateway_room_grant_secret_for_home(str(Path(root).expanduser().resolve()))
  81. def derive_room_grant_secret(api_key: str) -> bytes:
  82. """Domain-separate room grants from the configured API key.
  83. The 8-char floor is for contract tests; production key strength is enforced by the API-server startup guard.
  84. """
  85. if not isinstance(api_key, str) or len(api_key) < 8:
  86. raise HostedRoomGrantError("room grants require a strong gateway API key")
  87. return hmac.new(api_key.encode("utf-8"), b"hermes-hosted-room-grant-v1", hashlib.sha256).digest()
  88. def _identifier(value: Any, *, field: str) -> str:
  89. return identifier(
  90. value, label=field, error=HostedRoomPeerError, max_chars=256, pattern=_IDENTIFIER_RE,
  91. invalid=f"{field} is invalid")
  92. def _positive_int(value: Any, *, field: str) -> int:
  93. return bounded_int(value, error=HostedRoomPeerError, message=f"{field} must be a positive integer", low=1)
  94. def _digest(value: Any, *, field: str) -> str:
  95. if not isinstance(value, str) or not _DIGEST_RE.fullmatch(value):
  96. raise HostedRoomPeerError(f"{field} must be a sha256 digest")
  97. return value
  98. _exact_fields = partial(
  99. exact_fields, error=HostedRoomPeerError, missing_fmt="{label} missing fields: {fields}",
  100. unknown_fmt="{label} unknown fields: {fields}")
  101. def _canonical_json(value: Mapping[str, Any]) -> bytes:
  102. return compact_json(value).encode("ascii")
  103. def _b64encode(value: bytes) -> str:
  104. return base64.urlsafe_b64encode(value).rstrip(b"=").decode("ascii")
  105. def _b64decode(value: str) -> bytes:
  106. try:
  107. return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
  108. except Exception as exc:
  109. raise HostedRoomGrantError("room grant encoding is invalid") from exc
  110. def _split_token(token: str) -> tuple[bytes, bytes]:
  111. """Return the decoded ``(payload, signature)`` halves of a grant token."""
  112. encoded_token, separator, signature_token = token.partition(".")
  113. if not separator:
  114. raise HostedRoomGrantError("room grant is invalid")
  115. return _b64decode(encoded_token), _b64decode(signature_token)
  116. def _non_empty_list(value: Any, *, field: str) -> list[Any]:
  117. if not isinstance(value, list) or not value:
  118. raise HostedRoomPeerError(f"{field} must be a non-empty list")
  119. return value
  120. def _parse_link_modes(links_raw: Any) -> tuple[LinkMode, ...]:
  121. if any(item not in _LINK_MODES for item in _non_empty_list(links_raw, field="link_modes")):
  122. raise HostedRoomPeerError("link_modes contains an unsupported mode")
  123. return tuple(dict.fromkeys(links_raw))
  124. def _protocol_versions(versions_raw: Any) -> list[int]:
  125. return sorted({_positive_int(item, field="protocol_version") for item in versions_raw})
  126. def _catalog_digest(value: Mapping[str, Any]) -> str:
  127. """Digest of the catalog mapping without its ``catalog_digest`` field."""
  128. return hashlib.sha256(_canonical_json({k: v for k, v in value.items() if k != "catalog_digest"})).hexdigest()
  129. def _parse_endpoint(endpoint: Any) -> tuple[str | None, str | None, TransportSecurity | None]:
  130. """Return ``(url, reason, transport_security)`` for an advertised endpoint capability."""
  131. if not isinstance(endpoint, Mapping) or not isinstance(endpoint.get("available"), bool):
  132. raise HostedRoomPeerError("endpoint capability is invalid")
  133. if not endpoint["available"]:
  134. _exact_fields(endpoint, required={"available", "reason"}, label="endpoint capability")
  135. return None, _identifier(endpoint["reason"], field="endpoint.reason"), None
  136. _exact_fields(endpoint, required={"available", "url", "transport_security"}, label="endpoint capability")
  137. url, transport_security = validate_room_link_url(endpoint["url"])
  138. if endpoint["transport_security"] != transport_security:
  139. raise HostedRoomPeerError("endpoint transport_security does not match its URL")
  140. return url, None, transport_security
  141. _CATALOG_FIELDS = {
  142. "installation_id", "protocol_versions", "link_modes", "persistent_process", "text", "attachments",
  143. "execution_policy", "catalog_digest"}
  144. @dataclass(frozen=True)
  145. class GatewayRoomCatalog:
  146. """Authenticated gateway capabilities inherited by its Bots."""
  147. installation_id: str
  148. protocol_versions: tuple[int, ...]
  149. link_modes: tuple[LinkMode, ...]
  150. persistent_process: bool
  151. text: bool
  152. attachments: bool
  153. execution_policy: RoomExecutionPolicy
  154. catalog_digest: str
  155. endpoint_url: str | None = None
  156. endpoint_reason: str | None = None
  157. transport_security: TransportSecurity | None = None
  158. @classmethod
  159. def from_mapping(cls, value: Mapping[str, Any]) -> GatewayRoomCatalog:
  160. _exact_fields(value, required=_CATALOG_FIELDS, optional={"endpoint"}, label="capability catalog")
  161. installation_id = _identifier(value["installation_id"], field="installation_id")
  162. versions = tuple(_protocol_versions(_non_empty_list(value["protocol_versions"], field="protocol_versions")))
  163. links = _parse_link_modes(value["link_modes"])
  164. for field in ("persistent_process", "text", "attachments"):
  165. if not isinstance(value[field], bool):
  166. raise HostedRoomPeerError(f"{field} must be a boolean")
  167. policy = RoomExecutionPolicy.from_mapping(value["execution_policy"])
  168. endpoint = _parse_endpoint(value["endpoint"]) if "endpoint" in value else (None, None, None)
  169. catalog = cls(
  170. installation_id, versions, links, value["persistent_process"], value["text"], value["attachments"], policy,
  171. _digest(value["catalog_digest"], field="catalog_digest"), *endpoint)
  172. if not hmac.compare_digest(_catalog_digest(catalog.as_mapping()), catalog.catalog_digest):
  173. raise HostedRoomPeerError("catalog_digest does not match the catalog")
  174. return catalog
  175. def as_mapping(self) -> dict[str, Any]:
  176. """Canonical catalog mapping; ``endpoint`` appears only when advertised."""
  177. value = {
  178. "installation_id": self.installation_id, "protocol_versions": list(self.protocol_versions),
  179. "link_modes": list(self.link_modes), "persistent_process": self.persistent_process, "text": self.text,
  180. "attachments": self.attachments, "execution_policy": self.execution_policy.as_mapping(),
  181. "catalog_digest": self.catalog_digest}
  182. if self.endpoint_url is not None or self.endpoint_reason is not None:
  183. value["endpoint"] = self.endpoint_mapping()
  184. return value
  185. def endpoint_mapping(self) -> dict[str, Any]:
  186. """Return the normalized self-advertised endpoint capability."""
  187. if self.endpoint_url is None:
  188. return {"available": False, "reason": self.endpoint_reason or "not_configured"}
  189. return {"available": True, "url": self.endpoint_url, "transport_security": self.transport_security}
  190. def catalog_mapping(
  191. *, installation_id: str, protocol_versions: Iterable[int] = (PROTOCOL_VERSION,),
  192. link_modes: Iterable[LinkMode] = ("direct", "pull"), persistent_process: bool, text: bool = True,
  193. attachments: bool = False, endpoint: Mapping[str, Any] | None = None, target_profile: str,
  194. execution_policy: Mapping[str, Any] | None = None) -> dict[str, Any]:
  195. """Build a canonical catalog mapping with its digest for the SERVED ``target_profile``.
  196. The profile is the session's, never the process's: a multiplexed gateway advertises one
  197. catalog per served profile, so there is no env (``HERMES_PROFILE``) fallback (#116900)."""
  198. # A Desktop-managed gateway exits with the app: the caller's flag is only an upper bound.
  199. persistent_process = bool(persistent_process and os.getenv("HERMES_DESKTOP") != "1")
  200. profile = _identifier(target_profile, field="target_profile")
  201. checked_policy = RoomExecutionPolicy.from_mapping(
  202. execution_policy or execution_policy_mapping(target_profile=profile))
  203. if checked_policy.target_profile != profile:
  204. raise HostedRoomPeerError("execution_policy target_profile does not match the catalog target_profile")
  205. # A RoomLink run is initiated by another installation. Process-wide YOLO mode bypasses the scoped
  206. # approval ContextVar, so rewriting the advertised policy cannot make it safe: refuse.
  207. if checked_policy.approval_mode == "off":
  208. raise HostedRoomPeerError("remote room execution requires manual or smart approvals")
  209. value = {
  210. "installation_id": _identifier(installation_id, field="installation_id"),
  211. "protocol_versions": _protocol_versions(protocol_versions),
  212. # Direct HTTPS/loopback is the only implemented RoomLink transport; never advertise pull/relay.
  213. "link_modes": [mode for mode in dict.fromkeys(link_modes) if mode == "direct"],
  214. "persistent_process": persistent_process, "text": bool(text), "attachments": bool(attachments),
  215. "execution_policy": checked_policy.as_mapping(),
  216. "endpoint": dict(local_room_link_endpoint() if endpoint is None else endpoint)}
  217. value["catalog_digest"] = _catalog_digest(value)
  218. GatewayRoomCatalog.from_mapping(value)
  219. return value
  220. # The one truthful catalog advertised by this local process (keyword arguments as for catalog_mapping).
  221. local_catalog_mapping = partial(catalog_mapping, persistent_process=True)
  222. def local_room_link_endpoint(value: Any | None = None) -> dict[str, Any]:
  223. """Return the validated endpoint this gateway explicitly advertises."""
  224. if not str((configured := _configured_room_link_url() if value is None else value) or "").strip():
  225. return {"available": False, "reason": "not_configured"}
  226. try:
  227. url, transport_security = validate_room_link_url(configured)
  228. except HostedRoomPeerError:
  229. return {"available": False, "reason": "invalid_configuration"}
  230. return {"available": True, "url": url, "transport_security": transport_security}
  231. @lru_cache(maxsize=16)
  232. def _room_link_url_from_config(home: str) -> str | None:
  233. """Read the restart-scoped user setting without polling config on probes."""
  234. from gateway.config import load_gateway_config
  235. from hermes_constants import get_hermes_home, reset_hermes_home_override, set_hermes_home_override
  236. if str(get_hermes_home()) == home:
  237. value = load_gateway_config().room_link_url
  238. else:
  239. token = set_hermes_home_override(home)
  240. try:
  241. value = load_gateway_config().room_link_url
  242. finally:
  243. reset_hermes_home_override(token)
  244. return value.strip() if isinstance(value, str) and value.strip() else None
  245. def _configured_room_link_url() -> str | None:
  246. """Resolve the explicit endpoint: env override > profile config > root config."""
  247. if (override := os.getenv("HERMES_ROOM_LINK_URL")) is not None:
  248. return override
  249. from hermes_constants import get_default_hermes_root, get_hermes_home
  250. home = get_hermes_home()
  251. if configured := _room_link_url_from_config(str(home)):
  252. return configured
  253. # RoomLink is a gateway reachability property, not a Bot personality setting: named profiles may
  254. # override it but otherwise inherit the process gateway's root endpoint.
  255. root = get_default_hermes_root()
  256. return _room_link_url_from_config(str(root)) if root != home else None
  257. def validate_room_link_url(value: Any) -> tuple[str, TransportSecurity]:
  258. """Validate a RoomLink endpoint and classify its transport: plaintext HTTP only toward loopback."""
  259. raw = str(value or "").strip().rstrip("/")
  260. try:
  261. parsed = urllib.parse.urlsplit(raw)
  262. hostname = (parsed.hostname or "").rstrip(".").lower()
  263. # Force urllib to validate a malformed/out-of-range port.
  264. parsed.port
  265. except ValueError as exc:
  266. raise HostedRoomPeerError("target_url is invalid") from exc
  267. if not hostname or parsed.username is not None or parsed.password is not None:
  268. raise HostedRoomPeerError("target_url is invalid")
  269. if parsed.query or parsed.fragment:
  270. raise HostedRoomPeerError("target_url must not include query or fragment")
  271. if parsed.scheme.lower() == "https":
  272. return raw, "tls"
  273. if parsed.scheme.lower() != "http":
  274. raise HostedRoomPeerError("target_url must use https")
  275. try:
  276. if hostname == "localhost" or hostname.endswith(".localhost") or ipaddress.ip_address(hostname).is_loopback:
  277. return raw, "loopback"
  278. except ValueError:
  279. pass
  280. raise HostedRoomPeerError("target_url must use https outside the local machine")
  281. # Validator per dispatch field, in validation order (prompt/prompt_digest are cross-checked in from_mapping).
  282. _DISPATCH_FIELDS: dict[str, Callable[..., Any]] = dict(
  283. protocol_version=_positive_int, room_id=_identifier, home_install_id=_identifier, authority_gateway_id=_identifier,
  284. authority_epoch=_positive_int, member_id=_identifier, target_install_id=_identifier, target_profile=_identifier,
  285. task_id=_identifier, execution_generation=_positive_int, source_event_seq=_positive_int,
  286. cancellation_scope_id=_identifier, capability_digest=_digest, execution_policy_digest=_digest, trace_id=_identifier)
  287. @dataclass(frozen=True)
  288. class HostedMemberDispatch:
  289. """Recipient-validated identity for one remote room member attempt."""
  290. protocol_version: int
  291. room_id: str
  292. home_install_id: str
  293. authority_gateway_id: str
  294. authority_epoch: int
  295. member_id: str
  296. target_install_id: str
  297. target_profile: str
  298. task_id: str
  299. execution_generation: int
  300. source_event_seq: int
  301. cancellation_scope_id: str
  302. prompt: str
  303. prompt_digest: str
  304. capability_digest: str
  305. execution_policy_digest: str
  306. trace_id: str
  307. def as_mapping(self) -> dict[str, Any]:
  308. """Return the canonical wire mapping used for fingerprinting."""
  309. return asdict(self)
  310. @classmethod
  311. def from_mapping(cls, value: Mapping[str, Any]) -> HostedMemberDispatch:
  312. _exact_fields(value, required=set(_DISPATCH_FIELDS) | {"prompt", "prompt_digest"}, label="dispatch")
  313. if not isinstance(prompt := value["prompt"], str) or not prompt.strip():
  314. raise HostedRoomPeerError("prompt must be a non-empty string")
  315. text(prompt, error=HostedRoomPeerError, label="prompt", max_bytes=MAX_PROMPT_BYTES, strip=False)
  316. prompt_digest = _digest(value["prompt_digest"], field="prompt_digest")
  317. if not hmac.compare_digest(hashlib.sha256(prompt.encode("utf-8")).hexdigest(), prompt_digest):
  318. raise HostedRoomPeerError("prompt_digest does not match prompt")
  319. return cls(
  320. prompt=prompt, prompt_digest=prompt_digest,
  321. **{name: check(value[name], field=name) for name, check in _DISPATCH_FIELDS.items()})
  322. # Grant scope fields in issue-time validation order; each uses the matching dispatch checker (grant_id: identifier).
  323. _GRANT_SCOPE = (
  324. "grant_id", "room_id", "home_install_id", "authority_gateway_id", "authority_epoch", "member_id",
  325. "target_install_id", "target_profile")
  326. _GRANT_FIELDS = frozenset({
  327. "version", *_GRANT_SCOPE, "execution_policy_digest", "permissions", "issued_at", "expires_at"})
  328. _GRANT_REFRESH_FIELDS = _GRANT_FIELDS | {"status_expires_at"}
  329. _GRANT_PERMISSIONS = {"approve", "dispatch", "status", "stop"}
  330. MAX_DISPATCH_GRANT_TTL_SECONDS = 24 * 60 * 60
  331. MAX_STATUS_GRANT_TTL_SECONDS = 30 * 24 * 60 * 60
  332. def issue_room_grant(
  333. secret: bytes, *, grant_id: str, room_id: str, home_install_id: str, authority_gateway_id: str,
  334. authority_epoch: int, member_id: str, target_install_id: str, target_profile: str,
  335. execution_policy_digest: str | None = None, permissions: Iterable[str] = ("approve", "dispatch", "status", "stop"),
  336. issued_at: float | None = None, ttl_seconds: float = 3600, status_ttl_seconds: float | None = None,
  337. status_expires_at: float | None = None) -> str:
  338. """Issue a target-verifiable bearer grant scoped to one room member."""
  339. if len(secret) < 32:
  340. raise HostedRoomGrantError("room grant secret must be at least 32 bytes")
  341. now = clock(issued_at)
  342. bounded_status_expiry = (
  343. now + float(ttl_seconds if status_ttl_seconds is None else status_ttl_seconds)
  344. if status_expires_at is None
  345. else float(status_expires_at))
  346. if (
  347. not math.isfinite(now) or ttl_seconds <= 0 or ttl_seconds > MAX_DISPATCH_GRANT_TTL_SECONDS
  348. or not math.isfinite(bounded_status_expiry) or bounded_status_expiry < now + float(ttl_seconds)
  349. or bounded_status_expiry > now + MAX_STATUS_GRANT_TTL_SECONDS):
  350. raise HostedRoomGrantError("room grant lifetime is invalid")
  351. allowed = tuple(sorted(set(permissions)))
  352. if not allowed or not set(allowed) <= _GRANT_PERMISSIONS:
  353. raise HostedRoomGrantError("room grant permissions are invalid")
  354. scope = locals()
  355. payload = {
  356. "version": PROTOCOL_VERSION,
  357. **{name: _DISPATCH_FIELDS.get(name, _identifier)(scope[name], field=name) for name in _GRANT_SCOPE},
  358. "execution_policy_digest": _digest(
  359. execution_policy_digest
  360. or execution_policy_mapping(target_profile=target_profile)["policy_digest"], field="execution_policy_digest"
  361. ), "permissions": list(allowed), "issued_at": now, "expires_at": now + float(ttl_seconds),
  362. "status_expires_at": bounded_status_expiry}
  363. encoded = _canonical_json(payload)
  364. token = f"{_b64encode(encoded)}.{_b64encode(hmac.new(secret, encoded, hashlib.sha256).digest())}"
  365. if len(token.encode("ascii")) > MAX_TOKEN_BYTES:
  366. raise HostedRoomGrantError("room grant is too large")
  367. return token
  368. def verify_room_grant(
  369. secret: bytes, token: str, dispatch: HostedMemberDispatch, *, permission: str = "dispatch", now: float | None = None
  370. ) -> dict[str, Any]:
  371. """Verify one room grant against exact recipient dispatch coordinates."""
  372. payload = decode_room_grant(secret, token, permission=permission, now=now)
  373. if payload["version"] != dispatch.protocol_version:
  374. raise HostedRoomGrantError("room grant protocol does not match dispatch")
  375. if any(payload.get(f) != getattr(dispatch, f) for f in (*_GRANT_SCOPE[1:], "execution_policy_digest")):
  376. raise HostedRoomGrantError("room grant scope does not match dispatch")
  377. return payload
  378. def decode_room_grant(secret: bytes, token: str, *, permission: str, now: float | None = None) -> dict[str, Any]:
  379. """Verify grant signature, lifetime and operation without a dispatch."""
  380. if not isinstance(token, str) or len(token.encode("utf-8")) > MAX_TOKEN_BYTES:
  381. raise HostedRoomGrantError("room grant is invalid")
  382. encoded, supplied_signature = _split_token(token)
  383. if not hmac.compare_digest(hmac.new(secret, encoded, hashlib.sha256).digest(), supplied_signature):
  384. raise HostedRoomGrantError("room grant signature is invalid")
  385. try:
  386. payload = json.loads(encoded.decode("ascii"))
  387. except Exception as exc:
  388. raise HostedRoomGrantError("room grant payload is invalid") from exc
  389. if not isinstance(payload, dict) or frozenset(payload) not in {_GRANT_FIELDS, _GRANT_REFRESH_FIELDS}:
  390. raise HostedRoomGrantError("room grant fields are invalid")
  391. if not math.isfinite(checked_now := clock(now)):
  392. raise HostedRoomGrantError("room grant clock is invalid")
  393. try:
  394. issued_at = float(payload["issued_at"])
  395. expires_at = float(payload["expires_at"])
  396. status_expires_at = float(payload.get("status_expires_at", expires_at))
  397. except (TypeError, ValueError) as exc:
  398. raise HostedRoomGrantError("room grant lifetime is invalid") from exc
  399. lifetimes = (issued_at, expires_at, status_expires_at)
  400. if not (all(map(math.isfinite, lifetimes)) and issued_at < expires_at <= status_expires_at):
  401. raise HostedRoomGrantError("room grant lifetime is invalid")
  402. operation_expires_at = status_expires_at if permission in {"approve", "status", "stop"} else expires_at
  403. if checked_now < issued_at - 30 or checked_now >= operation_expires_at:
  404. raise HostedRoomGrantError("room grant is expired or not active")
  405. if not isinstance(permissions := payload.get("permissions"), list) or permission not in permissions:
  406. raise HostedRoomGrantError("room grant does not allow this operation")
  407. return payload
  408. def room_grant_needs_dispatch_refresh(token: str, *, now: float | None = None, leeway_seconds: float = 5 * 60) -> bool:
  409. """Read only grant timing to schedule refresh; trust is established by the target, not here."""
  410. try:
  411. expires_at = float(json.loads(_split_token(token)[0].decode("ascii"))["expires_at"])
  412. return clock(now) + max(0.0, float(leeway_seconds)) >= expires_at
  413. except Exception:
  414. return True