fix(approval): skip the execute_code gate only while an approving viewer is attached
The exemption's last condition, a notifier registered for the bound session key, holds for every gateway session turn: TurnRunner registers it whether or not a viewer is attached. It only told side tasks apart and did not show that anyone could answer. A viewer's queued turn that ran after the viewer detached still skipped the whole-script gate, so non-terminal() code in the script ran unprompted while its terminal() prompts timed out. The attached-viewer records are reachable without a new protocol: the live session that execute_admission binds for a viewer turn holds its subscribers, the same records the approval resolver checks (SessionAuthority accepts an approval answer only from an attached subscriber holding session:approve) and the local clarify path already reads. approval_context.is_viewer_turn_with_approver() now also requires such a subscriber at gate time; a read-only viewer or nobody attached keeps the whole-script gate. The notifier check stays, documented as what it is: it tells side tasks apart, not that a human is present. Tests: a viewer turn with nobody or only a read-only viewer attached gets the whole-script prompt and a denied script never runs, and a viewer's turn submitted after it detached keeps the gate in the real drain (both failed before this change: the script ran / the gate was skipped). Refs #134889 (T2) Refs #139523
This commit is contained in:
parent
021468f4b3
commit
4e0806d5dc
@ -14,7 +14,7 @@ logger = logging.getLogger(__name__)
|
||||
admission_author = ContextVar('admission_author', default=None)
|
||||
executing_admission = ContextVar('executing_admission', default=False)
|
||||
# The live session while the executing turn is one its viewer submitted (``is_viewer_input``), else None.
|
||||
viewer_turn = ContextVar('viewer_turn', default=None)
|
||||
viewer_turn: ContextVar = ContextVar('viewer_turn', default=None)
|
||||
# Set by a busy-path caller that must be released once its input is durably queued.
|
||||
busy_acceptance = ContextVar('busy_acceptance', default=None)
|
||||
# ``_validate_native`` clauses about the message's own content, safe to name to the sender's chat.
|
||||
|
||||
@ -76,7 +76,7 @@ async def test_only_the_viewers_own_turn_skips_the_whole_script_gate(tmp_path, m
|
||||
ref = create_local_session(authority, viewer, dict(request_id="cli", source="cli", model="fixture",
|
||||
toolsets=[]))
|
||||
live = authority.sessions[ref.session_id]
|
||||
await authority.attach(viewer, ref)
|
||||
subscription = (await authority.attach(viewer, ref)).subscription_id
|
||||
entry = runner.session_store.lookup_by_session_key(live.route)
|
||||
adapter = runner._adapter_for_source(live.source)
|
||||
|
||||
@ -88,12 +88,17 @@ async def test_only_the_viewers_own_turn_skips_the_whole_script_gate(tmp_path, m
|
||||
await async_wait_until(lambda: "plugin injection" in gates, timeout=10, what="the injected turn")
|
||||
assert await admit_route_wake(runner, adapter, live.source, "loop tick", "loop-tick") is True
|
||||
await async_wait_until(lambda: "loop tick" in gates, timeout=10, what="the /loop tick")
|
||||
# The viewer detaches: its queued turn still runs, with nobody attached who can answer.
|
||||
await authority.detach(viewer, subscription)
|
||||
await authority.submit(viewer, Submission("queued", ref, {"text": "typed, then detached"}, "queue"))
|
||||
await async_wait_until(lambda: "typed, then detached" in gates, timeout=10, what="the detached turn")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
assert gates == {"typed by the viewer": (True, []),
|
||||
"plugin injection": (False, ["execute_code"]),
|
||||
"loop tick": (False, ["execute_code"])}
|
||||
"loop tick": (False, ["execute_code"]),
|
||||
"typed, then detached": (False, ["execute_code"])}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("request_id,payload,viewer", [
|
||||
|
||||
@ -33,12 +33,15 @@ def _policy(source: str, cwd: str) -> LocalSessionPolicy:
|
||||
toolsets=(), config_json="{}", request_json="{}", terminal_json="{}")
|
||||
|
||||
|
||||
def _viewer_session():
|
||||
"""The live session with its viewer attached, holding ``session:approve`` (what ``session.resume`` records)."""
|
||||
def _viewer_session(attached: str = "approver"):
|
||||
"""The live session; ``attached`` is who ``session.resume`` recorded as subscribed: a viewer holding
|
||||
``session:approve``, a read-only one, or nobody."""
|
||||
from types import SimpleNamespace
|
||||
from gateway.session_authority import LiveSession
|
||||
live = LiveSession(None, SESSION_KEY)
|
||||
live.subscribers["viewer"] = SimpleNamespace(capabilities=frozenset({"session:read", "session:approve"}))
|
||||
capabilities = {"approver": {"session:read", "session:approve"}, "read-only": {"session:read"}}.get(attached)
|
||||
if capabilities is not None:
|
||||
live.subscribers["viewer"] = SimpleNamespace(capabilities=frozenset(capabilities))
|
||||
return live
|
||||
|
||||
|
||||
@ -60,9 +63,11 @@ def turn(monkeypatch, tmp_path):
|
||||
|
||||
cleanups = []
|
||||
|
||||
def start(*, platform: str = "local", source: str | None = None, viewer: bool = True, **set_answers):
|
||||
def start(*, platform: str = "local", source: str | None = None, viewer: bool = True,
|
||||
attached: str = "approver", **set_answers):
|
||||
"""``viewer``: the turn is one the session's viewer submitted (``execute_admission`` binds it);
|
||||
``False`` is a plugin injection or another producer admission into the session."""
|
||||
``False`` is a plugin injection or another producer admission into the session. ``attached``: see
|
||||
``_viewer_session``."""
|
||||
monkeypatch.setenv("HERMES_EXEC_ASK", "1") # start_gateway() sets it process-wide
|
||||
for name in ("HERMES_INTERACTIVE", "HERMES_GATEWAY_SESSION", "HERMES_CRON_SESSION"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
@ -72,7 +77,7 @@ def turn(monkeypatch, tmp_path):
|
||||
policy_token = _ACTIVE_POLICY.set(_policy(source, str(tmp_path)) if source else None)
|
||||
if viewer:
|
||||
from gateway.session_ingress import viewer_turn
|
||||
viewer_token = viewer_turn.set(_viewer_session())
|
||||
viewer_token = viewer_turn.set(_viewer_session(attached))
|
||||
cleanups.append(lambda: viewer_turn.reset(viewer_token))
|
||||
A.register_gateway_notify(SESSION_KEY, notify)
|
||||
cleanups.append(lambda: (A.unregister_gateway_notify(SESSION_KEY), _ACTIVE_POLICY.reset(policy_token),
|
||||
@ -184,6 +189,22 @@ def test_injected_turn_keeps_whole_script_gate(child_env, turn, source):
|
||||
assert [p["pattern_key"] for p in prompts] == ["execute_code"]
|
||||
|
||||
|
||||
@pytest.mark.platforms("posix")
|
||||
@pytest.mark.parametrize("source", ["cli", "gui"])
|
||||
@pytest.mark.parametrize("attached", ["nobody", "read-only"])
|
||||
def test_viewer_turn_with_no_approver_attached_keeps_whole_script_gate(child_env, turn, source, attached):
|
||||
"""The turn's notifier is registered for every session turn, viewer attached or not; the exemption also
|
||||
needs an attached viewer that can answer approvals. Otherwise the script is approved as a whole and,
|
||||
with nobody approving, never runs."""
|
||||
victim = child_env / "victim"
|
||||
victim.mkdir()
|
||||
prompts = turn(source=source, attached=attached) # every prompt is denied
|
||||
_code, result = _run_unguarded_rm(victim)
|
||||
assert result.get("error") == _DENIED_SCRIPT, result
|
||||
assert "ran" not in result.get("output", "") and victim.is_dir()
|
||||
assert [p["pattern_key"] for p in prompts] == ["execute_code"]
|
||||
|
||||
|
||||
@pytest.mark.platforms("posix")
|
||||
@pytest.mark.parametrize("source", ["cli", "acp"])
|
||||
@pytest.mark.parametrize("notifier", [True, False], ids=["during-parent-turn", "after-parent-turn"])
|
||||
|
||||
@ -1201,12 +1201,14 @@ _EXECUTE_CODE_DESCRIPTION = (
|
||||
|
||||
|
||||
def _is_local_viewer_turn() -> bool:
|
||||
"""A local session's turn its viewer submitted: its frozen launch policy is local-interactive, the admission
|
||||
is the viewer's own prompt (not a plugin injection or another producer admission), it is not a delegate_task
|
||||
child (sync or async; they inherit the parent's policy), and the turn's approval notifier is registered
|
||||
under the bound session key (side tasks bind their own task key with none)."""
|
||||
"""A local session's turn its viewer submitted, with that viewer there to answer: its frozen launch policy is
|
||||
local-interactive, the admission is the viewer's own prompt (not a plugin injection or another producer
|
||||
admission) and a viewer holding ``session:approve`` is attached now, it is not a delegate_task child (sync or
|
||||
async; they inherit the parent's policy), and the turn's approval notifier is registered under the bound
|
||||
session key. The notifier is registered for every session turn, so it only tells side tasks (their own task
|
||||
key, none registered) apart; it does not show anyone is attached."""
|
||||
from agent.delegation_context import is_delegated_child_process_context
|
||||
return (approval_context._is_local_interactive_session() and approval_context.is_viewer_submitted_turn()
|
||||
return (approval_context._is_local_interactive_session() and approval_context.is_viewer_turn_with_approver()
|
||||
and not is_delegated_child_process_context()
|
||||
and _gateway_notify_cb(get_current_session_key()) is not None)
|
||||
|
||||
|
||||
@ -96,16 +96,21 @@ def _is_local_interactive_session() -> bool:
|
||||
return policy is not None and policy.source in _LOCAL_INTERACTIVE_SOURCES
|
||||
|
||||
|
||||
def is_viewer_submitted_turn() -> bool:
|
||||
"""True while the executing turn is one its session's viewer submitted through ``session.submit``, as
|
||||
the gateway's FIFO drain recorded for this admission. A plugin ``inject_message`` turn, a delegation
|
||||
completion, a background-process or watch notice, a /loop tick, a heartbeat or a hosted-room task is
|
||||
not."""
|
||||
def is_viewer_turn_with_approver() -> bool:
|
||||
"""True while the executing turn is one its session's viewer submitted through ``session.submit`` (as the
|
||||
gateway's FIFO drain recorded for this admission) and a viewer that can answer approvals is attached now:
|
||||
a subscriber holding ``session:approve``, the only answer the gateway's approval resolver accepts. A plugin
|
||||
``inject_message`` turn, a delegation completion, a background-process or watch notice, a /loop tick, a
|
||||
heartbeat or a hosted-room task is never a viewer turn."""
|
||||
try:
|
||||
from gateway.session_ingress import viewer_turn
|
||||
except ImportError: # install without the gateway package: no admission is executing
|
||||
return False
|
||||
return viewer_turn.get() is not None
|
||||
live = viewer_turn.get()
|
||||
if live is None:
|
||||
return False
|
||||
with live.event_stream.lock:
|
||||
return any("session:approve" in member.capabilities for member in live.subscribers.values())
|
||||
|
||||
|
||||
def set_current_session_key(session_key: str) -> contextvars.Token[str]:
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user