From 5a37f9b0a947846b334663dece8fd4217b51b690 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:50:34 +0100 Subject: [PATCH 1/4] fix(mvp-control): honor STOP_NOW and active/expired agent leases, with synthetic regressions --- api/core/broker.py | 19 ++++++- scripts/ci/test.sh | 3 +- tests/test_mvp_control_safety.py | 87 ++++++++++++++++++++++++++++++++ 3 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 tests/test_mvp_control_safety.py diff --git a/api/core/broker.py b/api/core/broker.py index d9af37ea..06c4fc03 100644 --- a/api/core/broker.py +++ b/api/core/broker.py @@ -130,6 +130,19 @@ async def grant_agent( status_code=403, detail="A valid one-time challenge token is required to grant control", ) + if self.state.user_intent == UserIntent.STOP_NOW: + raise HTTPException( + status_code=403, + detail="User emergency stop prohibits agent control", + ) + if self.state.interactive and self.state.control_mode == ControlMode.AGENT: + expiry = self.state.lease_expiry + if expiry is None or now <= expiry: + raise HTTPException( + status_code=409, + detail="Agent input lease is already held", + ) + self.revoke_agent("lease_expired") # One-time token semantics. self._grant_challenge_token = None self._grant_challenge_expiry = 0.0 @@ -152,7 +165,11 @@ async def renew_agent(self, lease_seconds: int): ) if self.state.user_intent == UserIntent.STOP_NOW: raise HTTPException(status_code=403, detail="User requested STOP_NOW") - self.state.lease_expiry = time.time() + lease_seconds + now = time.time() + if self.state.lease_expiry is not None and now > self.state.lease_expiry: + self.revoke_agent("lease_expired") + raise HTTPException(status_code=403, detail="Agent lease expired") + self.state.lease_expiry = now + lease_seconds def revoke_agent(self, reason: str): # Sync version for internal calls diff --git a/scripts/ci/test.sh b/scripts/ci/test.sh index b773bdc7..89580b0d 100755 --- a/scripts/ci/test.sh +++ b/scripts/ci/test.sh @@ -35,4 +35,5 @@ pytest \ tests/test_ci_vnext_evidence.py \ tests/test_lifecycle_cancel_window.py \ tests/test_health_system_memory.py \ - tests/test_disposable_layer_contract.py + tests/test_disposable_layer_contract.py \ + tests/test_mvp_control_safety.py diff --git a/tests/test_mvp_control_safety.py b/tests/test_mvp_control_safety.py new file mode 100644 index 00000000..aafe0361 --- /dev/null +++ b/tests/test_mvp_control_safety.py @@ -0,0 +1,87 @@ +"""Bounded MVP human-override and single-writer broker regressions. + +Only invented sessions; no X11/Wine, host automation, human biometric checks, +or physical hardware are involved. +""" + +import asyncio +import time +from unittest.mock import patch + +import pytest +from fastapi import HTTPException + +from api.core.broker import InputBroker +from api.core.models import ControlMode, UserIntent + + +def _broker() -> InputBroker: + with patch("api.core.broker.get_instance_control_mode", return_value="hybrid"): + b = InputBroker() + asyncio.run(b.update_session("synthetic-ic1", interactive=True)) + return b + + +def _grant(b: InputBroker, seconds: int = 60) -> None: + challenge = asyncio.run(b.issue_grant_challenge()) + asyncio.run( + b.grant_agent(seconds, user_ack=True, challenge_token=challenge["token"]) + ) + + +def test_human_stop_cannot_be_overridden_by_new_acknowledgement(): + b = _broker() + _grant(b) + asyncio.run(b.set_user_intent(UserIntent.STOP_NOW)) + assert b.get_state().control_mode == ControlMode.USER + assert asyncio.run(b.check_access()) is False + + token = asyncio.run(b.issue_grant_challenge())["token"] + with pytest.raises(HTTPException) as stopped: + asyncio.run(b.grant_agent(60, user_ack=True, challenge_token=token)) + assert stopped.value.status_code == 403 + assert b.get_state().user_intent == UserIntent.STOP_NOW + assert b.get_state().control_mode == ControlMode.USER + + # Only a new explicit human WAIT intent can clear an emergency stop. + asyncio.run(b.set_user_intent(UserIntent.WAIT)) + _grant(b) + assert b.get_state().control_mode == ControlMode.AGENT + + +def test_second_active_agent_grant_is_refused_without_lease_extension(): + b = _broker() + _grant(b) + first_expiry = b.get_state().lease_expiry + assert first_expiry is not None + second = asyncio.run(b.issue_grant_challenge())["token"] + + with pytest.raises(HTTPException) as already_held: + asyncio.run(b.grant_agent(600, user_ack=True, challenge_token=second)) + assert already_held.value.status_code == 409 + assert b.get_state().control_mode == ControlMode.AGENT + assert b.get_state().lease_expiry == first_expiry + + +def test_expired_lease_cannot_be_renewed_without_new_human_grant(): + b = _broker() + _grant(b) + with b._lock: + b.state.lease_expiry = time.time() - 1 + + with pytest.raises(HTTPException) as expired: + asyncio.run(b.renew_agent(600)) + assert expired.value.status_code == 403 + assert b.get_state().control_mode == ControlMode.USER + assert asyncio.run(b.check_access()) is False + + +def test_active_lease_can_be_renewed_and_human_override_revokes(): + b = _broker() + _grant(b) + old_expiry = b.get_state().lease_expiry + asyncio.run(b.renew_agent(300)) + assert b.get_state().lease_expiry > old_expiry + asyncio.run(b.report_user_activity()) + assert b.get_state().control_mode == ControlMode.USER + assert asyncio.run(b.check_access()) is False From 5f4a35630e748ca1de184ac038e02de6e20bfcd2 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:19:39 +0100 Subject: [PATCH 2/4] test(mvp): HTTP-level agent input authorization, lease, STOP_NOW takeover regressions --- tests/test_mvp_control_api.py | 122 ++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 tests/test_mvp_control_api.py diff --git a/tests/test_mvp_control_api.py b/tests/test_mvp_control_api.py new file mode 100644 index 00000000..08d0cf97 --- /dev/null +++ b/tests/test_mvp_control_api.py @@ -0,0 +1,122 @@ +"""HTTP-level fail-closed input ownership and human takeover regressions. + +All commands are mocked and every session/token is invented; no X11, Wine, +filesystem mutation, human credential, or user device is accessed. +""" + +import asyncio +import os +from contextlib import ExitStack +from unittest.mock import AsyncMock, patch + +import pytest +from fastapi.testclient import TestClient + +from api.core.broker import broker +from api.core.models import ControlMode, UserIntent +from api.server import app + + +@pytest.fixture +def ic1_api(): + with ExitStack() as stack: + stack.enter_context(patch.dict(os.environ, {"API_TOKEN": "synthetic-control-token"})) + stack.enter_context( + patch( + "api.routers.control.read_session_dir", + return_value="/artifacts/sessions/ic1-test", + ) + ) + stack.enter_context( + patch("api.routers.input._require_active_session", return_value="/tmp/ic1-test") + ) + stack.enter_context( + patch("api.routers.input.append_input_event") + ) + stack.enter_context( + patch("api.routers.input.append_trace_event") + ) + stack.enter_context( + patch( + "api.routers.input.input_trace_windows_log_path", + return_value="/tmp/ic1-fake-windows-trace", + ) + ) + stack.enter_context(patch("api.routers.input.emit_operation_timing")) + stack.enter_context(patch("api.routers.control.emit_operation_timing")) + send = stack.enter_context( + patch("api.routers.input._send_keys", new_callable=AsyncMock) + ) + send.return_value = {"ok": True, "backend": "xdotool"} + asyncio.run(broker.set_user_intent(UserIntent.WAIT)) + asyncio.run(broker.update_session("ic1-test", interactive=True)) + try: + yield TestClient(app), {"X-API-Key": "synthetic-control-token"}, send + finally: + asyncio.run(broker.update_session("ic1-test", interactive=True)) + asyncio.run(broker.set_user_intent(UserIntent.WAIT)) + + +def _challenge(client, headers): + response = client.post( + "/sessions/ic1-test/control/challenge", headers=headers + ) + assert response.status_code == 200 + return response.json()["token"] + + +def _grant(client, headers, challenge): + return client.post( + "/sessions/ic1-test/control/grant", + json={ + "lease_seconds": 90, + "user_ack": True, + "challenge_token": challenge, + }, + headers=headers, + ) + + +def test_actual_api_input_blocked_until_human_grant_then_emitted(ic1_api): + client, headers, send = ic1_api + blocked = client.post( + "/input/key", json={"keys": "a", "backend": "xdotool"}, headers=headers + ) + assert blocked.status_code == 423 + send.assert_not_called() + + token = _challenge(client, headers) + assert _grant(client, headers, token).status_code == 200 + result = client.post( + "/input/key", json={"keys": "a", "backend": "xdotool"}, headers=headers + ) + assert result.status_code == 200 + assert result.json()["status"] == "sent" + send.assert_awaited_once() + assert broker.get_state().control_mode == ControlMode.AGENT + + +def test_api_emergency_stop_refuses_fresh_grant_and_real_input(ic1_api): + client, headers, send = ic1_api + first_token = _challenge(client, headers) + assert _grant(client, headers, first_token).status_code == 200 + assert _grant(client, headers, first_token).status_code == 403 + + competing_token = _challenge(client, headers) + assert _grant(client, headers, competing_token).status_code == 409 + + stopped = client.post( + "/sessions/ic1-test/user_intent", + json={"intent": "STOP_NOW"}, + headers=headers, + ) + assert stopped.status_code == 200 + assert broker.get_state().control_mode == ControlMode.USER + + attempted = _grant(client, headers, _challenge(client, headers)) + assert attempted.status_code == 403 + blocked = client.post( + "/input/key", json={"keys": "a", "backend": "xdotool"}, headers=headers + ) + assert blocked.status_code == 423 + send.assert_not_called() From 5faf8df27e2500c8bf7bdb1c05353af94e061ad0 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:19:59 +0100 Subject: [PATCH 3/4] ci(mvp): require broker HTTP-authorization and emergency-stop regressions in full unit suite --- scripts/ci/test.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/ci/test.sh b/scripts/ci/test.sh index 89580b0d..5efe7bb3 100755 --- a/scripts/ci/test.sh +++ b/scripts/ci/test.sh @@ -36,4 +36,5 @@ pytest \ tests/test_lifecycle_cancel_window.py \ tests/test_health_system_memory.py \ tests/test_disposable_layer_contract.py \ - tests/test_mvp_control_safety.py + tests/test_mvp_control_safety.py \ + tests/test_mvp_control_api.py From 99de3d75b527868f0b362de4bc832173b9788e9f Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:54:45 +0100 Subject: [PATCH 4/4] fix(mvp-control): invalidate grant challenges and agent lease on session handover --- api/core/broker.py | 9 +++++++++ tests/test_mvp_control_safety.py | 25 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/api/core/broker.py b/api/core/broker.py index 06c4fc03..e60f72bb 100644 --- a/api/core/broker.py +++ b/api/core/broker.py @@ -86,6 +86,15 @@ async def update_session( session_control_mode: ControlPolicyMode = ControlPolicyMode.HYBRID, ): with self._lock: + if self.state.session_id != session_id: + # Grant challenges are scoped to a session. A token issued + # before handover must not authorize control in the next one. + self._grant_challenge_token = None + self._grant_challenge_expiry = 0.0 + if self.state.control_mode == ControlMode.AGENT: + self.revoke_agent("session_changed") + else: + self.state.lease_expiry = None self.state.session_id = session_id self.state.interactive = interactive self.state.instance_control_mode = ControlPolicyMode(get_instance_control_mode()) diff --git a/tests/test_mvp_control_safety.py b/tests/test_mvp_control_safety.py index aafe0361..c8609f0d 100644 --- a/tests/test_mvp_control_safety.py +++ b/tests/test_mvp_control_safety.py @@ -85,3 +85,28 @@ def test_active_lease_can_be_renewed_and_human_override_revokes(): asyncio.run(b.report_user_activity()) assert b.get_state().control_mode == ControlMode.USER assert asyncio.run(b.check_access()) is False + + +def test_stale_human_challenge_cannot_grant_after_session_handover(): + b = _broker() + previous_token = asyncio.run(b.issue_grant_challenge())["token"] + asyncio.run(b.update_session("ic1-replacement-session", interactive=True)) + with pytest.raises(HTTPException) as stale: + asyncio.run(b.grant_agent(60, user_ack=True, challenge_token=previous_token)) + assert stale.value.status_code == 403 + assert b.get_state().control_mode == ControlMode.USER + new_token = asyncio.run(b.issue_grant_challenge())["token"] + asyncio.run(b.grant_agent(60, user_ack=True, challenge_token=new_token)) + assert b.get_state().control_mode == ControlMode.AGENT + + +def test_active_agent_lease_is_revoked_across_session_handover(): + b = _broker() + _grant(b) + assert b.get_state().lease_expiry is not None + asyncio.run(b.update_session("ic1-next-session", interactive=True)) + state = b.get_state() + assert state.session_id == "ic1-next-session" + assert state.control_mode == ControlMode.USER + assert state.lease_expiry is None + assert asyncio.run(b.check_access()) is False