The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: authenticate native HTTP through private daemon grants
Teknium75764b2ad0c8
diff --git a/gateway/run_api.py b/gateway/run_api.pyindex 9b693c1e5a1..43caac1da5e 100644--- a/gateway/run_api.py+++ b/gateway/run_api.py@@ -112,6 +112,9 @@ class GatewayRuntimeAPI:await JSONResponse({'error': 'gateway_not_ready', 'state': descriptor['state']},status_code=503)(scope, receive, send)return+ if scope['type'] == 'http':+ # Capture before Uvicorn's proxy middleware rewrites scope.client.+ scope['hermes.gateway_socket_peer'] = scope.get('client')if scope['type'] != 'websocket' or scope['path'] != '/api/ws':return await self.app(scope, receive, send)original_receive = receivediff --git a/gateway/runtime_bootstrap.py b/gateway/runtime_bootstrap.pyindex fb15b9ee628..4bad2036a0f 100644--- a/gateway/runtime_bootstrap.py+++ b/gateway/runtime_bootstrap.py@@ -9,6 +9,7 @@ import time_PURPOSE_CAPABILITIES = {'interactive': frozenset({'session:create', 'session:read', 'session:submit','session:control', 'session:approve', 'session:respond'}),+ 'native-http': frozenset({'http:owner'}),'exposure': frozenset({'transport:delegate'}),'worker-adoption': frozenset({'worker:adopt'}),}diff --git a/hermes_cli/dashboard_auth/middleware.py b/hermes_cli/dashboard_auth/middleware.pyindex 80c7bcc8a1f..ae366c4bfc7 100644--- a/hermes_cli/dashboard_auth/middleware.py+++ b/hermes_cli/dashboard_auth/middleware.py@@ -152,7 +152,9 @@ async def gated_auth_middleware(return await call_next(request)# Already authenticated by the token-auth seam (service caller on a registered token# route): not a cookie session, must not bounce to /login.- if getattr(request.state, "token_authenticated", False) or _path_is_public(request.url.path):+ if (getattr(request.state, "token_authenticated", False)+ or getattr(request.state, "native_http_principal", None)+ or _path_is_public(request.url.path)):return await call_next(request)# RFC 8252 native-app bearer path: the same provider-minted access token the cookie flow# stores, verified with the same provider stack, no cookie read or set. A presented-but-diff --git a/hermes_cli/dashboard_auth/native_http.py b/hermes_cli/dashboard_auth/native_http.pynew file mode 100644index 00000000000..8ce245d95f6--- /dev/null+++ b/hermes_cli/dashboard_auth/native_http.py@@ -0,0 +1,104 @@+"""Same-user private bootstrap at the existing HTTP authentication boundary.++This is not remote/exposure delegation. The daemon captures the actual socket+peer before proxy middleware, and the private control channel is the credential+issuer. A browser Origin (including an empty one) always disqualifies this path.+"""+from __future__ import annotations++import json+from pathlib import Path++from fastapi import HTTPException+from starlette.responses import JSONResponse++HEADER = 'x-hermes-gateway-ticket'+++def _own_profile(value, profile_id, *, current=True):+ from hermes_cli.web_server_profiles import _resolve_profile_dir++ if value is None or (isinstance(value, str) and current+ and (not value.strip() or value.strip().lower() == 'current')):+ return+ if not isinstance(value, str):+ raise PermissionError('profile_scope_mismatch')+ try:+ target = _resolve_profile_dir(value.strip()).resolve()+ except HTTPException:+ raise PermissionError('profile_scope_mismatch') from None+ if target != Path(profile_id):+ raise PermissionError('profile_scope_mismatch')+++async def _check_profile_scope(request, profile_id):+ # Existing handlers select body.profile OR query.profile. Check every value,+ # including repeated query keys, rather than normalizing away a disagreement.+ for value in request.query_params.getlist('profile'):+ _own_profile(value, profile_id)+ if request.headers.get('content-type', '').split(';', 1)[0].strip() == 'application/json':+ try:+ body = await request.json()+ except (ValueError, UnicodeError):+ body = None # Route validation still owns malformed JSON.+ if isinstance(body, dict) and 'profile' in body:+ _own_profile(body['profile'], profile_id)+ path = request.url.path.rstrip('/')+ if path == '/api/profiles':+ # GET is the existing discovery list, not authority to open their DBs.+ if request.method != 'GET':+ raise PermissionError('profile_scope_mismatch')+ elif path.startswith('/api/profiles/'):+ suffix = path.removeprefix('/api/profiles/')+ aggregate_selector = {+ 'sessions': 'profile', 'sessions/sidebar': 'recents_profile',+ }.get(suffix)+ if aggregate_selector:+ values = request.query_params.getlist(aggregate_selector)+ if not values:+ raise PermissionError('profile_scope_mismatch')+ for value in values:+ # These routes interpret absent/all differently from /api/config.+ _own_profile(value, profile_id, current=False)+ elif suffix == 'active' and request.method == 'GET':+ return # Discovery of sticky defaults does not switch this daemon.+ elif suffix in {'active', 'import', 'projects/tree', 'sessions/pull-requests'}:+ raise PermissionError('profile_scope_mismatch')+ else:+ _own_profile(suffix.split('/', 1)[0], profile_id, current=False)+ if request.method in {'PATCH', 'DELETE'}:+ # Moving/deleting the reserved home is not an in-place operation.+ raise PermissionError('profile_scope_mismatch')+++async def authenticate_native_http(request):+ """Return a rejection or stamp a one-request principal; absent header is inert."""+ tickets = request.headers.getlist(HEADER)+ if not tickets:+ return None+ runner = getattr(request.app.state, 'gateway_runner', None)+ descriptor = getattr(runner, 'session_runtime_descriptor', {})+ authority = getattr(runner, 'session_authority', None)+ store = getattr(runner, 'session_ticket_store', None)+ peer = request.scope.get('hermes.gateway_socket_peer')+ if (len(tickets) != 1 or 'origin' in request.headers or not peer+ or peer[0] not in {'127.0.0.1', '::1'}+ or descriptor.get('state') != 'ready' or getattr(runner, '_draining', True)+ or authority is None or store is None+ or store.instance_id != descriptor.get('instance_id')+ or authority.instance_id != store.instance_id+ or descriptor.get('served_profiles') != [+ {'profile_id': authority.profile_id, 'home': authority.profile_id}]):+ return JSONResponse({'detail': 'Unauthorized'}, status_code=401)+ try:+ grant = store.redeem(tickets[0], profile_id=authority.profile_id, purpose='native-http')+ if grant['capabilities'] != frozenset({'http:owner'}):+ raise PermissionError('invalid native grant')+ except PermissionError:+ return JSONResponse({'detail': 'Unauthorized'}, status_code=401)+ try:+ await _check_profile_scope(request, grant['profile_id'])+ except PermissionError:+ return JSONResponse({'detail': 'profile_scope_mismatch'}, status_code=403)+ request.state.native_http_principal = grant+ return Nonediff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 4e2d3be3b35..2958e2b932a 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -505,6 +505,7 @@ async def auth_middleware(request: Request, call_next):path = request.url.pathif (not getattr(request.state, "token_authenticated", False)+ and not getattr(request.state, "native_http_principal", None)and not getattr(request.app.state, "auth_required", False)and path.startswith("/api/")and path not in _PUBLIC_API_PATHS@@ -524,7 +525,11 @@ async def _token_auth_seam(request: Request, call_next):+ ``token_authenticated`` so downstream gates skip enforcement. Non-tokenroutes pass through untouched."""+ from hermes_cli.dashboard_auth.native_http import authenticate_native_httpfrom hermes_cli.dashboard_auth.token_auth import token_auth_middleware+ rejection = await authenticate_native_http(request)+ if rejection is not None:+ return rejectionreturn await token_auth_middleware(request, call_next)diff --git a/tests/gateway/test_native_http_auth.py b/tests/gateway/test_native_http_auth.pynew file mode 100644index 00000000000..230734ba9eb--- /dev/null+++ b/tests/gateway/test_native_http_auth.py@@ -0,0 +1,130 @@+"""Private native grants authenticate HTTP, never another purpose or profile."""+import asyncio+from contextlib import contextmanager+import json+import os+from pathlib import Path+import signal+import subprocess+import sys+import time++import httpx+import pytest+from websockets.asyncio.client import connect+from websockets.exceptions import InvalidStatus++from tests.gateway.test_normal_runtime_boot import control+++@contextmanager+def daemon(tmp_path):+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700, exist_ok=True)+ user.mkdir(exist_ok=True)+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'native-http-fixture',+ 'base_url': 'http://127.0.0.1:1/v1'},+ 'auxiliary': {'title_generation': {'enabled': False}},+ }))+ root = Path(__file__).resolve().parents[2]+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), PYTHONUNBUFFERED='1',+ HERMES_DASHBOARD_SESSION_TOKEN='normal-http-owner')+ with (tmp_path / 'gateway.log').open('w+') as log:+ process = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ try:+ deadline = time.monotonic() + 40+ descriptor = {}+ while process.poll() is None and time.monotonic() < deadline:+ try:+ descriptor = control(home, 'identify')+ if descriptor.get('state') == 'ready':+ break+ except (OSError, ValueError):+ pass+ time.sleep(.1)+ log.seek(0)+ assert descriptor.get('state') == 'ready', (descriptor, log.read())+ yield home, descriptor+ finally:+ if process.poll() is None:+ process.send_signal(signal.SIGINT)+ try:+ process.wait(timeout=20)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+++def ticket(home, descriptor, purpose='native-http', **overrides):+ return control(home, 'session-ticket', {+ 'profile_id': str(home.resolve()), 'instance_id': descriptor['instance_id'],+ 'purpose': purpose, **overrides,+ })['ticket']+++def headers(token):+ return {'X-Hermes-Gateway-Ticket': token}+++async def reject_ws(origin, token):+ with pytest.raises(InvalidStatus):+ async with connect(origin.replace('http:', 'ws:') + '/api/ws', subprotocols=[+ 'hermes-gateway-v1', 'hermes-gateway-ticket.' + token]):+ pass++[email protected]_only+def test_native_http_grants_are_single_use_and_bound_to_daemon(tmp_path):+ with daemon(tmp_path) as (home, descriptor), httpx.Client(+ base_url=descriptor['api_origin'], trust_env=False) as client:+ assert client.get('/api/config').status_code == 401+ normal = {'Authorization': 'Bearer normal-http-owner'}+ assert client.get('/api/config', headers=normal).status_code == 200+ first = ticket(home, descriptor)+ response = client.get('/api/config', headers=headers(first))+ assert response.status_code == 200, response.text+ assert 'native-http-fixture' in response.text+ assert client.get('/api/config', headers=headers(first)).status_code == 401+ assert client.get('/api/config', headers={**normal, **headers('invalid')}).status_code == 401+ for origin in ('https://evil.example', '', 'null'):+ assert client.get('/api/config', headers={**headers(ticket(home, descriptor)),+ 'Origin': origin}).status_code == 401+ assert client.get('/api/config', headers=[+ ('X-Hermes-Gateway-Ticket', ticket(home, descriptor)),+ ('X-Hermes-Gateway-Ticket', ticket(home, descriptor)),+ ]).status_code == 401+ for purpose in ('interactive', 'exposure', 'worker-adoption'):+ assert client.get('/api/config', headers=headers(ticket(home, descriptor, purpose))).status_code == 401+ asyncio.run(reject_ws(descriptor['api_origin'], ticket(home, descriptor)))+ for overrides in ({'instance_id': 'stale'}, {'profile_id': str(tmp_path / 'other')}):+ with pytest.raises(AssertionError, match='PermissionError'):+ ticket(home, descriptor, **overrides)+ for path in ('/api/config?profile=other', '/api/config?profile=current&profile=other',+ '/api/profiles/other/soul'):+ assert client.get(path, headers=headers(ticket(home, descriptor))).status_code == 403+ assert client.post('/api/config', json={'profile': 'other', 'config': {}},+ headers=headers(ticket(home, descriptor))).status_code == 403+ assert client.get('/api/config?profile=current',+ headers=headers(ticket(home, descriptor))).status_code == 200+ assert client.get('/api/profiles', headers=headers(ticket(home, descriptor))).status_code == 200+ query_ticket = ticket(home, descriptor)+ assert client.get('/api/config', params={'ticket': query_ticket}).status_code == 401+ assert client.get('/api/config', headers={'Cookie': 'X-Hermes-Gateway-Ticket=' + query_ticket}).status_code == 401+ expired = ticket(home, descriptor)+ time.sleep(31) # Real production TTL, not a patched clock or shortened grant.+ assert client.get('/api/config', headers=headers(expired)).status_code == 401+ stale = ticket(home, descriptor)+ old_instance = descriptor['instance_id']+ assert 'ticket' not in json.dumps(control(home, 'identify')).lower()+ with daemon(tmp_path) as (home, descriptor), httpx.Client(+ base_url=descriptor['api_origin'], trust_env=False) as client:+ assert descriptor['instance_id'] != old_instance+ assert client.get('/api/config', headers=headers(stale)).status_code == 401+ assert client.get('/api/config', headers=headers(ticket(home, descriptor))).status_code == 200+ print(json.dumps({'native_http': 'ordinary daemon config and profiles HTTP passed',+ 'replay_expiry_restart_purpose_origin_profile': 'rejected'}))