api_server_room_grants.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. """RoomLink room-member grants and capability HTTP handlers."""
  2. import time
  3. import uuid
  4. from typing import Any, Optional
  5. try:
  6. from aiohttp import web
  7. except ImportError:
  8. web = None # type: ignore[assignment]
  9. class RoomGrantReauthorizationRequired(ValueError):
  10. """A validly signed room grant was revoked or superseded."""
  11. def _json_error(_openai_error, message: str, *, status: int, **error_kwargs) -> web.Response:
  12. """JSON error response built with the injected ``_openai_error`` envelope builder."""
  13. return web.json_response(_openai_error(message, **error_kwargs), status=status)
  14. def _require_unchanged_execution_policy(claims: dict[str, Any], execution_policy: dict[str, Any]) -> None:
  15. """Keep renewal from silently granting a changed execution policy."""
  16. if str(execution_policy.get("policy_digest") or "") != str(claims.get("execution_policy_digest") or ""):
  17. raise RoomGrantReauthorizationRequired("room execution policy changed")
  18. def _room_grant_error_response(exc: Optional[Exception] = None, *, _openai_error) -> web.Response:
  19. """401 invalid grant, or 403 reauthorization-required for a revoked/superseded grant."""
  20. if isinstance(exc, RoomGrantReauthorizationRequired):
  21. message, code, status = "Room authorization needs to be renewed.", "room_reauthorization_required", 403
  22. else:
  23. message, code, status = "Room authorization is invalid or expired.", "invalid_room_grant", 401
  24. return _json_error(_openai_error, message, err_type="gateway_auth_error", code=code, status=status)
  25. def _hard_expiry(claims: dict[str, Any]) -> float:
  26. return float(claims.get("status_expires_at", claims["expires_at"]))
  27. _ROOM_IDENTITY_FIELDS = ("room_id", "home_install_id", "authority_gateway_id", "authority_epoch", "member_id")
  28. def _room_identity(source: dict[str, Any], *, coerce: bool = False) -> dict[str, Any]:
  29. """Room-authority kwargs for ``issue_room_grant``; *coerce* applies ``str``/``int`` to raw body values."""
  30. text = str if coerce else (lambda v: v)
  31. return {k: int(source[k]) if k == "authority_epoch" else text(source[k]) for k in _ROOM_IDENTITY_FIELDS}
  32. def _local_target(claims: dict[str, Any] | None, _api_request_profile) -> tuple[str, str]:
  33. """Return ``(profile, installation_id)`` for this gateway; *claims* must target it."""
  34. from gateway import hosted_rooms
  35. profile = _api_request_profile.get() or "default"
  36. installation_id = hosted_rooms.local_authority_gateway_id()
  37. if claims is not None and (claims["target_profile"], claims["target_install_id"]) != (profile, installation_id):
  38. raise ValueError("room grant target does not match this profile")
  39. return profile, installation_id
  40. def _local_room_catalog(self, profile: str, installation_id: str) -> tuple[dict, dict]:
  41. """Return ``(execution_policy, catalog)`` for this gateway's *profile*."""
  42. from gateway.hosted_room_peer import PROTOCOL_VERSION, catalog_mapping
  43. from gateway.hosted_room_execution_policy import execution_policy_mapping
  44. with self._profile_scope(profile):
  45. execution_policy = execution_policy_mapping(target_profile=profile)
  46. catalog = catalog_mapping(
  47. installation_id=installation_id, protocol_versions=(PROTOCOL_VERSION,), link_modes=("direct",),
  48. persistent_process=True, text=True, attachments=False, target_profile=profile,
  49. execution_policy=execution_policy)
  50. return execution_policy, catalog
  51. def _http_routes(self) -> list[tuple[str, str, Any]]:
  52. return [
  53. ("POST", "/v1/room-members/invitations", self._handle_room_member_invitation),
  54. ("GET", "/v1/room-members/capabilities", self._handle_room_member_capabilities),
  55. ("POST", "/v1/room-members/grants/refresh", self._handle_room_member_grant_refresh),
  56. ("POST", "/v1/room-members/grants/revoke", self._handle_room_member_grant_revoke)]
  57. def _room_grant_token(request: web.Request) -> str:
  58. scheme, separator, token = str(request.headers.get("Authorization") or "").partition(" ")
  59. return token.strip() if separator and scheme.lower() == "hermesroom" else ""
  60. def _room_grant_secret(self) -> bytes:
  61. from gateway.hosted_room_peer import gateway_room_grant_secret
  62. return gateway_room_grant_secret()
  63. def _decode_request_grant(self, request: web.Request, *, permission: str) -> dict[str, Any]:
  64. """Signature/scope/horizon check only (no revocation lookup)."""
  65. from gateway.hosted_room_peer import decode_room_grant
  66. token = self._room_grant_token(request)
  67. if not token:
  68. raise ValueError("room grant is missing")
  69. return decode_room_grant(self._room_grant_secret(), token, permission=permission)
  70. def _room_grant_claims(self, request: web.Request, *, permission: str) -> dict[str, Any]:
  71. claims = _decode_request_grant(self, request, permission=permission)
  72. from gateway import hosted_rooms
  73. db_path = hosted_rooms.default_db_path()
  74. if hosted_rooms.room_grant_is_revoked(db_path, claims=claims):
  75. raise RoomGrantReauthorizationRequired("room grant is revoked")
  76. if not hosted_rooms.peer_room_grant_is_current(db_path, claims=claims):
  77. raise RoomGrantReauthorizationRequired("room grant is no longer current")
  78. return claims
  79. async def _handle_room_member_invitation(
  80. self, request: web.Request, *, _openai_error, _api_request_profile) -> web.Response:
  81. """Mint a short-lived room/profile grant for a trusted home gateway."""
  82. auth_err = self._check_auth(request)
  83. if auth_err:
  84. return auth_err
  85. body, error = await self._read_json_body(request)
  86. if error:
  87. return error
  88. required = set(_ROOM_IDENTITY_FIELDS)
  89. allowed = required | {"grant_id", "ttl_seconds", "status_ttl_seconds"}
  90. if set(body) - allowed or not required <= set(body):
  91. return _json_error(
  92. _openai_error, "Invitation is missing required room authority fields.",
  93. code="invalid_room_invitation", status=400)
  94. try:
  95. from gateway import hosted_rooms
  96. from gateway.hosted_room_peer import decode_room_grant, issue_room_grant
  97. profile, target_install_id = _local_target(None, _api_request_profile)
  98. ttl = float(body.get("ttl_seconds", 3600))
  99. if not 60 <= ttl <= 24 * 60 * 60:
  100. raise ValueError("ttl_seconds must be between 60 and 86400")
  101. status_ttl = float(body.get("status_ttl_seconds", ttl))
  102. if not ttl <= status_ttl <= 30 * 24 * 60 * 60:
  103. raise ValueError("status_ttl_seconds must be at least ttl_seconds and no more than 2592000")
  104. execution_policy, catalog = _local_room_catalog(self, profile, target_install_id)
  105. token = issue_room_grant(
  106. self._room_grant_secret(),
  107. grant_id=str(body.get("grant_id") or f"grant-{uuid.uuid4().hex}"),
  108. **_room_identity(body, coerce=True),
  109. target_install_id=target_install_id, target_profile=profile,
  110. execution_policy_digest=execution_policy["policy_digest"], issued_at=time.time(),
  111. ttl_seconds=ttl, status_ttl_seconds=status_ttl)
  112. claims = decode_room_grant(self._room_grant_secret(), token, permission="status")
  113. hosted_rooms.reserve_peer_room(
  114. hosted_rooms.default_db_path(), claims=claims, expires_at=_hard_expiry(claims))
  115. except Exception as exc:
  116. return _json_error(_openai_error, str(exc), code="invalid_room_invitation", status=400)
  117. return web.json_response({
  118. "object": "hermes.room_member.invitation", "grant": token, "target_profile": profile,
  119. "catalog": catalog, "expires_at": float(claims["expires_at"]),
  120. "status_expires_at": float(claims["status_expires_at"])}, status=201)
  121. async def _handle_room_member_capabilities(
  122. self, request: web.Request, *, _openai_error, _api_request_profile) -> web.Response:
  123. """Verify a scoped grant and return this target's live room catalog."""
  124. try:
  125. claims = self._room_grant_claims(request, permission="status")
  126. profile, installation_id = _local_target(claims, _api_request_profile)
  127. _, catalog = _local_room_catalog(self, profile, installation_id)
  128. except Exception as exc:
  129. return _room_grant_error_response(exc, _openai_error=_openai_error)
  130. return web.json_response({
  131. "object": "hermes.room_member.capabilities", **{k: claims[k] for k in _ROOM_IDENTITY_FIELDS},
  132. "target_profile": profile, "catalog": catalog})
  133. async def _handle_room_member_grant_refresh(
  134. self, request: web.Request, *, _openai_error, _api_request_profile) -> web.Response:
  135. """Refresh dispatch access without a Desktop or broad gateway key."""
  136. body, error = await self._read_json_body(request)
  137. if error:
  138. return error
  139. if set(body) - {"ttl_seconds"}:
  140. return _json_error(
  141. _openai_error, "Grant refresh accepts only ttl_seconds.",
  142. code="invalid_room_grant_refresh", status=400)
  143. try:
  144. from gateway.hosted_room_peer import MAX_DISPATCH_GRANT_TTL_SECONDS, issue_room_grant
  145. from gateway.hosted_room_execution_policy import execution_policy_mapping
  146. # A status-only bearer must never mint dispatch authority: renewal needs live "dispatch".
  147. claims = self._room_grant_claims(request, permission="dispatch")
  148. profile, installation_id = _local_target(claims, _api_request_profile)
  149. now = time.time()
  150. hard_expiry = _hard_expiry(claims)
  151. remaining = hard_expiry - now
  152. requested = float(body.get("ttl_seconds", MAX_DISPATCH_GRANT_TTL_SECONDS))
  153. if remaining <= 0 or requested <= 0:
  154. raise ValueError("room grant renewal horizon expired")
  155. dispatch_ttl = min(requested, MAX_DISPATCH_GRANT_TTL_SECONDS, remaining)
  156. with self._profile_scope(profile):
  157. execution_policy = execution_policy_mapping(target_profile=profile)
  158. _require_unchanged_execution_policy(claims, execution_policy)
  159. token = issue_room_grant(
  160. self._room_grant_secret(), grant_id=f"grant-refresh-{uuid.uuid4().hex}",
  161. **_room_identity(claims), target_install_id=installation_id, target_profile=profile,
  162. execution_policy_digest=execution_policy["policy_digest"],
  163. permissions=claims["permissions"], issued_at=now, ttl_seconds=dispatch_ttl,
  164. status_expires_at=hard_expiry)
  165. except Exception as exc:
  166. return _room_grant_error_response(exc, _openai_error=_openai_error)
  167. return web.json_response({
  168. "object": "hermes.room_member.grant", "grant": token, "expires_at": now + dispatch_ttl,
  169. "status_expires_at": hard_expiry, "execution_policy": execution_policy})
  170. async def _handle_room_member_grant_revoke(
  171. self, request: web.Request, *, _openai_error, _api_request_profile) -> web.Response:
  172. """Revoke exactly the scoped grant authenticating this request."""
  173. body, error = await self._read_json_body(request)
  174. if error:
  175. return error
  176. if body:
  177. return _json_error(
  178. _openai_error, "Grant revoke accepts no fields.",
  179. code="invalid_room_grant_revoke", status=400)
  180. try:
  181. from gateway import hosted_rooms
  182. # Idempotent: a response-lost retry authenticates with the grant just denylisted, so
  183. # verify signature/scope/horizon directly (not _room_grant_claims) and upsert the id.
  184. claims = _decode_request_grant(self, request, permission="status")
  185. _local_target(claims, _api_request_profile)
  186. hosted_rooms.revoke_room_grant_scope(
  187. hosted_rooms.default_db_path(), claims=claims, expires_at=_hard_expiry(claims))
  188. except Exception:
  189. return _room_grant_error_response(_openai_error=_openai_error)
  190. return web.json_response({"object": "hermes.room_member.grant.revocation", "revoked": True})