The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: owner verifies managed worker identity through interpreter trampolines
Tekniume8fbefb21e37
diff --git a/agent/managed_worker.py b/agent/managed_worker.pyindex afe90007e96..8c1ca7aabf0 100644--- a/agent/managed_worker.py+++ b/agent/managed_worker.py@@ -210,10 +210,20 @@ def execute(frame, channel):store.close()+def hello():+ """Identity the owner verifies before it reserves: this interpreter's pid and birth plus+ the ancestor chain it observes. Launchers (uv's venv python.exe) put the owner's Popen+ handle one or two hops above; the owner, never this process, decides whether they match."""+ import psutil+ me = psutil.Process()+ return {'pid': me.pid, 'birth': me.create_time(), 'ancestors': [p.pid for p in me.parents()[:3]]}++def main():channel = WorkerChannel(os.fdopen(os.dup(sys.stdout.fileno()), 'wb', buffering=0)) # windows-footgun: ok — binary framesos.dup2(sys.stderr.fileno(), sys.stdout.fileno())try:+ channel.send('hello', **hello())frame = validate_bootstrap(read_frame(sys.stdin.buffer))execute(frame, channel)except Exception:diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.pyindex 87264f549a4..130a7886eae 100644--- a/gateway/session_managed_worker.py+++ b/gateway/session_managed_worker.py@@ -55,6 +55,8 @@ def _bootstrap(authority, ref, row, policy, scope):class ManagedWorker:def __init__(self, process):self.process = process+ # Verified interpreter behind the handle (a launcher trampoline may sit between).+ self.worker = Noneself.write_lock = threading.Lock()self.commands = queue.Queue(maxsize=16)self.closed = threading.Event()@@ -87,15 +89,32 @@ class ManagedWorker:self.process.stdin.write(encode_frame(frame))self.process.stdin.flush()+ def _signal_worker(self, kill):+ """Signal the verified interpreter, not only the handle: a launcher that exec-chained+ or exited leaves the real worker outside the Popen's reach."""+ import psutil+ if self.worker is None or self.worker[0] == self.process.pid:+ return+ try:+ proc = psutil.Process(self.worker[0])+ if proc.create_time() == self.worker[1]:+ (proc.kill if kill else proc.terminate)()+ except psutil.Error:+ pass+def close(self):self.closed.set()if self.process.poll() is None:+ self._signal_worker(kill=False)self.process.terminate()try:self.process.wait(timeout=5)except subprocess.TimeoutExpired:+ self._signal_worker(kill=True)self.process.kill()self.process.wait(timeout=5)+ else:+ self._signal_worker(kill=True)if self.writer.ident is not None:self.writer.join(timeout=5)self.process.stdin.close()@@ -165,8 +184,12 @@ async def execute_managed(authority, ref, row, policy):accepted = Nonescope = Nonetry:+ # The interpreter behind the handle introduces itself first; the owner verifies that+ # identity (alive, same birth, descends from the handle) before reserving for it.+ hello = await asyncio.to_thread(read_frame, process.stdout)scope = reserve_admission_worker(authority, admission_id=row['admission_id'],- process=process, principal_id=row['principal_id'])+ process=process, principal_id=row['principal_id'], hello=hello)+ worker.worker = (scope['pid'], scope['birth'])# The child reads nothing else until the exact reservation has committed.await asyncio.to_thread(worker.send, _bootstrap(authority, ref, row, policy, scope))worker.writer.start()@@ -177,7 +200,7 @@ async def execute_managed(authority, ref, row, policy):if _prompt_frame(authority, ref, row, worker, frame):continuekind = frame.get('type')- if kind == 'ready' and set(frame) == {'type', 'pid'} and frame['pid'] == process.pid:+ if kind == 'ready' and set(frame) == {'type', 'pid'} and frame['pid'] == scope['pid']:continueif kind == 'delta' and set(frame) == {'type', 'text'} and isinstance(frame['text'], str):authority.publish_execution(ref.session_id, row['generation'], 'message.delta', {'text': frame['text']})diff --git a/gateway/session_worker_reservation.py b/gateway/session_worker_reservation.pyindex c5587c50134..1c6606a4129 100644--- a/gateway/session_worker_reservation.py+++ b/gateway/session_worker_reservation.py@@ -10,25 +10,54 @@ import subprocessfrom gateway.session_admission import admission_fingerprintfrom hermes_state_runtime import RuntimeStoreError, _admission, _epoch, _secret_digest, _session+# A venv launcher (uv's Windows python.exe, pip's exe shim) sits between the owner's+# handle and the interpreter; the real worker is never further away than this.+MAX_LAUNCHER_HOPS = 3-def reserve_admission_worker(authority, *, admission_id, process, principal_id):- """Return a private bootstrap scope; never accept caller-selected kind/target.- Only the owner process may reserve its live direct exec child. The admission- supplies physical session and generation; its durable principal must match- the producer. Do not publish the returned secret on any client event stream.+def verify_worker_identity(process, hello):+ """Return the verified ``(pid, birth)`` of the interpreter behind ``process``.++ ``Popen.pid`` may be a launcher trampoline, so the worker reports its own pid and+ birth in a ``hello`` frame; the OWNER proves that pid is alive, carries that birth,+ and descends from (or is) the reserved handle. The worker never decides equality."""import psutil- authority._require_admission_open()if not isinstance(process, subprocess.Popen) or process.poll() is not None:raise RuntimeStoreError('worker_not_live')+ if (not isinstance(hello, dict) or hello.get('type') != 'hello' or type(hello.get('pid')) is not int+ or type(hello.get('birth')) not in (int, float) or not isinstance(hello.get('ancestors'), list)+ or any(type(p) is not int for p in hello['ancestors'])):+ raise RuntimeStoreError('invalid_worker_frame')+ pid = hello['pid']+ if pid <= 0 or pid == os.getpid():+ raise RuntimeStoreError('permission_denied')try:- child = psutil.Process(process.pid)- if child.ppid() != os.getpid() or child.status() == psutil.STATUS_ZOMBIE:+ handle = psutil.Process(process.pid)+ if handle.ppid() != os.getpid() or handle.status() == psutil.STATUS_ZOMBIE:raise RuntimeStoreError('permission_denied')- birth = child.create_time()+ worker = psutil.Process(pid)+ birth = worker.create_time()+ if birth != hello['birth'] or not worker.is_running() or worker.status() == psutil.STATUS_ZOMBIE:+ raise RuntimeStoreError('permission_denied')+ # psutil's parent() already refuses a recycled ppid (parent born after child).+ chain = [p.pid for p in worker.parents()[:MAX_LAUNCHER_HOPS]]except psutil.Error as exc:raise RuntimeStoreError('worker_not_live') from exc+ if pid != process.pid and process.pid not in chain:+ raise RuntimeStoreError('permission_denied')+ return pid, birth+++def reserve_admission_worker(authority, *, admission_id, process, principal_id, hello):+ """Return a private bootstrap scope; never accept caller-selected kind/target.++ Only the owner process may reserve its live direct exec child. The admission+ supplies physical session and generation; its durable principal must match+ the producer. Do not publish the returned secret on any client event stream.+ """+ authority._require_admission_open()+ pid, birth = verify_worker_identity(process, hello)secret = secrets.token_urlsafe(32)def write(conn):@@ -47,7 +76,7 @@ def reserve_admission_worker(authority, *, admission_id, process, principal_id):if conn.execute("SELECT 1 FROM worker_executions WHERE session_id=? AND status!='terminal'", (sid,)).fetchone():raise RuntimeStoreError('stale_generation')scope = dict(profile_id=authority.profile_id, session_id=sid, execution_id=execution_id,- generation=generation, pid=process.pid, birth=birth, secret=secret)+ generation=generation, pid=pid, birth=birth, secret=secret)claim = admission_fingerprint(canonical_target=sid, payload=scope | {'principal': principal_id})conn.execute("INSERT INTO worker_executions(execution_id,session_id,kind,owner_epoch,generation,status,adoption_digest) ""VALUES(?,?,'compute',?,?,'registered',?)",diff --git a/tests/gateway/test_managed_worker_fencing.py b/tests/gateway/test_managed_worker_fencing.pyindex 99153aafe24..62708021abd 100644--- a/tests/gateway/test_managed_worker_fencing.py+++ b/tests/gateway/test_managed_worker_fencing.py@@ -1,15 +1,22 @@"""Loss is not success; delayed parent results cannot revive an admission."""from contextlib import closing+import osimport subprocessimport sysfrom types import SimpleNamespace+import psutilimport pytestfrom hermes_state import SessionDBfrom hermes_state_runtime import admit_session_input, begin_runtime_epoch, claim_session_input+def hello(process):+ """A direct child's self-introduction (no launcher: chain length 0)."""+ return {'type': 'hello', 'pid': process.pid, 'birth': psutil.Process(process.pid).create_time(), 'ancestors': [os.getpid()]}++def test_worker_loss_fences_same_generation_parent_result(tmp_path):from gateway.session_worker_reservation import reserve_admission_worker, lose_admission_workerfrom gateway.session_results import retain_result@@ -22,7 +29,7 @@ def test_worker_loss_fences_same_generation_parent_result(tmp_path):child = subprocess.Popen([sys.executable, '-c', 'import sys; sys.stdin.read()'],stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)try:- scope = reserve_admission_worker(authority, admission_id=row['admission_id'], process=child, principal_id='human')+ scope = reserve_admission_worker(authority, admission_id=row['admission_id'], process=child, principal_id='human', hello=hello(child))child.kill()child.wait(timeout=5)lose_admission_worker(authority, row, scope)diff --git a/tests/gateway/test_worker_admission_reservation.py b/tests/gateway/test_worker_admission_reservation.pyindex f9556174e97..34261a3fbd5 100644--- a/tests/gateway/test_worker_admission_reservation.py+++ b/tests/gateway/test_worker_admission_reservation.py@@ -1,8 +1,10 @@"""Owner-issued admission reservations never weaken idle public registration."""+import osimport subprocessimport sysfrom types import SimpleNamespace+import psutilimport pytestfrom hermes_state import SessionDB@@ -10,6 +12,11 @@ from hermes_state_runtime import (admit_session_input, begin_runtime_epoch, clairegister_worker_execution, settle_session_input)+def hello(process):+ """A direct child's self-introduction (no launcher: chain length 0)."""+ return {'type': 'hello', 'pid': process.pid, 'birth': psutil.Process(process.pid).create_time(), 'ancestors': [os.getpid()]}++def test_started_admission_binds_only_exact_owned_process_and_principal(tmp_path):from gateway.session_worker_reservation import reserve_admission_workerdb = SessionDB(tmp_path / 'state.db')@@ -20,7 +27,7 @@ def test_started_admission_binds_only_exact_owned_process_and_principal(tmp_pathepoch = begin_runtime_epoch(db, instance_id='owner')authority = SimpleNamespace(db=db, epoch=epoch, profile_id=str(tmp_path), _require_admission_open=lambda: None)admitted = admit_session_input(db, epoch=epoch, principal_id='human', session_id='owned', request_id='input', payload={})- kwargs = dict(admission_id=admitted['admission_id'], process=process, principal_id='human')+ kwargs = dict(admission_id=admitted['admission_id'], process=process, principal_id='human', hello=hello(process))with pytest.raises(Exception, match='producer_not_started'):reserve_admission_worker(authority, **kwargs)claim = claim_session_input(db, epoch=epoch, session_id='owned')@@ -58,7 +65,7 @@ async def test_reserved_process_uses_existing_authenticated_adoption_and_persistauthority = SimpleNamespace(db=db, epoch=epoch, profile_id=str(tmp_path), _require_admission_open=lambda: None)admitted = admit_session_input(db, epoch=epoch, principal_id='human', session_id='owned', request_id='input', payload={})claim_session_input(db, epoch=epoch, session_id='owned')- scope = reserve_admission_worker(authority, admission_id=admitted['admission_id'], process=process, principal_id='human')+ scope = reserve_admission_worker(authority, admission_id=admitted['admission_id'], process=process, principal_id='human', hello=hello(process))actor = SimpleNamespace(subject='human', profile_id=str(tmp_path), capabilities={'worker:adopt'})connection = SimpleNamespace(authority=authority, actor=actor)identity = {k: v for k, v in scope.items() if k != 'epoch'}