The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: an issued interactive ticket keeps its profile scope across sibling selectors
Teknium1b93988e1b5c
diff --git a/apps/desktop/electron/local-gateway-python.test.ts b/apps/desktop/electron/local-gateway-python.test.tsindex 21a4b098bcc..1d50120f501 100644--- a/apps/desktop/electron/local-gateway-python.test.ts+++ b/apps/desktop/electron/local-gateway-python.test.ts@@ -38,7 +38,8 @@ test.skipIf(process.platform === 'win32')('Python ticket bridge pins profile, owtry {for (const purpose of ['interactive', 'native-http'] as const) {await expect(mintGatewayTicketWithPython(backend, cwd, endpoint, purpose)).resolves.toBe('private-grant')- expect(requests.at(-1).params).toEqual({ profile_id: home, instance_id: 'owner', purpose })+ // Only the interactive (shared-primary) socket asks for host scope; native-http stays profile-bound.+ expect(requests.at(-1).params).toEqual({ profile_id: home, instance_id: 'owner', purpose, ...(purpose === 'interactive' ? { scope: 'host' } : {}) })}for (const invalid of [{ instance_id: 'other' }, { profile_id: '/other' }, { runtime_protocol: 2 }, { ticket: '' }]) {@@ -85,7 +86,7 @@ test.skipIf(process.platform === 'win32')('Python ticket bridge pins profile, owawait new Promise<void>(resolve => server.listen(path.join(mux, 'gateway.sock'), resolve))await fs.chmod(path.join(mux, 'gateway.sock'), 0o600)await expect(mintGatewayTicketWithPython(backend, cwd, { ...endpoint, control_home: mux }, 'interactive')).resolves.toBe('private-grant')- expect(requests.at(-1).params).toEqual({ profile_id: home, instance_id: 'owner', purpose: 'interactive' })+ expect(requests.at(-1).params).toEqual({ profile_id: home, instance_id: 'owner', purpose: 'interactive', scope: 'host' })} finally {closeGatewayTicketBridges()await new Promise<void>(resolve => server.close(() => resolve()))diff --git a/apps/desktop/electron/local-gateway-python.ts b/apps/desktop/electron/local-gateway-python.tsindex 39a9baad08b..4fb94092ae8 100644--- a/apps/desktop/electron/local-gateway-python.ts+++ b/apps/desktop/electron/local-gateway-python.ts@@ -35,7 +35,8 @@ while True:raise ValueError('invalid ticket endpoint')if os.name != 'nt':_private_node(home, kind='directory', home=True)- ticket = _session_ticket(home, endpoint, purpose=request['purpose'])+ ticket = _session_ticket(home, endpoint, purpose=request['purpose'],+ scope='host' if request['purpose'] == 'interactive' else None)reply = {'id': request['id'], 'ticket': ticket}except DiscoveryError as exc:reply = {'id': request['id'], 'error': exc.reason}diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.tsindex eea8dbfc5cf..c6f679de1ef 100644--- a/apps/desktop/electron/local-gateway.test.ts+++ b/apps/desktop/electron/local-gateway.test.ts@@ -87,6 +87,10 @@ test.skipIf(process.platform === 'win32').each([0o700, 0o750, 0o701])('native HTexpect(requests.map(r => r.params)).toEqual([1, 2].map(() => ({ profile_id: home, instance_id: 'owner', purpose: 'native-http' })))await expect(nativeGatewayHttpHeaders(descriptor, 'http://127.0.0.1:4567/api/config')).rejects.toThrow('origin')expect(requests).toHaveLength(2)+ // The shared-primary WS socket alone asks for a host-scoped grant (sibling `profile` routing).+ const { mintLocalGatewayTicket } = await import('./local-gateway')+ await mintLocalGatewayTicket(endpoint)+ expect(requests.at(-1).params).toEqual({ profile_id: home, instance_id: 'owner', purpose: 'interactive', scope: 'host' })} finally {await new Promise<void>(resolve => server.close(() => resolve()))await fs.rm(home, { recursive: true, force: true })diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.tsindex c34c9a8511c..dc88f563e9e 100644--- a/apps/desktop/electron/local-gateway.ts+++ b/apps/desktop/electron/local-gateway.ts@@ -379,6 +379,13 @@ async function resolveControlSocket(home: string): Promise<string> {return socketPath}+/** 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'): { scope?: 'host' } {+ return purpose === 'interactive' ? { scope: 'host' } : {}+}+export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http' = 'interactive'): Promise<string> {if (process.platform === 'win32') {if (!pythonTicketClient) {throw new Error('Gateway ticket client is not configured')}@@ -417,7 +424,7 @@ export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint, purpose:const deadline = setTimeout(() => socket.destroy(new Error('Gateway ticket deadline')), 5000)socket.on('error', () => reject(new Error('Gateway ticket bootstrap failed')))socket.on('close', () => { clearTimeout(deadline); reject(new Error('Gateway ticket connection closed')) })- socket.on('connect', () => socket.write(JSON.stringify({ protocol: 1, id: 1, verb: 'session-ticket', params: { profile_id: home, instance_id: endpoint.instance_id, purpose } }) + '\n'))+ socket.on('connect', () => socket.write(JSON.stringify({ protocol: 1, id: 1, verb: 'session-ticket', params: { profile_id: home, instance_id: endpoint.instance_id, purpose, ...ticketScope(purpose) } }) + '\n'))socket.on('data', chunk => {buffer += chunk.toString()diff --git a/gateway/control_socket.py b/gateway/control_socket.pyindex ae29fdf2365..8a8bc4720c3 100644--- a/gateway/control_socket.py+++ b/gateway/control_socket.py@@ -314,12 +314,13 @@ class GatewayControlServer:if set(request) - {"protocol", "verb", "id", "params"} or request.get("protocol") != 1:raise PermissionError("invalid bootstrap envelope")params = request.get("params")- if not isinstance(params, dict) or set(params) != {"profile_id", "instance_id", "purpose"}:+ if (not isinstance(params, dict) or not {"profile_id", "instance_id", "purpose"} <= set(params)+ or set(params) - {"profile_id", "instance_id", "purpose", "scope"}):raise PermissionError("invalid bootstrap parameters")if params["instance_id"] != self.ticket_store.instance_id:raise PermissionError("stale runtime instance")- ticket = self.ticket_store.mint(profile_id=params["profile_id"],- subject=peer_subject, purpose=params["purpose"])+ ticket = self.ticket_store.mint(profile_id=params["profile_id"], subject=peer_subject,+ purpose=params["purpose"], scope=params.get("scope", "profile"))return {"ticket": ticket, "expires_in_seconds": 30,"instance_id": self.ticket_store.instance_id,"profile_id": params["profile_id"], "runtime_protocol": 1}diff --git a/gateway/run_api.py b/gateway/run_api.pyindex 84860baa4ac..1049044b43b 100644--- a/gateway/run_api.py+++ b/gateway/run_api.py@@ -185,5 +185,6 @@ class GatewayRuntimeAPI:await handle_ws(ws, auth_identity={'user_id': grant['subject'], 'provider': 'local','profile_id': grant['profile_id'],'instance_id': grant['instance_id'],- 'capabilities': grant['capabilities'], 'native_bootstrap': True},+ 'capabilities': grant['capabilities'], 'native_bootstrap': True,+ 'profile_scope': grant.get('scope', 'profile')},subprotocol=CANONICAL_GATEWAY_PROTOCOL, operator=operator)diff --git a/gateway/runtime_bootstrap.py b/gateway/runtime_bootstrap.pyindex c929c2ae50a..76e55154708 100644--- a/gateway/runtime_bootstrap.py+++ b/gateway/runtime_bootstrap.py@@ -13,6 +13,8 @@ _PURPOSE_CAPABILITIES = {'exposure': frozenset({'transport:delegate'}),'worker-adoption': frozenset({'worker:adopt'}),}+# A grant's profile reach: its own home, or (interactive only) every served sibling.+_SCOPES = frozenset({'profile', 'host'})class TicketStore:@@ -27,8 +29,11 @@ class TicketStore:self._entries: dict[str, tuple[float, dict]] = {}self._lock = threading.Lock()- def mint(self, *, profile_id, subject, purpose) -> str:- if profile_id not in self.profile_ids or purpose not in _PURPOSE_CAPABILITIES or not subject:+ def mint(self, *, profile_id, subject, purpose, scope='profile') -> str:+ """``scope='host'`` lets an interactive connection select every profile this process+ serves (the Desktop's one shared socket); the default binds exactly ``profile_id``."""+ if (profile_id not in self.profile_ids or purpose not in _PURPOSE_CAPABILITIES or not subject+ or scope not in _SCOPES or (scope == 'host' and purpose != 'interactive')):raise PermissionError('bootstrap binding rejected')with self._lock:now = time.monotonic()@@ -39,7 +44,7 @@ class TicketStore:self._entries[hashlib.sha256(ticket.encode()).hexdigest()] = (now + self.TTL_SECONDS,{'instance_id': self.instance_id, 'profile_id': profile_id, 'subject': subject,- 'purpose': purpose, 'capabilities': _PURPOSE_CAPABILITIES[purpose]})+ 'purpose': purpose, 'capabilities': _PURPOSE_CAPABILITIES[purpose], 'scope': scope})return ticketdef redeem(self, ticket, *, profile_id, purpose) -> dict:diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex be2c5fdfb6c..f70c2d15720 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -46,11 +46,14 @@ class AuthorityConnection:def _sibling_for(self, profile):"""Connection bound to the sibling authority a ``profile`` param names, or None for our own- home. One native socket serves every profile this process multiplexes (the Desktop's- shared-primary route); a profile nobody here serves is a mismatch, never a fallback."""+ home. Only a host-scoped grant (the Desktop's shared-primary socket, the dashboard gate)+ reaches a sibling; a profile-bound ticket naming any other profile is a mismatch, exactly+ like a profile nobody here serves. Never a fallback, never a rewritten profile_id."""from hermes_cli.profiles import profile_matches_homeif profile_matches_home(profile, Path(self.authority.profile_id)):return None+ if self._identity.get('profile_scope') != 'host':+ raise RuntimeStoreError('profile_mismatch')registry = getattr(getattr(self.authority, 'runner', None), 'session_authorities', None)for sibling in (registry or ()):if sibling is not self.authority and profile_matches_home(profile, Path(sibling.profile_id)):diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.pyindex 5cb097bb47a..d72c8782ad4 100644--- a/hermes_cli/gateway_client.py+++ b/hermes_cli/gateway_client.py@@ -99,13 +99,14 @@ class GatewayClient:self.pending.pop(rid, None)-def _session_ticket(home: Path, endpoint, *, purpose="interactive") -> str:+def _session_ticket(home: Path, endpoint, *, purpose="interactive", scope=None) -> str:from hermes_cli.gateway_runtime import control_home_forfrom hermes_cli.gateway_runtime_discovery import connect_private, _identify_response# A served secondary's ticket is minted by the multiplexer's socket, bound to the secondary.home = control_home_for(home, endpoint)request = json.dumps({"protocol": 1, "id": 1, "verb": "session-ticket", "params": {"profile_id": endpoint.profile_id, "instance_id": endpoint.instance_id, "purpose": purpose,+ **({"scope": scope} if scope else {}),}}).encode() + b"\n"if os.name == "nt":from gateway.runtime_bootstrap_windows import query_runtime_controldiff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.pyindex 5f0e6facf0f..8f80f43dfdf 100644--- a/hermes_cli/web_routers/chat_ws.py+++ b/hermes_cli/web_routers/chat_ws.py@@ -722,6 +722,10 @@ async def gateway_ws(ws: WebSocket) -> None:'profile_id': authority.profile_id, 'instance_id': authority.instance_id,'capabilities': ['session:create', 'session:read', 'session:submit','session:control', 'session:approve', 'session:respond']}+ if identity is not None:+ # The dashboard gate authorizes the whole host (its REST routes take ``?profile=`` for+ # every profile), so its socket may select any served sibling too.+ identity = {**identity, 'profile_scope': 'host'}await handle_ws(ws,auth_identity=identity,diff --git a/tests/gateway/test_ticket_profile_scope.py b/tests/gateway/test_ticket_profile_scope.pynew file mode 100644index 00000000000..01de16bd74c--- /dev/null+++ b/tests/gateway/test_ticket_profile_scope.py@@ -0,0 +1,85 @@+"""An issued interactive ticket keeps its profile scope across sibling selectors (#106742 W1)."""+import json+from pathlib import Path++import pytest++from tests.gateway.test_session_authorities_multiplex import _reserve_homes, _runner+++class _Transport:+ def write(self, frame):+ return True++ def close(self):+ pass+++async def test_profile_bound_ticket_never_reaches_a_sibling_authority(tmp_path, monkeypatch):+ from gateway.config import Platform+ from gateway.run_runtime import initialize_gateway_runtime+ from gateway.runtime_ownership import process_ownership+ from gateway.session import SessionSource+ from gateway.session_authorities import authority_for_profile_id, owner_scope+ from gateway.session_authority import LiveSession+ from gateway.session_controls import AuthorityConnection+ root, homes = _reserve_homes(tmp_path, monkeypatch)+ process_ownership.reserve([home for _, home in homes])+ connections, runner = [], None+ try:+ runner = _runner(root, homes)+ await initialize_gateway_runtime(runner)+ store = runner.session_ticket_store+ alpha_id, beta_id = (str(home.resolve()) for _, home in homes[1:])+ beta = authority_for_profile_id(runner, beta_id)+ beta.db.create_session('beta-private', source='api_server')+ beta.db.append_message('beta-private', 'user', 'PRIVATE_BETA_MARKER')+ beta.sessions['beta-private'] = LiveSession(+ SessionSource(platform=Platform.LOCAL, chat_id='local-x', user_id='uid:other'), 'route')++ def connect(profile_id, **scope):+ # Exactly gateway/run_api.py's redeem → identity → operator connection binding.+ ticket = store.mint(profile_id=profile_id, subject='uid:attacker', purpose='interactive', **scope)+ grant = store.redeem(ticket, profile_id=None, purpose='interactive')+ authority = authority_for_profile_id(runner, grant['profile_id'])+ identity = {'user_id': grant['subject'], 'provider': 'local', 'profile_id': grant['profile_id'],+ 'instance_id': grant['instance_id'], 'capabilities': grant['capabilities'],+ 'native_bootstrap': True, 'profile_scope': grant.get('scope', 'profile')}+ with owner_scope(authority):+ connection = AuthorityConnection(authority, _Transport(), identity, operator=True)+ connections.append(connection)+ return connection++ async def call(connection, method, **params):+ with owner_scope(connection.authority):+ return await connection.dispatch({'id': 1, 'method': method, 'params': params})++ alpha, root_ticket = connect(alpha_id), connect(str(root.resolve()))+ for connection in (alpha, root_ticket):+ for method, params in (('session.list', {}), ('session.resume', {'session_id': 'beta-private'}),+ ('prompt.submit', {'session_id': 'beta-private', 'submission_id': 'x', 'text': 't'}),+ ('session.interrupt', {'session_id': 'beta-private'}),+ ('session.mutate', {'session_id': 'beta-private'}), ('session.create', {})):+ reply = await call(connection, method, profile='beta', **params)+ assert reply.get('error', {}).get('message') == 'profile_mismatch', (method, reply)+ assert 'PRIVATE_BETA_MARKER' not in json.dumps(reply)+ assert (await call(connection, 'session.list', profile='gamma'))['error']['message'] == 'profile_mismatch'+ assert 'result' in await call(alpha, 'session.list')+ assert 'result' in await call(alpha, 'session.list', profile='alpha') # own-profile selector+ assert (await call(alpha, 'session.list', profile='default'))['error']['message'] == 'profile_mismatch'+ # The Desktop's shared-primary socket asks for a host-scoped grant and keeps its sibling route.+ host = connect(str(root.resolve()), scope='host')+ listed = await call(host, 'session.list', profile='beta')+ assert [row['session_id'] for row in listed['result']['sessions']] == ['beta-private'], listed+ assert (await call(host, 'session.list', profile='gamma'))['error']['message'] == 'profile_mismatch'+ with pytest.raises(PermissionError):+ store.mint(profile_id=alpha_id, subject='uid:1', purpose='native-http', scope='host')+ finally:+ for connection in connections:+ with owner_scope(connection.authority):+ await connection.close()+ for authority in list(getattr(runner, 'session_authorities', []) or []):+ authority.db.close()+ for _, home in homes:+ process_ownership.release(Path(home))