fix(sandbox): an acquired process stream stays its agent's (round-2 finding 16)

start_process and attach_process returned the backend's raw stdin/stdout/poll, so a
stream acquired under A could be read or written by anyone holding it under B. They
now return ScopedPipe proxies and a scoped poll. Every pipe operation (read, write,
flush, close, fileno, iteration, attribute access) and poll() checks the bound scope
against the sandbox's identity first, and refuses with CrossAgentHandleRefused under
another agent or with no scope bound. The foreign_handle_refused conformance check
drives the real stub process stream under B. A unit test covers start and attach.
This commit is contained in:
Ben Barclay
2026-11-06 16:54:06 +11:00
committed by Mark S.
parent 4fd509e4e0
commit 99a69efede
5 changed files with 97 additions and 5 deletions

View File

@@ -67,7 +67,9 @@ class TerminalEnvironmentProvider(ProviderBase):
bound scope as ``scope=`` to every operation. The environment must implement the hosted operation
interface (``sandbox_scope.require_hosted_interface``: ``execute``, ``cleanup`` and the long-lived
process methods, plus ``fetch_file``/``fetch_realpath``/``get_temp_dir``/``stop_idle`` when present,
each accepting ``scope=``) or it is refused at creation. The long-lived process methods are:
each accepting ``scope=``) or it is refused at creation. The streams core hands back are proxies
that refuse every pipe and ``poll`` operation under another agent's scope. The long-lived process
methods are:
* ``start_process(name, argv, *, child_env=None, scope)`` → ``ProcessStream`` with stdin and stdout
open as byte pipes; ``attach_process(name, *, scope)`` → the running process's stream, or

View File

@@ -376,3 +376,31 @@ def test_local_scopes_build_byte_identical_environments(monkeypatch):
monkeypatch.setattr(sandbox_scope, "hosted_scope", real_hosted_scope)
assert with_machinery == without, f"local behaviour changed under scope {scope}"
assert b"False)" not in with_machinery, "a local backend came back wrapped"
def test_an_acquired_stream_is_refused_under_another_scope():
"""start_process / attach_process hand back proxies: once acquired, a stream's pipes and poll
stay A's, whoever holds the object (round-2 finding 16)."""
import io
from agent.runtime_scope import bind_state
from tools.environments.sandbox_scope import ProcessRef, ProcessStream
class Backend:
def start_process(self, *args, **kwargs):
return ProcessStream(ProcessRef("", "service"), io.BytesIO(), io.BytesIO(b"A-PRIVATE"), lambda: None)
attach_process = start_process
env = ScopedEnvironment(Backend(), sandbox_identity(A), owner=A)
with bind_state(A):
stream, attached = env.start_process("service", ["cat"]), env.attach_process("service")
for s in (stream, attached):
with bind_state(B):
for op in (lambda: s.stdout.read(), lambda: s.stdin.write(b"x"), s.poll, lambda: s.stdout.close(),
lambda: list(s.stdout), lambda: s.stdout.closed):
with pytest.raises(CrossAgentHandleRefused):
op()
with pytest.raises(CrossAgentHandleRefused): # no scope at all is not the owner either
s.stdout.read()
with bind_state(A):
assert stream.stdout.read() == b"A-PRIVATE" and stream.poll() is None

View File

