api_server_room_dispatch.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. """RoomLink dispatch validation and hidden member-session ownership."""
  2. import asyncio
  3. import hashlib
  4. import hmac
  5. import time
  6. from typing import Any
  7. try:
  8. from aiohttp import web
  9. except ImportError:
  10. web = None # type: ignore[assignment]
  11. from gateway.platforms.api_server_room_grants import _json_error
  12. _ROOM_ONLY_FIELDS = frozenset({"hosted_room_dispatch", "_room_execution_policy"})
  13. async def _ensure_hosted_member_session(self, dispatch: Any) -> str:
  14. """Create or verify the target's canonical hidden group session. The ``Group: <room_id>``
  15. namespace is reused on purpose (Desktop-assisted -> hosted keeps one transcript); a
  16. conflicting title under another session id fails closed rather than merging."""
  17. db = await self._ensure_session_db_async()
  18. if db is None:
  19. raise RuntimeError("session database unavailable")
  20. title = f"Group: {dispatch.room_id}"
  21. seed = (
  22. f"{dispatch.home_install_id}\0{dispatch.room_id}\0"
  23. f"{dispatch.member_id}\0{dispatch.target_profile}")
  24. session_id = f"room_{hashlib.sha256(seed.encode()).hexdigest()[:32]}"
  25. from gateway.session_authorities import active_authority
  26. authority = active_authority(self.gateway_runner)
  27. if authority is not None:
  28. from gateway.session_api import bind_api_steps, hosted_member_session, run_steps_off_loop
  29. if db is not authority.db:
  30. raise RuntimeError('profile_mismatch')
  31. # A member session the user deleted stays deleted: the room moves to its next generation.
  32. identity = [dispatch.home_install_id, dispatch.room_id, dispatch.member_id, dispatch.target_profile]
  33. session_id = (await asyncio.to_thread(hosted_member_session, authority.db, identity))[1]
  34. # The binding transaction runs off the owner loop, in admission order (as API admission does).
  35. return (await run_steps_off_loop(authority, bind_api_steps(
  36. authority, session_id, hosted_dispatch=dispatch.as_mapping()))).session_id
  37. def atomic(conn):
  38. row = conn.execute("SELECT id, title, source FROM sessions WHERE id=?", (session_id,)).fetchone()
  39. if row is not None:
  40. if row["title"] != title or row["source"] != "bot_room":
  41. raise RuntimeError("room session identity conflicts with existing data")
  42. return session_id
  43. clean_title = db.sanitize_title(title)
  44. conflict = conn.execute(
  45. "SELECT id FROM sessions WHERE title=? AND id!=?", (clean_title, session_id)).fetchone()
  46. if conflict:
  47. raise RuntimeError(
  48. "Another group already uses this room title on the target gateway. "
  49. "Rename or migrate that group before retrying.")
  50. conn.execute(
  51. "INSERT INTO sessions(id, source, title, hidden, started_at) VALUES(?, 'bot_room', ?, 1, ?)",
  52. (session_id, clean_title, time.time()))
  53. return session_id
  54. return await asyncio.to_thread(db._execute_write, atomic)
  55. def _room_dispatch_error(exc: Exception, *, _openai_error) -> web.Response:
  56. message, code = str(exc), "invalid_room_dispatch"
  57. lowered = message.lower()
  58. if "execution policy" in lowered or "remote room execution requires" in lowered:
  59. message = "Room execution policy changed; reauthorization is required."
  60. code = "room_execution_policy_changed"
  61. elif "capability catalog changed" in lowered:
  62. message = "Room capability catalog changed; reauthorization is required."
  63. code = "room_capability_catalog_changed"
  64. return _json_error(_openai_error, message, code=code, status=403)
  65. async def _normalize_room_dispatch(
  66. self, request: web.Request, body: Any, *, _api_server) -> tuple[Any, web.Response | None]:
  67. """Validate and normalize a scoped RoomLink dispatch request."""
  68. _openai_error, room_token = _api_server._openai_error, self._room_grant_token(request)
  69. if not room_token:
  70. # Room fields are server-built from a verified grant; a caller-supplied copy would let an
  71. # API key choose its own toolsets, approval mode and turn limit.
  72. if isinstance(body, dict) and _ROOM_ONLY_FIELDS & set(body):
  73. return body, _json_error(
  74. _openai_error, "hosted_room_dispatch and _room_execution_policy require a room grant.",
  75. code="room_grant_required", status=403)
  76. return body, None
  77. if not isinstance(body, dict) or set(body) - {"input", "hosted_room_dispatch"}:
  78. return body, _json_error(
  79. _openai_error, "Room dispatch accepts only input and hosted_room_dispatch.",
  80. code="invalid_room_dispatch", status=400)
  81. try:
  82. from gateway import hosted_rooms
  83. from gateway.hosted_room_peer import GatewayRoomCatalog, HostedMemberDispatch, verify_room_grant
  84. from gateway.hosted_room_execution_policy import RoomExecutionPolicy
  85. from gateway.platforms.api_server_room_grants import _local_room_catalog
  86. dispatch = HostedMemberDispatch.from_mapping(body.get("hosted_room_dispatch"))
  87. verify_room_grant(self._room_grant_secret(), room_token, dispatch, permission="dispatch")
  88. active_profile = _api_server._api_request_profile.get() or "default"
  89. local_install = hosted_rooms.local_authority_gateway_id()
  90. if dispatch.target_profile != active_profile or dispatch.target_install_id != local_install:
  91. raise ValueError("room dispatch target does not match this profile")
  92. _, catalog_map = _local_room_catalog(self, active_profile, local_install)
  93. catalog = GatewayRoomCatalog.from_mapping(catalog_map)
  94. policy = RoomExecutionPolicy.from_mapping(catalog.execution_policy.as_mapping())
  95. if not hmac.compare_digest(policy.policy_digest, dispatch.execution_policy_digest):
  96. raise ValueError("room execution policy changed")
  97. if not hmac.compare_digest(catalog.catalog_digest, dispatch.capability_digest):
  98. raise ValueError("room capability catalog changed")
  99. if body.get("input") not in {None, dispatch.prompt}:
  100. raise ValueError("room dispatch input does not match its prompt")
  101. expected_key = f"room:{dispatch.task_id}:{dispatch.execution_generation}"
  102. if request.headers.get("Idempotency-Key", "").strip() != expected_key:
  103. raise ValueError("room dispatch idempotency key is invalid")
  104. session_id = await self._ensure_hosted_member_session(dispatch)
  105. return {
  106. "input": dispatch.prompt,
  107. "session_id": session_id,
  108. "hosted_room_dispatch": dispatch.as_mapping(),
  109. "_room_execution_policy": policy.as_mapping(),
  110. }, None
  111. except Exception as exc:
  112. return body, _room_dispatch_error(exc, _openai_error=_openai_error)