Skip to content

The agent that grows with you

fix(dashboard): bind implicit profile selectors of a native ticket to the ticket's profile (R2, reported by @rahlquist)

teknium1facb65a9a854
diff --git a/hermes_cli/dashboard_auth/native_http.py b/hermes_cli/dashboard_auth/native_http.py
index a9f6bc6ffd9..afd18acae7a 100644
--- a/hermes_cli/dashboard_auth/native_http.py
+++ b/hermes_cli/dashboard_auth/native_http.py
@@ -6,6 +6,7 @@ issuer. A browser Origin (including an empty one) always disqualifies this path.
"""
from __future__ import annotations
+from contextlib import contextmanager
from pathlib import Path
from fastapi import HTTPException
@@ -14,6 +15,32 @@ from starlette.responses import JSONResponse
HEADER = 'x-hermes-gateway-ticket'
+@contextmanager
+def native_profile_scope(request):
+ """Resolve the request's implicit selectors (omitted / '' / 'current') in the TICKET's home.
+
+ ``_own_profile`` lets those selectors through unbound; the routes then resolve
+ ``get_hermes_home()`` / ``_default_db_path()``, which is the launch home unless the
+ task-local override says otherwise. A secondary-profile ticket must read and write its
+ own profile, never the launch profile's dashboard state. The launch profile's own ticket
+ already resolves there, so it keeps the ambient (single-profile) behaviour byte-for-byte.
+ """
+ grant = getattr(request.state, 'native_http_principal', None)
+ if grant is None:
+ yield
+ return
+ from hermes_constants import get_process_hermes_home, reset_hermes_home_override, set_hermes_home_override
+ home = Path(grant['profile_id'])
+ if home.resolve() == get_process_hermes_home().resolve():
+ yield
+ return
+ token = set_hermes_home_override(str(home))
+ try:
+ yield
+ finally:
+ reset_hermes_home_override(token)
+
+
def _own_profile(value, profile_id, *, current=True):
from hermes_cli.web_server_profiles import _resolve_profile_dir
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index b13a19b7aa2..6bf060df253 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -535,12 +535,13 @@ async def _token_auth_seam(request: Request, call_next):
+ ``token_authenticated`` so downstream gates skip enforcement. Non-token
routes pass through untouched.
"""
- from hermes_cli.dashboard_auth.native_http import authenticate_native_http
+ from hermes_cli.dashboard_auth.native_http import authenticate_native_http, native_profile_scope
from hermes_cli.dashboard_auth.token_auth import token_auth_middleware
rejection = await authenticate_native_http(request)
if rejection is not None:
return rejection
- return await token_auth_middleware(request, call_next)
+ with native_profile_scope(request):
+ return await token_auth_middleware(request, call_next)
_DASHBOARD_HEALTH_WINDOW_SECONDS = 300.0
diff --git a/tests/gateway/test_native_http_secondary_profile_binding.py b/tests/gateway/test_native_http_secondary_profile_binding.py
new file mode 100644
index 00000000000..ea00249452c
--- /dev/null
+++ b/tests/gateway/test_native_http_secondary_profile_binding.py
@@ -0,0 +1,81 @@
+"""A secondary-profile native ticket binds every implicit profile selector to its own home."""
+import json
+import os
+from pathlib import Path
+import signal
+import subprocess
+import sys
+import time
+
+import httpx
+import pytest
+
+from tests.gateway.test_normal_runtime_boot import control
+
+
+def test_secondary_native_ticket_implicit_selectors_touch_only_the_secondary_home(tmp_path):
+ """R2: omitted / empty / ``current`` selectors used to pass ``_own_profile`` unbound, so the
+ route resolved through the LAUNCH home and a valid secondary ticket read and wrote the launch
+ profile's config. One read route and one write route, no explicit selector, must resolve
+ against the ticket's profile and leave the launch home byte-identical."""
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ beta = home / 'profiles' / 'beta'
+ beta.mkdir(parents=True)
+ (beta / 'config.yaml').write_text(json.dumps({'model': {'provider': 'custom', 'default': 'beta-model'}}))
+ (home / 'config.yaml').write_text(json.dumps({
+ 'gateway': {'multiplex_profiles': True},
+ 'model': {'provider': 'custom', 'default': 'launch-model', 'base_url': 'http://127.0.0.1:1/v1'},
+ 'auxiliary': {'title_generation': {'enabled': False}},
+ }))
+ launch_before = (home / 'config.yaml').read_bytes()
+ root = Path(__file__).resolve().parents[2]
+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') 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() + 60
+ 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())
+ served = {p['profile_id'] for p in descriptor['served_profiles']}
+ assert str(beta.resolve()) in served and str(home.resolve()) in served, descriptor
+
+ def ticket():
+ return control(home, 'session-ticket', {'profile_id': str(beta.resolve()),
+ 'instance_id': descriptor['instance_id'], 'purpose': 'native-http'})['ticket']
+
+ with httpx.Client(base_url=descriptor['api_origin'], trust_env=False, timeout=30) as client:
+ for params in ({}, {'profile': ''}, {'profile': 'current'}):
+ response = client.get('/api/config', params=params,
+ headers={'X-Hermes-Gateway-Ticket': ticket()})
+ assert response.status_code == 200, (params, response.text)
+ assert 'beta-model' in response.text and 'launch-model' not in response.text, (params, response.text)
+ for body in ({}, {'profile': 'current'}):
+ updated = client.put('/api/config', json={**body, 'config': {'display': {'skin': 'ares'}}},
+ headers={'X-Hermes-Gateway-Ticket': ticket()})
+ assert updated.status_code == 200, (body, updated.text)
+ import yaml
+ assert yaml.safe_load((beta / 'config.yaml').read_text())['display']['skin'] == 'ares'
+ assert (home / 'config.yaml').read_bytes() == launch_before
+ 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)