@@ -225,7 +225,16 @@ def check_foreign_handle_refused(provider: RecordingSandboxProvider, a: Scope, b
else:
raise AssertionError("B's environment accepted a process reference naming A's sandbox")
assert all(c.sandbox != _identity(a) for c in provider.calls[seen:]), "a refused call reached A's sandbox"
with _bind(b): # the stream object A acquired stays A's: no pipe or poll operation runs under B
for attempt in (lambda: stream.stdin.write(b"x"), lambda: stream.stdout.read(1), stream.poll,
lambda: stream.stdin.close(), lambda: stream.stdout.fileno(), lambda: next(iter(stream.stdout))):
try:
attempt()
except CrossAgentHandleRefused:
continue
raise AssertionError("an operation on A's process stream ran under B's scope")
with _bind(a):
assert stream.poll() is None
attached = env_a.attach_process(stream.ref)
assert attached is not None
attached.stdin.write(b"ping\n")

View File

@@ -23,7 +23,7 @@ import functools
import inspect
import os
import posixpath
from dataclasses import dataclass, field, replace
from dataclasses import dataclass, field
from typing import IO, Any, Callable, Optional
from urllib.parse import quote
@@ -254,19 +254,25 @@ class ScopedEnvironment:
"""Start *argv* in this sandbox as the long-lived process *name*, stdio open both ways."""
scope = require_identity(self.sandbox, "start_process")
stream = self._inner.start_process(name, argv, child_env=child_env, scope=scope)
return replace(stream, ref=ProcessRef(self.sandbox.key, name))
return self._guard_stream(stream, name)
def attach_process(self, ref: ProcessRef | str) -> Optional[ProcessStream]:
"""The running process *ref* started earlier in this sandbox, or ``None``."""
name = self._own_name(ref, "attach_process")
stream = self._inner.attach_process(name, scope=require_identity(self.sandbox, "attach_process"))
return None if stream is None else replace(stream, ref=ProcessRef(self.sandbox.key, name))
return None if stream is None else self._guard_stream(stream, name)
def stop_process(self, ref: ProcessRef | str) -> bool:
"""Stop *ref*; ``False`` when no such process was running."""
name = self._own_name(ref, "stop_process")
return self._inner.stop_process(name, scope=require_identity(self.sandbox, "stop_process"))
def _guard_stream(self, stream: ProcessStream, name: str) -> ProcessStream:
"""*stream* with every pipe and ``poll`` behind this sandbox's identity check: a stream once
acquired by A stays A's, whoever holds the object later."""
return ProcessStream(ProcessRef(self.sandbox.key, name), ScopedPipe(stream.stdin, self.sandbox),
ScopedPipe(stream.stdout, self.sandbox), _scoped_call(stream.poll, self.sandbox, "poll"))
def _own_name(self, ref: ProcessRef | str, what: str) -> str:
if isinstance(ref, ProcessRef):
if ref.sandbox != self.sandbox.key:
@@ -276,3 +282,48 @@ class ScopedEnvironment:
def __repr__(self) -> str:
return f"ScopedEnvironment({self._inner!r}, {self.sandbox.key})"
def _scoped_call(fn: Callable[..., Any], identity: SandboxIdentity, what: str) -> Callable[..., Any]:
@functools.wraps(fn)
def call(*args: Any, **kwargs: Any) -> Any:
require_identity(identity, what)
return fn(*args, **kwargs)
return call
class ScopedPipe:
"""One stdio pipe of a hosted long-lived process. Every operation (read, write, flush, close,
fileno, iteration, ...) is refused unless the bound scope is the sandbox's own agent."""
def __init__(self, raw: Any, identity: SandboxIdentity) -> None:
object.__setattr__(self, "_raw", raw)
object.__setattr__(self, "_identity", identity)
def __getattr__(self, name: str) -> Any:
require_identity(self._identity, f"stream {name}")
value = getattr(self._raw, name)
return _scoped_call(value, self._identity, f"stream {name}") if callable(value) else value
def __setattr__(self, name: str, value: Any) -> None:
require_identity(self._identity, f"stream {name}")
setattr(self._raw, name, value)
def __iter__(self) -> Any:
require_identity(self._identity, "stream iteration")
return self
def __next__(self) -> Any:
require_identity(self._identity, "stream iteration")
return next(self._raw)
def __enter__(self) -> ScopedPipe:
require_identity(self._identity, "stream")
return self
def __exit__(self, *exc: object) -> None:
self.close()
def __repr__(self) -> str:
return f"ScopedPipe({self._identity.key})"

View File

@@ -341,7 +341,9 @@ def stop_process(self, name, *, scope): ... # -> bool
```
`ProcessStream` (from `sandbox_scope`) holds byte pipes `stdin` and `stdout`
and a `poll()` that returns the exit status or `None`. A later call in the same
and a `poll()` that returns the exit status or `None`. The stream Hermes hands
back wraps yours: every pipe operation and `poll()` checks the bound scope, so
a stream acquired by one agent is refused to any other holder. A later call in the same
session attaches with the `ProcessRef` from the first stream; a reference that
names another agent's sandbox is refused before your method runs. The built-in
backends implement these too (`tools/environments/base_processes.py`: the