Skip to content

The agent that grows with you

fix: reject approval publication from retired gateway workers

Teknium295bc0f57d9c
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 526e5bdc856..601e3f441b3 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -334,12 +334,13 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
return response
def _approval_notify_sync(self, approval_data: dict) -> None:
+ if self._approval_owner is not None:
+ authority, session_id, generation = self._approval_owner
+ authority.check_approval_generation(session_id, generation)
# A native decline must finish before any observer can authorize work.
self._render_approval_sync(approval_data)
if self._approval_owner is not None:
- authority, session_id, generation = self._approval_owner
- live = authority.sessions[session_id]
- live.controls.register(session_id, self._ctx.session_key, generation, approval_data)
+ authority.register_approval(session_id, generation, self._ctx.session_key, approval_data)
def _render_approval_sync(self, approval_data: dict) -> None:
"""Send the approval request from the agent thread: the adapter's interactive button
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 8f112b81e1c..559d091d4c6 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -201,6 +201,17 @@ class SessionAuthority:
agent.interrupt()
return self._handle(ref)
+ def check_approval_generation(self, session_id, generation):
+ handle = self._handle(SessionRef(self.profile_id, session_id))
+ if handle.execution_generation != generation or handle.execution_state != "running":
+ raise RuntimeStoreError("stale_generation")
+
+ def register_approval(self, session_id, generation, route, data):
+ live = self.sessions[session_id]
+ with live.event_stream.lock:
+ self.check_approval_generation(session_id, generation)
+ live.controls.register(session_id, route, generation, data)
+
async def respond(self, actor, ref, generation, prompt_id, response):
self.authorize(actor, ref, "session:approve")
live = self.sessions[ref.session_id]
diff --git a/tests/gateway/fixtures/control_boundaries.py b/tests/gateway/fixtures/control_boundaries.py
new file mode 100644
index 00000000000..2681dbba195
--- /dev/null
+++ b/tests/gateway/fixtures/control_boundaries.py
@@ -0,0 +1,116 @@
+
+
+import json
+
+
+async def exercise_control_boundaries(tmp_path, monkeypatch):
+ """Real tools waiters and TurnRunner callback, no alternative approval queue."""
+ import asyncio
+ from dataclasses import replace
+ from types import SimpleNamespace
+ from gateway.run_turn_runner import TurnRunner
+ from gateway.session_authority import LiveSession, SessionAuthority
+ from gateway.session_contract import Principal, SessionRef
+ from hermes_state import SessionDB
+ from hermes_state_runtime import (RuntimeStoreError, admit_session_input, begin_runtime_epoch,
+ claim_session_input, settle_session_input)
+ from tools.approval import list_gateway_approvals, resolve_gateway_approval
+ from tools.approval_gateway_wait import _await_gateway_decision
+
+ db = SessionDB(tmp_path / 'controls.db')
+ db.create_session('s', source='telegram')
+ epoch = begin_runtime_epoch(db, instance_id='controls')
+ admit_session_input(db, epoch=epoch, principal_id='owner', session_id='s', request_id='first', payload={'text': 'first'})
+ row = claim_session_input(db, epoch=epoch, session_id='s')
+ authority = SessionAuthority(SimpleNamespace(), profile_id='p', instance_id='controls', db=db, epoch=epoch)
+ live = authority.sessions['s'] = LiveSession(None, 'boundary-route')
+ ref = SessionRef('p', 's')
+ actor = Principal('operator', 'p', frozenset({'session:read', 'session:approve'}), 'a')
+ snap = await authority.attach(actor, ref)
+
+ class NativeCard:
+ mode = 'sent'
+ sends = 0
+ def pause_typing_for_chat(self, chat_id):
+ pass
+ async def send_exec_approval(self, **kwargs):
+ if self.mode == 'declined':
+ return SimpleNamespace(success=False, error='declined')
+ return SimpleNamespace(success=True)
+ async def send(self, *args, **kwargs):
+ self.sends += 1
+ return SimpleNamespace(success=True)
+
+ adapter = NativeCard()
+ ctx = SimpleNamespace(session_id='s', session_key='boundary-route', _status_adapter=adapter,
+ _status_chat_id='chat', _status_thread_metadata=None,
+ _loop_for_step=asyncio.get_running_loop(), stream_consumer_holder=[None])
+ turn = TurnRunner(SimpleNamespace(session_authority=authority), ctx)
+
+ async def wait_prompt():
+ async with asyncio.timeout(5):
+ while True:
+ snapshot = await authority.attach(actor, ref)
+ if snapshot.prompts:
+ return snapshot.prompts[-1]
+ await asyncio.sleep(.01)
+
+ tasks = []
+ try:
+ for n in range(2):
+ task = asyncio.create_task(asyncio.to_thread(_await_gateway_decision, live.route,
+ turn._approval_notify_sync, {'command': f'owned-command-{n}', 'description': 'fixture',
+ 'allow_session': False, 'allow_permanent': False, 'pattern_keys': [str(n)]}))
+ tasks.append(task)
+ async with asyncio.timeout(5):
+ while len((await authority.attach(actor, ref)).prompts) < n + 1:
+ await asyncio.sleep(.01)
+ prompts = (await authority.attach(actor, ref)).prompts
+ import pytest
+ for bad_actor, bad_ref, gen, reason in [
+ (replace(actor, capabilities=frozenset({'session:read'})), ref, row['generation'], 'permission_denied'),
+ (replace(actor, profile_id='foreign'), ref, row['generation'], 'profile_mismatch'),
+ (actor, SessionRef('foreign', 's'), row['generation'], 'profile_mismatch'),
+ (actor, SessionRef('p', 'missing'), row['generation'], 'not_found'),
+ (replace(actor, transport_id='unattached'), ref, row['generation'], 'permission_denied'),
+ (actor, ref, row['generation'] + 1, 'stale_generation'),
+ ]:
+ with pytest.raises(RuntimeStoreError) as exc:
+ await authority.respond(bad_actor, bad_ref, gen, prompts[0]['prompt_id'], {'choice': 'once'})
+ assert exc.value.reason == reason
+ for answer in ({'choice': 'always'}, {'choice': 'session'}, {'answer': 'PRIVATE_SUDO_ANSWER'}, {'choice': []}):
+ with pytest.raises(RuntimeStoreError) as exc:
+ await authority.respond(actor, ref, row['generation'], prompts[0]['prompt_id'], answer)
+ assert exc.value.reason == 'invalid_params'
+ await authority.detach(actor, snap.subscription_id)
+ assert len(list_gateway_approvals(live.route)) == 2
+ await authority.attach(actor, ref)
+ # Resolve second first: no FIFO consumption by a stale/native response.
+ response = await authority.respond(actor, ref, row['generation'], prompts[1]['prompt_id'], {'choice': 'once'})
+ assert response['status'] == 'resolved'
+ assert (await tasks[1])['choice'] == 'once'
+ assert not tasks[0].done()
+ resolve_gateway_approval(live.route, 'deny', request_id=prompts[0]['prompt_id'])
+ assert (await tasks[0])['choice'] == 'deny'
+ assert not (await authority.attach(actor, ref)).prompts
+ replay = live.event_stream.since(live.event_stream.epoch, 0)
+ assert 'PRIVATE_SUDO_ANSWER' not in json.dumps(replay)
+
+ # A delayed old worker callback must not publish a fresh actionable card
+ # after a new generation has claimed the session.
+ settle_session_input(db, epoch=epoch, admission_id=row['admission_id'], generation=row['generation'], outcome='completed')
+ admit_session_input(db, epoch=epoch, principal_id='owner', session_id='s', request_id='next', payload={'text': 'next'})
+ newer = claim_session_input(db, epoch=epoch, session_id='s')
+ from tools import approval_context
+ monkeypatch.setattr(approval_context, "_get_approval_timeout", lambda: 0)
+ before = live.event_stream.watermark()
+ stale = await asyncio.to_thread(_await_gateway_decision, live.route, turn._approval_notify_sync,
+ {'command': 'late-old-worker', 'pattern_keys': ['late']})
+ assert stale.get('notify_failed'), 'retired worker registered a new shared approval'
+ assert live.event_stream.watermark() == before, 'retired worker published an approval event'
+ assert not (await authority.attach(actor, ref)).prompts
+ settle_session_input(db, epoch=epoch, admission_id=newer['admission_id'], generation=newer['generation'], outcome='completed')
+ finally:
+ resolve_gateway_approval(live.route, 'deny', resolve_all=True)
+ await asyncio.gather(*tasks)
+ db.close()
diff --git a/tests/gateway/test_shared_session_controls.py b/tests/gateway/test_shared_session_controls.py
index a9b390f68ec..b8048b21775 100644
--- a/tests/gateway/test_shared_session_controls.py
+++ b/tests/gateway/test_shared_session_controls.py
@@ -19,3 +19,10 @@ def test_shared_approval_outlives_viewer_and_bypasses_fifo(tmp_path):
receipt = json.loads((state / 'receipt.json').read_text())
print(json.dumps(receipt))
assert receipt['real_terminal_effect'] and receipt['fifo_bypassed'] and receipt['detach_kept_pending']
+
+
+def test_control_identity_rejects_foreign_and_retired_workers(tmp_path, monkeypatch):
+ import asyncio
+ import runpy
+ fixture = runpy.run_path(str(Path(__file__).parent / 'fixtures' / 'control_boundaries.py'))
+ asyncio.run(fixture['exercise_control_boundaries'](tmp_path, monkeypatch))