The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(profiles): rename and delete a served profile over a dedicated native registry grant
Tekniumaa00b801b9ca
diff --git a/apps/desktop/electron/connection-config.test.ts b/apps/desktop/electron/connection-config.test.tsindex 8e4c4bf093d..f924f0ec107 100644--- a/apps/desktop/electron/connection-config.test.ts+++ b/apps/desktop/electron/connection-config.test.ts@@ -649,6 +649,24 @@ test('pathForRegistryBackendRequest uses the resolved registry backend scope', ()})+test('a /api/profiles/<name>/… path already names its profile: no ambient scope is appended (#140791)', () => {+ for (const backend of [{ mode: 'local' }, { sharedPrimary: true }, { sharedRemote: true }]) {+ for (const ambient of ['default', '__all__', 'beta']) {+ for (const path of ['/api/profiles/p2/soul', '/api/profiles/p2', '/api/profiles/p2/model',+ '/api/profiles/projects/soul', '/api/profiles/sessions/soul']) {+ assert.equal(pathForRegistryBackendRequest(path, ambient, backend), path)+ }++ // Collection routes under /api/profiles/ carry no name in the path: they still get the scope.+ for (const path of ['/api/profiles/sessions', '/api/profiles/projects/tree', '/api/profiles']) {+ assert.equal(pathForRegistryBackendRequest(path, ambient, backend), `${path}?profile=${ambient}`)+ }+ }+ }++ assert.equal(pathWithProfileScope('/api/profiles/p2/soul', 'default'), '/api/profiles/p2/soul')+})+test('registry model reads and writes retain each profile on a shared local backend', () => {for (const backend of [{ mode: 'local' }, { sharedPrimary: true }]) {for (const profile of ['research', 'default', 'research']) {diff --git a/apps/desktop/electron/connection-config.ts b/apps/desktop/electron/connection-config.tsindex 9378401dcc0..e1f89b36257 100644--- a/apps/desktop/electron/connection-config.ts+++ b/apps/desktop/electron/connection-config.ts@@ -1007,6 +1007,21 @@ function translateSelfProfileQuery(path, profile, backendProfile) {* gateway host serving every profile, scoped per request). An explicit* `?profile=` already on the path wins; an empty profile is a no-op.*/+// `/api/profiles/<suffix>` routes that are collections, not a profile named in the path. Matched on+// the whole suffix (the gateway's native_http._check_profile_scope and local-gateway.ts's+// PROFILE_COLLECTION_ROUTES use the same set), so a profile NAMED `sessions` keeps its own path.+const PROFILE_COLLECTION_SUFFIXES = new Set([+ 'active', 'import', 'projects/tree', 'sessions', 'sessions/pull-requests', 'sessions/sidebar'+])++/** True for `/api/profiles/<name>[/…]`: the path itself names the target profile (#140791). */+function pathNamesProfile(pathname: string): boolean {+ const suffix = pathname.replace(/\/+$/, '').startsWith('/api/profiles/')+ ? pathname.replace(/\/+$/, '').slice('/api/profiles/'.length) : ''++ return Boolean(suffix) && !PROFILE_COLLECTION_SUFFIXES.has(suffix)+}+function pathWithProfileScope(path, profile) {const scopedProfile = connectionScopeKey(profile)@@ -1028,7 +1043,9 @@ function pathWithProfileScope(path, profile) {return path}- if (parsed.searchParams.has('profile')) {+ // A path that already names its profile never also carries the ambient one: the two disagree+ // whenever the sidebar is on another profile or "All profiles", and the gateway refuses the pair.+ if (parsed.searchParams.has('profile') || pathNamesProfile(parsed.pathname)) {return path}diff --git a/apps/desktop/electron/local-gateway-python.ts b/apps/desktop/electron/local-gateway-python.tsindex b2f53797cea..c8eaf7bec2e 100644--- a/apps/desktop/electron/local-gateway-python.ts+++ b/apps/desktop/electron/local-gateway-python.ts@@ -77,7 +77,7 @@ class TicketBridge {this.child.on('close', () => this.dispose())}- request(endpoint: TicketEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create'): Promise<string> {+ request(endpoint: TicketEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create' | 'native-profile-registry'): Promise<string> {clearTimeout(this.idleTimer)return new Promise((resolve, reject) => {@@ -238,7 +238,7 @@ export function createGatewayTicketResolver(resolveBackend: () => Promise<Resolvlet cached: Promise<{ command: string; env?: NodeJS.ProcessEnv }> | undefinedlet cachedGeneration = -1- return async (endpoint: TicketEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create'): Promise<string> => {+ return async (endpoint: TicketEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create' | 'native-profile-registry'): Promise<string> => {const generation = bridgeGenerationif (!cached || cachedGeneration !== generation) {@@ -264,7 +264,7 @@ export function mintGatewayTicketWithPython(backend: { command: string; env?: NodeJS.ProcessEnv },cwd: string,endpoint: TicketEndpoint,- purpose: 'interactive' | 'native-http' | 'native-profile-create'+ purpose: 'interactive' | 'native-http' | 'native-profile-create' | 'native-profile-registry'): Promise<string> {const env = { ...process.env, ...backend.env, HERMES_HOME: endpoint.profile_id,PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1' }diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.tsindex 49f0f0923ac..3550e0255bf 100644--- a/apps/desktop/electron/local-gateway.test.ts+++ b/apps/desktop/electron/local-gateway.test.ts@@ -97,7 +97,13 @@ test.skipIf(process.platform === 'win32').each([0o700, 0o750, 0o701])('native HT['/api/profiles?unused=1', 'post', 'native-profile-create'],['/api/profiles', 'GET', 'native-http'],['/api/profiles/import', 'POST', 'native-http'],- ['/api/config', 'POST', 'native-http']+ ['/api/config', 'POST', 'native-http'],+ // Rename/delete of the launch profile ride the registry grant (#140345); its SOUL stays native-http.+ ['/api/profiles/default', 'PATCH', 'native-profile-registry'],+ ['/api/profiles/default', 'delete', 'native-profile-registry'],+ ['/api/profiles/default/soul', 'PUT', 'native-http'],+ ['/api/profiles/active', 'PATCH', 'native-http'],+ ['/api/profiles/import', 'DELETE', 'native-http']]) {await nativeGatewayHttpHeaders(descriptor, endpoint.api_origin + route, home, method)expect(requests.at(-1).params).toEqual({ profile_id: home, instance_id: 'owner', purpose })diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.tsindex dc7796db6e1..671261b3aad 100644--- a/apps/desktop/electron/local-gateway.ts+++ b/apps/desktop/electron/local-gateway.ts@@ -468,6 +468,25 @@ export async function routedTicketEndpoint(endpoint: GatewayEndpoint, urlOrProfireturn { ...routed, profile_id: home }}+/** Every purpose a Desktop mints a gateway ticket for (gateway/runtime_bootstrap.py). */+export type GatewayTicketPurpose = 'interactive' | 'native-http' | 'native-profile-create' | 'native-profile-registry'++/** The native grant a REST request needs. Creating a profile and renaming/deleting the one a path+ * names are registry operations with grants of their own; every other route is `native-http`. */+export function nativeGrantPurpose(url: string, method = 'GET'): GatewayTicketPurpose {+ const verb = method.toUpperCase()+ const pathname = new URL(url).pathname.replace(/\/+$/, '')++ if (verb === 'POST' && pathname === '/api/profiles') {return 'native-profile-create'}+ const suffix = pathname.startsWith('/api/profiles/') ? pathname.slice('/api/profiles/'.length) : ''++ if ((verb === 'PATCH' || verb === 'DELETE') && suffix && !suffix.includes('/') && !PROFILE_COLLECTION_ROUTES.has(suffix)) {+ return 'native-profile-registry'+ }++ return 'native-http'+}+/** What a native grant is minted for: the URL's own profile selector or, when it names none, a* JSON body's `profile`. The gateway checks both against the grant, and a session write such as* `PATCH /api/sessions/<id>` names its owner in the body alone. */@@ -483,21 +502,20 @@ export async function nativeGatewayHttpHeaders(descriptor: { gatewayEndpoint: Gathrow new Error('Native gateway HTTP origin mismatch')}- const purpose = method.toUpperCase() === 'POST' && new URL(url).pathname.replace(/\/$/, '') === '/api/profiles'- ? 'native-profile-create' : 'native-http'+ const purpose = nativeGrantPurpose(url, method)return { 'X-Hermes-Gateway-Ticket': await mintLocalGatewayTicket(await routedTicketEndpoint(descriptor.gatewayEndpoint, nativeGrantRoute(url, body), launchHome), purpose) }}// The installed runtime's own ticket client: every Windows mint (SID-validated pipe), and a POSIX// home whose group-write only Python can prove private.-let pythonTicketClient: ((endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create') => Promise<string>) | undefined+let pythonTicketClient: ((endpoint: GatewayEndpoint, purpose: GatewayTicketPurpose) => Promise<string>) | undefinedexport function configurePythonGatewayTicketClient(client: NonNullable<typeof pythonTicketClient>) {pythonTicketClient = client}-async function mintGroupWritableHome(endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create', homes: string[]) {+async function mintGroupWritableHome(endpoint: GatewayEndpoint, purpose: GatewayTicketPurpose, homes: string[]) {if (!pythonTicketClient) {throw new Error(`Unsafe gateway control path: profile home is group-writable and this Desktop cannot verify the group is private: run chmod g-w ${homes.map(shellQuote).join(' ')}`)}try {@@ -584,11 +602,11 @@ async function resolveControlSocket(home: string): Promise<string> {/** The Desktop's interactive socket is the one shared-primary route: its renderer selects every* served sibling with a `profile` param, so it asks for a host-scoped grant explicitly. Every* other ticket (and every other client's) stays bound to the one profile it names. */-export function ticketScope(purpose: 'interactive' | 'native-http' | 'native-profile-create'): { scope?: 'host' } {+export function ticketScope(purpose: GatewayTicketPurpose): { scope?: 'host' } {return purpose === 'interactive' ? { scope: 'host' } : {}}-export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create' = 'interactive'): Promise<string> {+export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint, purpose: GatewayTicketPurpose = 'interactive'): Promise<string> {if (process.platform === 'win32') {if (!pythonTicketClient) {throw new Error('Gateway ticket client is not configured')}diff --git a/gateway/runtime_bootstrap.py b/gateway/runtime_bootstrap.pyindex 61a882df37b..564757e3b86 100644--- a/gateway/runtime_bootstrap.py+++ b/gateway/runtime_bootstrap.py@@ -12,6 +12,9 @@ _PURPOSE_CAPABILITIES = {'native-http': frozenset({'http:owner'}),# Same-user host operation, not permission to read or mutate another profile.'native-profile-create': frozenset({'profiles:create'}),+ # Rename/delete of the ONE profile it is minted for (#140345): a registry write on that home,+ # never a read of it or any other route.+ 'native-profile-registry': frozenset({'profiles:registry'}),'exposure': frozenset({'transport:delegate'}),'worker-adoption': frozenset({'worker:adopt'}),}diff --git a/hermes_cli/dashboard_auth/native_http.py b/hermes_cli/dashboard_auth/native_http.pyindex 92ebe530a7c..6315f50bdac 100644--- a/hermes_cli/dashboard_auth/native_http.py+++ b/hermes_cli/dashboard_auth/native_http.py@@ -100,27 +100,66 @@ async def _check_profile_scope(request, profile_id):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.+ # Moving/deleting a home is a registry operation, not a profile REST write: it+ # rides the dedicated ``native-profile-registry`` grant (_check_registry_scope).raise PermissionError('profile_scope_mismatch')+def _registry_target(request):+ """The profile a ``PATCH``/``DELETE /api/profiles/<name>`` names, or None for any other route."""+ if request.method not in {'PATCH', 'DELETE'}:+ return None+ suffix = request.url.path.rstrip('/').removeprefix('/api/profiles/')+ if suffix == request.url.path.rstrip('/') or not suffix or '/' in suffix or suffix in {'active', 'import'}:+ return None+ return suffix+++def _check_registry_scope(request, profile_id, launch_home):+ """A registry grant renames or deletes exactly the profile it was minted for (#140345).++ Never the gateway's launch home, which this live process is running in: deleting it or moving+ its directory pulls the runtime out from under itself. The default root's rename stays allowed,+ because it only sets a presentation ``display_name`` and never moves the directory.+ """+ target = _registry_target(request)+ for value in request.query_params.getlist('profile'):+ _own_profile(value, profile_id, current=False)+ _own_profile(target, profile_id, current=False)+ from hermes_constants import get_default_hermes_root+ if Path(profile_id) == launch_home and not (+ request.method == 'PATCH' and launch_home == get_default_hermes_root().resolve()):+ raise PermissionError('profile_scope_mismatch')++def _redeem_http_ticket(store, ticket, request):try:grant = store.redeem(ticket, profile_id=None, purpose='native-http')expected = frozenset({'http:owner'})except PermissionError:- # Only this host-management operation accepts the dedicated same-user grant.+ # Only these host-management operations accept a dedicated same-user grant.# Wrong-purpose redemption does not consume a ticket; ordinary profile grants- # still reach _check_profile_scope and remain unable to create other profiles.- if request.method != 'POST' or request.url.path.rstrip('/') != '/api/profiles':+ # still reach _check_profile_scope and remain unable to create, move or delete profiles.+ if request.method == 'POST' and request.url.path.rstrip('/') == '/api/profiles':+ grant = store.redeem(ticket, profile_id=None, purpose='native-profile-create')+ expected = frozenset({'profiles:create'})+ elif _registry_target(request) is not None:+ grant = store.redeem(ticket, profile_id=None, purpose='native-profile-registry')+ expected = frozenset({'profiles:registry'})+ else:raise- grant = store.redeem(ticket, profile_id=None, purpose='native-profile-create')- expected = frozenset({'profiles:create'})if grant['capabilities'] != expected:raise PermissionError('invalid native grant')return grant+def _launch_home(runner):+ from gateway.session_authorities import all_authorities+ registry = getattr(runner, 'session_authorities', None)+ launch = registry.launch if registry is not None else (all_authorities(runner) or [None])[0]+ return Path(launch.profile_id) if launch is not None else None++def _native_store(conn, tickets):"""The runner's ticket store when *conn* may redeem a private grant here, else None."""from gateway.drain_control import restart_wait_read@@ -207,7 +246,9 @@ async def authenticate_native_http(request):except PermissionError:return JSONResponse({'detail': 'Unauthorized'}, status_code=401)try:- if grant['purpose'] != 'native-profile-create':+ if grant['purpose'] == 'native-profile-registry':+ _check_registry_scope(request, grant['profile_id'], _launch_home(runner))+ elif grant['purpose'] != 'native-profile-create':await _check_profile_scope(request, grant['profile_id'])except PermissionError:return JSONResponse({'detail': 'profile_scope_mismatch'}, status_code=403)diff --git a/tests/gateway/test_native_profile_registry_grant.py b/tests/gateway/test_native_profile_registry_grant.pynew file mode 100644index 00000000000..b9f9a7b2877--- /dev/null+++ b/tests/gateway/test_native_profile_registry_grant.py@@ -0,0 +1,136 @@+"""Desktop rename/delete of a served profile over a native grant (#134889 DB-5, #140345, #140791).++A multiplexing gateway refused ``PATCH``/``DELETE /api/profiles/<name>`` under every native grant,+even one minted for that very profile, so the Desktop Profiles screen could never rename or delete a+profile while a gateway ran. Rename/delete now ride a dedicated ``native-profile-registry`` grant+(the twin of ``native-profile-create``): minted for the named profile's own home, redeemable only+for ``PATCH``/``DELETE`` of that one profile, never for the gateway's launch profile's home move,+and never for any other route. An ordinary ``native-http`` grant keeps refusing both.+"""+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++[email protected]('linux')+def test_registry_grant_renames_and_deletes_only_its_own_served_profile(tmp_path):+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ model = {'model': {'provider': 'custom', 'default': 'm', 'base_url': 'http://127.0.0.1:1/v1'},+ 'auxiliary': {'title_generation': {'enabled': False}}}+ (home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': True}, **model}))+ for name in ('beta', 'gamma', 'keep'):+ (home / 'profiles' / name).mkdir(parents=True)+ (home / 'profiles' / name / 'config.yaml').write_text(json.dumps(model))+ 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')+ 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, descriptor = time.monotonic() + 60, {}+ while process.poll() is None and time.monotonic() < deadline:+ try:+ descriptor = control(home, 'identify')+ if descriptor.get('state') == 'ready' and len(descriptor.get('served_profiles', [])) == 4:+ break+ except (OSError, ValueError):+ pass+ time.sleep(.1)+ log.seek(0)+ assert descriptor.get('state') == 'ready', (descriptor, log.read())++ def home_of(profile):+ return str(home.resolve() if profile == 'default' else (home / 'profiles' / profile).resolve())++ def grant(profile, purpose):+ return {'X-Hermes-Gateway-Ticket': control(home, 'session-ticket', {+ 'profile_id': home_of(profile), 'purpose': purpose,+ 'instance_id': control(home, 'identify')['instance_id']})['ticket']}++ def ready():+ # A rename/delete rescans the served set; wait for the descriptor to settle so the+ # next grant is not refused as "a profile being hot-served".+ d = {}+ for _ in range(200):+ d = control(home, 'identify')+ if d.get('state') == 'ready':+ return d+ time.sleep(.05)+ return d++ with httpx.Client(base_url=descriptor['api_origin'], trust_env=False, timeout=60) as client:+ # The Desktop's request shape before this fix: a native-http grant for the profile the+ # path names. It stays refused (a profile REST grant is not a registry operation).+ for method, body in (('DELETE', None), ('PATCH', {'new_name': 'renamed'})):+ response = client.request(method, '/api/profiles/beta', json=body,+ headers=grant('beta', 'native-http'))+ assert response.status_code == 403, (method, response.text)+ assert (home / 'profiles' / 'beta').is_dir()++ registry = 'native-profile-registry'+ # Bound to the profile it was minted for: beta's grant cannot touch gamma.+ response = client.delete('/api/profiles/gamma', headers=grant('beta', registry))+ assert response.status_code == 403, response.text+ assert (home / 'profiles' / 'gamma').is_dir()+ # Bound to the two registry writes: no read, no create, no SOUL write, no import.+ for method, path, body in (('GET', '/api/config', None), ('GET', '/api/profiles/beta/soul', None),+ ('PUT', '/api/profiles/beta/soul', {'content': 'x'}),+ ('POST', '/api/profiles', {'name': 'sneaky'}),+ ('POST', '/api/profiles/import', {'archive': 'x'})):+ response = client.request(method, path, json=body, headers=grant('beta', registry))+ assert response.status_code == 401, (method, path, response.text)+ assert not (home / 'profiles' / 'sneaky').exists()++ # The fix: a registry grant for the named profile renames and deletes it live.+ response = client.patch('/api/profiles/gamma', json={'new_name': 'delta'},+ headers=grant('gamma', registry))+ assert response.status_code == 200, response.text+ assert response.json()['name'] == 'delta'+ assert not (home / 'profiles' / 'gamma').exists()+ assert (home / 'profiles' / 'delta' / 'config.yaml').is_file()+ ready()+ response = client.delete('/api/profiles/beta', headers=grant('beta', registry))+ assert response.status_code == 200, response.text+ assert not (home / 'profiles' / 'beta').exists()+ # Single use: the same ticket never authorizes a second write.+ once = grant('keep', registry)+ ready()+ assert client.delete('/api/profiles/keep', headers=once).status_code == 200+ assert client.patch('/api/profiles/delta', json={'new_name': 'again'},+ headers=once).status_code == 401++ # The launch (default) home never moves: rename is its presentation-only display name.+ served = ready()+ assert home_of('default') in {p['profile_id'] for p in served['served_profiles']}+ response = client.patch('/api/profiles/default', json={'new_name': 'Main'},+ headers=grant('default', registry))+ assert response.status_code == 200, response.text+ assert (response.json()['name'], response.json()['display_name']) == ('default', 'Main')+ response = client.delete('/api/profiles/default', headers=grant('default', registry))+ assert response.status_code == 403, response.text+ assert (home / 'config.yaml').is_file()+ # The surviving profile still answers its ordinary grant (the gateway kept serving).+ ready()+ assert client.get('/api/profiles/delta/soul',+ headers=grant('delta', 'native-http')).status_code == 200+ 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)