native_http.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. """Same-user private bootstrap at the existing HTTP authentication boundary.
  2. This is not remote/exposure delegation. The daemon captures the actual socket
  3. peer before proxy middleware, and the private control channel is the credential
  4. issuer. A browser Origin (including an empty one) always disqualifies this path.
  5. """
  6. from __future__ import annotations
  7. from contextlib import contextmanager
  8. from pathlib import Path
  9. from fastapi import HTTPException
  10. from starlette.responses import JSONResponse
  11. HEADER = 'x-hermes-gateway-ticket'
  12. def native_profile_scope(request):
  13. """Resolve the request's implicit selectors (omitted / '' / 'current') in the TICKET's home.
  14. ``_own_profile`` lets those selectors through unbound; the routes then resolve
  15. ``get_hermes_home()`` / ``_default_db_path()``, which is the launch home unless the
  16. task-local override says otherwise. A secondary-profile ticket must read and write its
  17. own profile, never the launch profile's dashboard state. The launch profile's own ticket
  18. binds its home override too, so it never inherits a foreign override that happens to be
  19. ambient in the request context.
  20. """
  21. return grant_home_scope(getattr(request.state, 'native_http_principal', None))
  22. @contextmanager
  23. def grant_home_scope(grant):
  24. """Bind *grant*'s home as the task-local home override; no-op without a grant."""
  25. if grant is None:
  26. yield
  27. return
  28. from hermes_constants import reset_hermes_home_override, set_hermes_home_override
  29. home = Path(grant['profile_id'])
  30. token = set_hermes_home_override(str(home))
  31. try:
  32. yield
  33. finally:
  34. reset_hermes_home_override(token)
  35. def _own_profile(value, profile_id, *, current=True):
  36. from hermes_cli.web_server_profiles import _resolve_profile_dir
  37. if value is None or (isinstance(value, str) and current
  38. and (not value.strip() or value.strip().lower() == 'current')):
  39. return
  40. if not isinstance(value, str):
  41. raise PermissionError('profile_scope_mismatch')
  42. try:
  43. target = _resolve_profile_dir(value.strip()).resolve()
  44. except HTTPException:
  45. raise PermissionError('profile_scope_mismatch') from None
  46. if target != Path(profile_id):
  47. raise PermissionError('profile_scope_mismatch')
  48. async def _check_profile_scope(request, profile_id):
  49. # Existing handlers select body.profile OR query.profile. Check every value,
  50. # including repeated query keys, rather than normalizing away a disagreement.
  51. path = request.url.path.rstrip('/')
  52. current = not path.startswith(('/api/profiles/', '/api/cron/jobs', '/api/sessions',
  53. '/api/fs/download', '/api/fs/read-data-url'))
  54. for value in request.query_params.getlist('profile'):
  55. _own_profile(value, profile_id, current=current)
  56. content_type = request.headers.get('content-type', '').split(';', 1)[0].strip().lower()
  57. if not content_type or content_type == 'application/json' or (
  58. content_type.startswith('application/') and content_type.endswith('+json')):
  59. try:
  60. body = await request.json()
  61. except (ValueError, UnicodeError):
  62. body = None # Route validation still owns malformed JSON.
  63. if isinstance(body, dict) and 'profile' in body:
  64. _own_profile(body['profile'], profile_id, current=current)
  65. if path.startswith('/api/cron/jobs') and not request.query_params.get('profile'):
  66. # Job-id discovery and the default list scan other profiles. Require an
  67. # explicit, verified named profile instead of silently changing defaults.
  68. raise PermissionError('profile_scope_mismatch')
  69. if path == '/api/profiles':
  70. # GET is the existing discovery list, not authority to open their DBs.
  71. if request.method != 'GET':
  72. raise PermissionError('profile_scope_mismatch')
  73. elif path.startswith('/api/profiles/'):
  74. suffix = path.removeprefix('/api/profiles/')
  75. collection = profile_collection_route(path, request.method)
  76. aggregate_selector = {
  77. 'sessions': 'profile', 'sessions/sidebar': 'recents_profile',
  78. 'projects/tree': 'profile', 'sessions/pull-requests': 'profile',
  79. }.get(collection)
  80. if aggregate_selector:
  81. values = request.query_params.getlist(aggregate_selector)
  82. if not values:
  83. raise PermissionError('profile_scope_mismatch')
  84. for value in values:
  85. # These routes interpret absent/all differently from /api/config.
  86. _own_profile(value, profile_id, current=False)
  87. elif collection == 'active' and request.method == 'GET':
  88. return # Discovery of sticky defaults does not switch this daemon.
  89. elif collection in {'active', 'import'}:
  90. raise PermissionError('profile_scope_mismatch')
  91. else:
  92. _own_profile(suffix.split('/', 1)[0], profile_id, current=False)
  93. if request.method in {'PATCH', 'DELETE'}:
  94. # Moving/deleting a home is a registry operation, not a profile REST write: it
  95. # rides the dedicated ``native-profile-registry`` grant (_check_registry_scope).
  96. raise PermissionError('profile_scope_mismatch')
  97. # ``/api/profiles/<suffix>`` collection routes, by method (hermes_cli/web_routers/profiles.py). Every
  98. # other method on these paths is the per-profile ``/api/profiles/{name}`` route of a profile NAMED
  99. # ``active``/``import``/``sessions``/…: valid profile names (PROFILE_ID_RE, not reserved).
  100. # Desktop mirror: apps/desktop/electron/profile-routes.ts.
  101. PROFILE_COLLECTION_ROUTES = {
  102. 'active': frozenset({'GET', 'POST'}), 'import': frozenset({'POST'}),
  103. 'projects/tree': frozenset({'GET'}), 'sessions': frozenset({'GET'}),
  104. 'sessions/pull-requests': frozenset({'POST'}), 'sessions/sidebar': frozenset({'GET'}),
  105. }
  106. def profile_collection_route(path, method):
  107. """The collection suffix ``method path`` serves, or None when the path names a profile."""
  108. suffix = path.rstrip('/').removeprefix('/api/profiles/')
  109. if suffix == path.rstrip('/'):
  110. return None
  111. return suffix if method.upper() in PROFILE_COLLECTION_ROUTES.get(suffix, ()) else None
  112. def _registry_target(request):
  113. """The profile a ``PATCH``/``DELETE /api/profiles/<name>`` names, or None for any other route."""
  114. if request.method not in {'PATCH', 'DELETE'}:
  115. return None
  116. suffix = request.url.path.rstrip('/').removeprefix('/api/profiles/')
  117. if suffix == request.url.path.rstrip('/') or not suffix or '/' in suffix:
  118. return None
  119. return suffix
  120. def _check_registry_scope(request, profile_id, launch_home):
  121. """A registry grant renames or deletes exactly the profile it was minted for (#140345).
  122. Never the gateway's launch home, which this live process is running in: deleting it or moving
  123. its directory pulls the runtime out from under itself. The default root's rename stays allowed,
  124. because it only sets a presentation ``display_name`` and never moves the directory.
  125. """
  126. target = _registry_target(request)
  127. for value in request.query_params.getlist('profile'):
  128. _own_profile(value, profile_id, current=False)
  129. _own_profile(target, profile_id, current=False)
  130. if launch_home is None:
  131. # Fail closed: with no known launch home the guard below cannot tell it apart.
  132. raise PermissionError('profile_scope_mismatch')
  133. from hermes_constants import get_default_hermes_root, hermes_home_key
  134. # Compared by hermes_home_key, as SessionAuthorities keys homes (symlinks, case, separators).
  135. launch = hermes_home_key(launch_home)
  136. if hermes_home_key(profile_id) == launch and not (
  137. request.method == 'PATCH' and launch == hermes_home_key(get_default_hermes_root())):
  138. raise PermissionError('profile_scope_mismatch')
  139. def _redeem_http_ticket(store, ticket, request):
  140. from gateway.runtime_bootstrap import _PURPOSE_CAPABILITIES
  141. try:
  142. grant = store.redeem(ticket, profile_id=None, purpose='native-http')
  143. except PermissionError:
  144. # Only these host-management operations accept a dedicated same-user grant.
  145. # Wrong-purpose redemption does not consume a ticket; ordinary profile grants
  146. # still reach _check_profile_scope and remain unable to create, move or delete profiles.
  147. if request.method == 'POST' and request.url.path.rstrip('/') == '/api/profiles':
  148. grant = store.redeem(ticket, profile_id=None, purpose='native-profile-create')
  149. elif _registry_target(request) is not None:
  150. grant = store.redeem(ticket, profile_id=None, purpose='native-profile-registry')
  151. else:
  152. raise
  153. # The issuer's own purpose -> capability table, not a second copy of it.
  154. if grant['capabilities'] != _PURPOSE_CAPABILITIES[grant['purpose']]:
  155. raise PermissionError('invalid native grant')
  156. return grant
  157. def _launch_home(runner):
  158. from gateway.session_authorities import all_authorities
  159. registry = getattr(runner, 'session_authorities', None)
  160. launch = registry.launch if registry is not None else (all_authorities(runner) or [None])[0]
  161. return launch.profile_id if launch is not None else None
  162. def _native_store(conn, tickets):
  163. """The runner's ticket store when *conn* may redeem a private grant here, else None."""
  164. from gateway.drain_control import restart_wait_read
  165. from gateway.session_authorities import all_authorities
  166. runner = getattr(conn.app.state, 'gateway_runner', None)
  167. descriptor = getattr(runner, 'session_runtime_descriptor', {})
  168. authorities = all_authorities(runner)
  169. store = getattr(runner, 'session_ticket_store', None)
  170. peer = conn.scope.get('hermes.gateway_socket_peer')
  171. if (len(tickets) != 1 or 'origin' in conn.headers or not peer
  172. or peer[0] not in {'127.0.0.1', '::1'}
  173. or descriptor.get('state') != 'ready'
  174. # A restart's after-turn wait still serves the reads that open a parked prompt (#139041).
  175. # A websocket scope has no method, so a socket upgrade never matches that GET allowlist.
  176. or (getattr(runner, '_draining', True)
  177. and not restart_wait_read(runner, conn.scope.get('method'), conn.url.path))
  178. or not authorities or store is None
  179. or store.instance_id != descriptor.get('instance_id')
  180. or any(a is not None and a.instance_id != store.instance_id for a in authorities)
  181. # A profile being hot-served (just created: a reserved ``None`` slot, then an authority
  182. # not yet published to the descriptor and ticket store) is not served yet. It cannot
  183. # redeem a grant, and it must not refuse every already-served profile meanwhile.
  184. or descriptor.get('served_profiles') != [
  185. {'profile_id': a.profile_id, 'home': a.profile_id} for a in authorities
  186. if a is not None and not getattr(a, 'retiring', False) and a.profile_id in store.profile_ids]):
  187. return None
  188. return runner, store
  189. def redeem_native_ws(conn):
  190. """Redeem the ``native-http`` grant a Desktop plugin socket upgrade presents; None when refused.
  191. Same issuer, header, peer/Origin and served-profile rules as HTTP: a plugin socket is the
  192. live twin of the plugin REST call that already rides this grant on a local gateway. The
  193. upgrade's ``profile`` selectors must name the grant's home. Plugin sockets only: ``/api/ws``
  194. and other core streams keep their own purpose-bound credentials. Called once per upgrade, by
  195. ``PluginApiWebSocketGate`` ahead of routing, so the grant's profile decides consent and scope
  196. before any route dependency or plugin code runs.
  197. """
  198. tickets = conn.headers.getlist(HEADER)
  199. gate = _native_store(conn, tickets) if conn.url.path.startswith('/api/plugins/') else None
  200. if gate is None:
  201. return None
  202. runner, store = gate
  203. from gateway.session_authorities import authority_for_profile_id
  204. try:
  205. grant = store.redeem(tickets[0], profile_id=None, purpose='native-http')
  206. if (grant['capabilities'] != frozenset({'http:owner'})
  207. or authority_for_profile_id(runner, grant['profile_id']) is None):
  208. return None
  209. for value in conn.query_params.getlist('profile'):
  210. _own_profile(value, grant['profile_id'])
  211. except PermissionError:
  212. return None
  213. return grant
  214. AUDIO_STREAM_PATHS = frozenset({'/api/audio/speak-stream', '/api/audio/transcribe-stream'})
  215. def redeem_audio_ws(ws):
  216. """Redeem the ``interactive`` grant a local Desktop's audio stream upgrade presents; None when refused.
  217. The voice sockets are siblings of the Desktop's ``/api/ws`` dial and ride the same one-use
  218. grant in the same gateway subprotocol (``gateway/run_api.py``), under the HTTP seam's
  219. peer/Origin/served-profile rules. The upgrade's ``profile`` selectors must name the grant's home.
  220. """
  221. from hermes_cli.web_server_boundary import _gateway_ws_ticket_from_subprotocol
  222. ticket, reason = _gateway_ws_ticket_from_subprotocol(ws)
  223. gate = _native_store(ws, [ticket]) if reason == 'ok' and ws.url.path in AUDIO_STREAM_PATHS else None
  224. if gate is None:
  225. return None
  226. runner, store = gate
  227. from gateway.session_authorities import authority_for_profile_id
  228. try:
  229. grant = store.redeem(ticket, profile_id=None, purpose='interactive')
  230. if authority_for_profile_id(runner, grant['profile_id']) is None:
  231. return None
  232. for value in ws.query_params.getlist('profile'):
  233. _own_profile(value, grant['profile_id'])
  234. except PermissionError:
  235. return None
  236. return grant
  237. def authenticate_native_ws(ws):
  238. """The grant :func:`redeem_native_ws` admitted for this plugin socket, or None (refused).
  239. Never redeems: the gate already did, once, and bound the grant's home and secret scope for
  240. the whole connection.
  241. """
  242. if not ws.url.path.startswith('/api/plugins/'):
  243. return None
  244. return getattr(ws.state, 'native_http_principal', None)
  245. async def authenticate_native_http(request):
  246. """Return a rejection or stamp a one-request principal; absent header is inert."""
  247. tickets = request.headers.getlist(HEADER)
  248. if not tickets:
  249. return None
  250. from gateway.session_authorities import authority_for_profile_id
  251. gate = _native_store(request, tickets)
  252. if gate is None:
  253. return JSONResponse({'detail': 'Unauthorized'}, status_code=401)
  254. runner, store = gate
  255. try:
  256. # The ticket names the served profile it was minted for; that home's authority owns it.
  257. grant = _redeem_http_ticket(store, tickets[0], request)
  258. if authority_for_profile_id(runner, grant['profile_id']) is None:
  259. raise PermissionError('unserved native grant')
  260. except PermissionError:
  261. return JSONResponse({'detail': 'Unauthorized'}, status_code=401)
  262. try:
  263. if grant['purpose'] == 'native-profile-registry':
  264. _check_registry_scope(request, grant['profile_id'], _launch_home(runner))
  265. elif grant['purpose'] != 'native-profile-create':
  266. await _check_profile_scope(request, grant['profile_id'])
  267. except PermissionError:
  268. return JSONResponse({'detail': 'profile_scope_mismatch'}, status_code=403)
  269. request.state.native_http_principal = grant
  270. return None