Skip to content

The agent that grows with you

fix(gateway): scope owner-side prompts to the authority that sent them

Teknium3aeda8a33051
diff --git a/gateway/session_clarify_lock.py b/gateway/session_clarify_lock.py
index aaab65c0d21..e1d9a99697d 100644
--- a/gateway/session_clarify_lock.py
+++ b/gateway/session_clarify_lock.py
@@ -16,7 +16,7 @@ _FIELDS = frozenset({'request_id', 'question_id', 'answer', 'profile'})
async def clarify_lock(connection, ref, params):
- from gateway.session_sudo_prompt import lock_answer
+ from gateway.session_sudo_prompt import lock_answer, owned_by
request_id, question_id = params.get('request_id'), params.get('question_id')
# ``profile`` naming another served profile was routed to its owner by ``dispatch``.
if (set(params) - _FIELDS or not isinstance(request_id, str) or not request_id
@@ -28,7 +28,11 @@ async def clarify_lock(connection, ref, params):
answer = json.dumps(answer, ensure_ascii=False)
authority, actor = connection.authority, connection.actor
- def entitled(session_id):
+ def 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:
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 6b2f3ef7054..aaf671d56ca 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -694,9 +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 resolve
+ from gateway.session_sudo_prompt import owned_by, resolve
- def entitled(session_id):
+ def 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:
diff --git a/gateway/session_sudo_prompt.py b/gateway/session_sudo_prompt.py
index 304458932ad..c927ed062c7 100644
--- a/gateway/session_sudo_prompt.py
+++ b/gateway/session_sudo_prompt.py
@@ -22,11 +22,14 @@ _POLL_S = 0.25
class _Pending:
- __slots__ = ("event", "locked", "qids", "result", "session_id", "value")
+ __slots__ = ("event", "events", "locked", "qids", "result", "session_id", "value")
- def __init__(self, session_id, qids=None):
+ def __init__(self, session_id, qids=None, events=None):
self.event = threading.Event()
self.session_id = session_id
+ # The live session's own event stream the request went out on: one per authority (profile) and
+ # session mount, so a viewer of another profile's same-named session can never settle it.
+ self.events = events
self.value = ""
self.result = None
# A batch clarify: its question ids and the answers ``clarify.lock`` has locked so far.
@@ -39,6 +42,12 @@ _open: dict[str, _Pending] = {}
_OUTCOMES = ("submitted", "timed_out", "cancelled")
+def owned_by(authority, session_id, events) -> bool:
+ """True when *authority*'s live *session_id* is the very stream a request was sent on."""
+ live = authority.sessions.get(session_id)
+ return live is not None and events is not None and live.event_stream is events
+
+
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)
@@ -59,12 +68,14 @@ def _settle_batch(locked, result):
return {"answers": locked, "outcome": outcome if outcome in ("timed_out", "cancelled") else "cancelled"}
-def resolve(frame, *, session_ok=lambda session_id: True) -> bool:
+def resolve(frame, *, session_ok=lambda session_id, events: True) -> bool:
"""Settle the open request *frame* answers; False when nothing (here) waits for that id.
- ``session_ok`` lets the caller refuse an answer from a connection not entitled to that session."""
+ ``session_ok(session_id, events)`` lets the caller refuse an answer from a connection not entitled
+ to that session: the caller's own authority must own ``events``, the stream the request was sent on
+ (session ids are only unique per profile, and ``_open`` is process-wide)."""
with _lock:
pending = _open.get(frame["id"])
- if pending is None or not session_ok(pending.session_id):
+ if pending is None or not session_ok(pending.session_id, pending.events):
return False
_open.pop(frame["id"], None)
locked = dict(pending.locked) if pending.qids is not None else None
@@ -101,14 +112,15 @@ def ask_viewer_result(events, session_id, method, params, *, cancelled=lambda: F
return pending.result if pending is not None else None
-def lock_answer(request_id, question_id, answer, *, session_ok=lambda session_id: False):
+def lock_answer(request_id, question_id, answer, *, session_ok=lambda session_id, events: False):
"""Lock one answer of an open batch request (``clarify.lock``; editable until the last lock;
``None`` = skipped). Returns the question ids still unanswered; the lock that empties it settles
the request with ``{answers, outcome: submitted}``. ``None`` when no open batch has that id or the
- caller may not answer its session (expired or foreign); ``ValueError`` for an unknown question id."""
+ caller may not answer its session (expired, or another profile's / session's request: see
+ :func:`resolve`); ``ValueError`` for an unknown question id."""
with _lock:
pending = _open.get(request_id)
- if pending is None or pending.qids is None or not session_ok(pending.session_id):
+ if pending is None or pending.qids is None or not session_ok(pending.session_id, pending.events):
return None
if question_id not in pending.qids:
raise ValueError(question_id)
@@ -126,7 +138,7 @@ def _ask(events, session_id, method, params, *, cancelled, timeout, qids=None):
if not events.fanout.transports():
return None
request_id = f"srq-{uuid.uuid4().hex[:12]}"
- pending = _Pending(session_id, qids)
+ pending = _Pending(session_id, qids, events)
with _lock:
_open[request_id] = pending
events.fanout.write({"jsonrpc": "2.0", "id": request_id, "method": method,
diff --git a/tests/gateway/test_clarify_lock_owner.py b/tests/gateway/test_clarify_lock_owner.py
index d915bff1fcd..639e2e27702 100644
--- a/tests/gateway/test_clarify_lock_owner.py
+++ b/tests/gateway/test_clarify_lock_owner.py
@@ -124,3 +124,39 @@ def test_cli_turn_batch_answered_by_clarify_lock_from_a_second_viewer_end_to_end
cwd=tmp_path, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=90, check=False)
assert result.returncode == 0, result.stdout + result.stderr
assert (state / 'lock-passed').read_text() == 'both locked answers reached the real model'
+
+
+async def test_another_profiles_viewer_of_the_same_session_id_cannot_answer(tmp_path, monkeypatch):
+ """The pending-request table is process-wide and session ids are only unique per profile. Two real
+ authorities (separate homes and SQLite stores) both mount ``s``: profile B's own, attached viewer
+ with ``session:respond`` must not lock or answer profile A's request, through ``clarify.lock`` or a
+ raw response frame."""
+ from gateway.session_controls import AuthorityConnection
+ from gateway.session_sudo_prompt import _open
+
+ async def answer(event):
+ return 'ok'
+ a = await _authority(tmp_path / 'a', monkeypatch, answer)
+ b = await _authority(tmp_path / 'b', monkeypatch, answer)
+ b.profile_id = str(tmp_path / 'b')
+ own = AuthorityConnection(a, object(), {'user_id': 'owner'})
+ foreign = AuthorityConnection(b, object(), {'user_id': 'owner'})
+ try:
+ for connection in (own, foreign):
+ resumed = await connection.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}})
+ assert 'result' in resumed, resumed
+ peer, worker, out = _start_batch(a)
+ 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')
+ refused = await _lock(foreign, rid, 'q0', 'FROM_PROFILE_B', 2)
+ assert refused.get('result') == {'status': 'expired'}, refused
+ foreign._resolve_response({'jsonrpc': '2.0', 'id': rid, 'result': {'answers': {'q0': 'B', 'q1': 'B'}}})
+ assert rid in _open and not _open[rid].locked
+ assert (await _lock(own, rid, 'q0', 'red', 3))['result'] == {'status': 'ok', 'remaining': ['q1']}
+ assert (await _lock(own, rid, 'q1', 'big', 4))['result'] == {'status': 'ok', 'remaining': []}
+ await asyncio.to_thread(worker.join, 5)
+ assert out == {'answers': {'q0': 'red', 'q1': 'big'}, 'outcome': 'submitted'}
+ finally:
+ await own.close()
+ await foreign.close()
diff --git a/tests/gateway/test_local_viewer_sudo_prompt.py b/tests/gateway/test_local_viewer_sudo_prompt.py
index 75cb337d377..8caf3660394 100644
--- a/tests/gateway/test_local_viewer_sudo_prompt.py
+++ b/tests/gateway/test_local_viewer_sudo_prompt.py
@@ -100,7 +100,7 @@ async def test_the_viewer_response_frame_is_routed_by_the_authority_connection(t
return 'ok'
authority = await _authority(tmp_path, monkeypatch, answer)
connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})
- pending = session_sudo_prompt._Pending('s')
+ pending = session_sudo_prompt._Pending('s', events=authority.sessions['s'].event_stream)
session_sudo_prompt._open['srq-abc'] = pending
try:
reply = await connection.dispatch({'jsonrpc': '2.0', 'id': 'srq-abc', 'result': {'value': 'pw'}})