The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): one entitlement rule for clarify.lock and the closing response frame
Tekniumb94cb635cd8d
diff --git a/gateway/session_clarify_lock.py b/gateway/session_clarify_lock.pyindex a9891acca3a..8725234c6e3 100644--- a/gateway/session_clarify_lock.py+++ b/gateway/session_clarify_lock.py@@ -9,12 +9,11 @@ attached to the request's session with ``session:respond`` may lock its answers."""import json-from gateway.session_contract import SessionReffrom hermes_state_runtime import RuntimeStoreErrorasync def clarify_lock(connection, ref, params):- from gateway.session_sudo_prompt import lock_answer, owned_by+ from gateway.session_sudo_prompt import lock_answer, may_settle# The dispatcher already refused unknown keys and mistyped fields against the declared# ``ClarifyLockParams`` (``tui_gateway/contracts/canonical.py``); a missing or empty id is ours to refuse.# ``profile`` naming another served profile was routed to its owner by ``dispatch``.@@ -27,16 +26,8 @@ async def clarify_lock(connection, ref, params):authority, actor = connection.authority, connection.actordef entitled(session_id, events):- # The request must have been sent on THIS authority's live session (session ids repeat across- # profiles; the pending table is process-wide), then the caller needs respond + a subscription.- if not owned_by(authority, session_id, events):- return False- try:- authority.authorize(actor, SessionRef(authority.profile_id, session_id), 'session:respond')- except RuntimeStoreError:- return False- live = authority.sessions.get(session_id)- return live is not None and actor in live.subscribers.values()+ # The same rule the closing response frame for this request id goes through.+ return may_settle(authority, actor, session_id, events)try:remaining = lock_answer(request_id, question_id, answer, session_ok=entitled)except ValueError:diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex aaf671d56ca..d079a7347fd 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -694,16 +694,11 @@ class AuthorityConnection:return asdict(await self.authority.interrupt(self.actor, ref, params.get('execution_generation')))def _resolve_response(self, frame):- from gateway.session_sudo_prompt import owned_by, resolve+ from gateway.session_sudo_prompt import may_settle, resolvedef entitled(session_id, events):- if not owned_by(self.authority, session_id, events):- return False # another profile's (or another mount's) request with the same session id- try:- self.authority.authorize(self.actor, SessionRef(self.actor.profile_id, session_id), 'session:respond')- except RuntimeStoreError:- return False- return True+ # The same rule ``clarify.lock`` applies to the same request id (attached + respond).+ return may_settle(self.authority, self.actor, session_id, events)if not resolve(frame, session_ok=entitled):import logginglogging.getLogger(__name__).debug('dropping response for unknown server request id=%r', frame.get('id'))diff --git a/gateway/session_sudo_prompt.py b/gateway/session_sudo_prompt.pyindex f76a888c382..4596f3669bf 100644--- a/gateway/session_sudo_prompt.py+++ b/gateway/session_sudo_prompt.py@@ -48,6 +48,23 @@ def owned_by(authority, session_id, events) -> bool:return live is not None and events is not None and live.event_stream is events+def may_settle(authority, actor, session_id, events) -> bool:+ """The one rule for who may settle an owner request (a response frame or ``clarify.lock``): the+ request went out on *authority*'s own live stream for that session (session ids repeat across+ profiles and ``_open`` is process-wide), *actor* holds ``session:respond`` there, and *actor* is+ attached to that session, the same set of connections the request frame was written to."""+ from gateway.session_contract import SessionRef+ from hermes_state_runtime import RuntimeStoreError+ if not owned_by(authority, session_id, events):+ return False+ try:+ authority.authorize(actor, SessionRef(authority.profile_id, session_id), "session:respond")+ except RuntimeStoreError:+ return False+ live = authority.sessions.get(session_id)+ return live is not None and actor in live.subscribers.values()++def is_response_frame(frame) -> bool:"""A viewer's answer to one of the owner's requests: a string ``srq-`` id, a result/error, no method."""return (isinstance(frame, dict) and "method" not in frame and isinstance(frame.get("id"), str)diff --git a/tests/gateway/test_clarify_lock_owner.py b/tests/gateway/test_clarify_lock_owner.pyindex b8695ae7c34..8a561659037 100644--- a/tests/gateway/test_clarify_lock_owner.py+++ b/tests/gateway/test_clarify_lock_owner.py@@ -195,3 +195,32 @@ async def test_clarify_lock_params_are_checked_by_the_declared_canonical_contracassert late['result'] == {'status': 'expired'}, latefinally:await connection.close()+++async def test_an_unattached_connection_cannot_settle_the_batch_with_a_raw_response_frame(tmp_path, monkeypatch):+ """``clarify.lock`` and the closing response frame are two ways to settle the same request id: both go+ through one entitlement rule (``session_sudo_prompt.may_settle``), so a same-profile connection that+ never attached the session can no more close the batch with a frame than lock one of its answers."""+ from gateway.session_controls import AuthorityConnection++ async def answer(event):+ return 'ok'+ authority = await _authority(tmp_path, monkeypatch, answer)+ owner = AuthorityConnection(authority, object(), {'user_id': 'owner'})+ outsider = AuthorityConnection(authority, object(), {'user_id': 'owner'}) # same actor, never attached+ try:+ await owner.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}})+ peer, worker, out = _start_batch(authority)+ await _wait_for(lambda: any(f.get('method') == 'clarify' for f in peer.frames))+ rid = next(f['id'] for f in peer.frames if f.get('method') == 'clarify')+ from gateway.session_sudo_prompt import _open+ # ``dispatch`` settles a response frame synchronously: still open afterwards means refused.+ await outsider.dispatch({'jsonrpc': '2.0', 'id': rid, 'result': {'answers': {'q0': 'X', 'q1': 'X'}}})+ assert rid in _open and not _open[rid].event.is_set() and out == {}, out+ await owner.dispatch({'jsonrpc': '2.0', 'id': rid, 'result': {'answers': {'q0': 'red', 'q1': 'big'}}})+ await asyncio.to_thread(worker.join, 5)+ assert out == {'answers': {'q0': 'red', 'q1': 'big'}, 'outcome': 'submitted'}, out+ finally:+ await outsider.close()+ await owner.close()diff --git a/tests/gateway/test_local_viewer_sudo_prompt.py b/tests/gateway/test_local_viewer_sudo_prompt.pyindex 8caf3660394..b4e79e857d6 100644--- a/tests/gateway/test_local_viewer_sudo_prompt.py+++ b/tests/gateway/test_local_viewer_sudo_prompt.py@@ -100,6 +100,8 @@ async def test_the_viewer_response_frame_is_routed_by_the_authority_connection(treturn 'ok'authority = await _authority(tmp_path, monkeypatch, answer)connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})+ # Only a viewer attached to the session gets the request frame, and only it may answer.+ await connection.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}})pending = session_sudo_prompt._Pending('s', events=authority.sessions['s'].event_stream)session_sudo_prompt._open['srq-abc'] = pendingtry: