diff --git a/api/core/broker.py b/api/core/broker.py index d9af37ea..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()) @@ -130,6 +139,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 +174,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..5efe7bb3 100755 --- a/scripts/ci/test.sh +++ b/scripts/ci/test.sh @@ -35,4 +35,6 @@ 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 \ + 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() diff --git a/tests/test_mvp_control_safety.py b/tests/test_mvp_control_safety.py new file mode 100644 index 00000000..c8609f0d --- /dev/null +++ b/tests/test_mvp_control_safety.py @@ -0,0 +1,112 @@ +"""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 + + +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