diff --git a/.github/workflows/formal-cross-layer-tlc.yml b/.github/workflows/formal-cross-layer-tlc.yml new file mode 100644 index 00000000..6bf7ad7b --- /dev/null +++ b/.github/workflows/formal-cross-layer-tlc.yml @@ -0,0 +1,91 @@ +name: Formal Cross-Layer Safety (TLC) + +on: + pull_request: + paths: + - "formal/**" + - ".github/workflows/formal-cross-layer-tlc.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: formal-cross-layer-${{ github.ref }} + cancel-in-progress: true + +jobs: + check-finite-state-models: + runs-on: ubuntu-24.04 + timeout-minutes: 12 + steps: + - name: Checkout public synthetic model source + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + persist-credentials: false + - name: Install pinned public TLC v1.7.4 + shell: bash + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/formal" + curl --fail --location --silent --show-error --retry 2 \ + --connect-timeout 15 --max-time 90 \ + https://github.com/tlaplus/tlaplus/releases/download/v1.7.4/tla2tools.jar \ + -o "$RUNNER_TEMP/formal/tla2tools.jar" + printf 'bee4a54f3ee3d4afc347c3240ec2d9e93b075104 %s\n' \ + "$RUNNER_TEMP/formal/tla2tools.jar" | sha1sum --check --status + java -version + - name: Exhaustive finite-state invariant checking + shell: bash + run: | + set -euo pipefail + cd formal/tla + for model in ControlLease SessionHandover ReleaseAdmission; do + echo "TLC_MODEL=$model" + timeout 90s java -Xmx768m -XX:+UseParallelGC \ + -cp "$RUNNER_TEMP/formal/tla2tools.jar" tlc2.TLC \ + -workers 1 -deadlock -config "$model.cfg" "$model.tla" + done + echo "FORMAL_TLC_VERDICT=PASS" + - name: Prove adversarial stale-input model is rejected by TLC + shell: bash + run: | + set -euo pipefail + cd formal/tla + if timeout 45s java -Xmx512m -XX:+UseParallelGC \ + -cp "$RUNNER_TEMP/formal/tla2tools.jar" tlc2.TLC \ + -workers 1 -deadlock -config ControlLeaseUnsafe.cfg \ + ControlLeaseUnsafe.tla > "$RUNNER_TEMP/formal/unsafe-tlc.log" 2>&1; then + echo "FORMAL_NEGATIVE_CONTROL=FAILED_TO_DETECT_STALE_INPUT" + exit 1 + fi + # A parser error or missing dependency is not a valid counterexample. + if ! grep -Fq 'Invariant NoUnauthorizedEffect is violated' \ + "$RUNNER_TEMP/formal/unsafe-tlc.log"; then + echo "FORMAL_NEGATIVE_CONTROL=NO_EXPECTED_COUNTEREXAMPLE" + exit 1 + fi + echo "FORMAL_NEGATIVE_CONTROL=STALE_INPUT_COUNTEREXAMPLE_CONFIRMED" + - name: Prove split-owner restart without reconciliation is rejected by TLC + shell: bash + run: | + set -euo pipefail + cd formal/tla + if timeout 45s java -Xmx512m -XX:+UseParallelGC \ + -cp "$RUNNER_TEMP/formal/tla2tools.jar" tlc2.TLC \ + -workers 1 -deadlock -config SessionHandoverUnsafe.cfg \ + SessionHandoverUnsafe.tla > "$RUNNER_TEMP/formal/unsafe-handover.log" 2>&1; then + echo "FORMAL_HANDOVER_NEGATIVE=FAILED_TO_DETECT_SPLIT_OWNER" + exit 1 + fi + if ! grep -Fq 'Invariant ConvergedAtRest is violated' \ + "$RUNNER_TEMP/formal/unsafe-handover.log"; then + echo "FORMAL_HANDOVER_NEGATIVE=NO_EXPECTED_COUNTEREXAMPLE" + exit 1 + fi + echo "FORMAL_HANDOVER_NEGATIVE=SPLIT_OWNER_COUNTEREXAMPLE_CONFIRMED" + - name: Run dependency-free model contract tests + shell: bash + run: | + set -euo pipefail + python3 -m unittest discover -s formal/tests -p 'test_*.py' -v diff --git a/api/core/broker.py b/api/core/broker.py index d9af37ea..97dd2530 100644 --- a/api/core/broker.py +++ b/api/core/broker.py @@ -31,6 +31,7 @@ def __init__(self): self.last_agent_activity = 0.0 self._grant_challenge_token = None self._grant_challenge_expiry = 0.0 + self._authority_epoch = 1 @property def last_activity(self) -> float: @@ -53,6 +54,7 @@ def _compute_effective_mode(self) -> ControlPolicyMode: async def set_instance_control_mode(self, mode: ControlPolicyMode): with self._lock: + self._authority_epoch += 1 self.state.instance_control_mode = mode self.state.effective_control_mode = self._compute_effective_mode() if self.state.effective_control_mode == ControlPolicyMode.AGENT_ONLY: @@ -71,6 +73,7 @@ async def issue_grant_challenge(self, ttl_seconds: int = 30) -> dict: async def set_session_control_mode(self, mode: ControlPolicyMode): with self._lock: + self._authority_epoch += 1 self.state.session_control_mode = mode self.state.effective_control_mode = self._compute_effective_mode() if self.state.effective_control_mode == ControlPolicyMode.AGENT_ONLY: @@ -86,6 +89,7 @@ async def update_session( session_control_mode: ControlPolicyMode = ControlPolicyMode.HYBRID, ): with self._lock: + self._authority_epoch += 1 self.state.session_id = session_id self.state.interactive = interactive self.state.instance_control_mode = ControlPolicyMode(get_instance_control_mode()) @@ -140,6 +144,7 @@ async def grant_agent( ) if not self.state.interactive: return # Always implicit in non-interactive + self._authority_epoch += 1 self.state.control_mode = ControlMode.AGENT self.state.lease_expiry = time.time() + lease_seconds self.state.user_intent = UserIntent.WAIT @@ -152,14 +157,17 @@ 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._authority_epoch += 1 self.state.lease_expiry = time.time() + lease_seconds def revoke_agent(self, reason: str): - # Sync version for internal calls - self.state.control_mode = ControlMode.USER - self.state.lease_expiry = None - self.state.agent_status = AgentStatus.STOPPING - print(f"Broker: Agent revoked ({reason})") + # RLock is reentrant for callers already holding the state lock. + with self._lock: + self._authority_epoch += 1 + self.state.control_mode = ControlMode.USER + self.state.lease_expiry = None + self.state.agent_status = AgentStatus.STOPPING + print(f"Broker: Agent revoked ({reason})") async def report_user_activity(self): with self._lock: @@ -180,6 +188,12 @@ async def set_user_intent(self, intent: UserIntent): async def check_access(self) -> bool: """Returns True if agent is allowed to execute.""" with self._lock: + # STOP_NOW is an absolute veto, including headless and agent-only + # sessions. Never admit a new ticket after human emergency stop. + if self.state.user_intent == UserIntent.STOP_NOW: + if self.state.control_mode == ControlMode.AGENT: + self.revoke_agent("user_stop_now") + return False if self.state.effective_control_mode == ControlPolicyMode.HUMAN_ONLY: return False if self.state.effective_control_mode == ControlPolicyMode.AGENT_ONLY: @@ -196,6 +210,22 @@ async def check_access(self) -> bool: return False return True + async def issue_input_ticket(self) -> int | None: + """Capture current authority generation for one pending input action.""" + with self._lock: + if not await self.check_access(): + return None + return self._authority_epoch + + async def validate_input_ticket(self, ticket: int) -> bool: + """Reject queued work after control/session changes or lease expiry. + + Admission is immediately before backend invocation; it cannot stop an + external process already running. Consumer-side fencing remains needed. + """ + with self._lock: + return ticket == self._authority_epoch and await self.check_access() + def get_state(self) -> ControlState: # Return a detached snapshot so callers cannot mutate shared broker state. with self._lock: diff --git a/api/routers/input.py b/api/routers/input.py index 8aa2eab4..db8ed56e 100644 --- a/api/routers/input.py +++ b/api/routers/input.py @@ -353,7 +353,8 @@ def input_events( async def click_at(data: ClickModel): """Click at coordinates (x, y).""" op_started = time.perf_counter() - if not await broker.check_access(): + authority_ticket = await broker.issue_input_ticket() + if authority_ticket is None: raise HTTPException(status_code=423, detail="Agent control denied by policy") await broker.report_agent_activity() @@ -435,6 +436,10 @@ async def click_at(data: ClickModel): cmd.extend(["click", str(data.button)]) + # Do not execute an action queued before STOP_NOW, lease expiry, or + # session handover. This is admission fencing, not an OS-level kill switch. + if not await broker.validate_input_ticket(authority_ticket): + raise HTTPException(status_code=423, detail="Agent control revoked before input dispatch") result = await run_async_command(cmd) if not result.get("ok"): emit_operation_timing( @@ -507,7 +512,8 @@ async def key_press(data: KeyModel): when configured and the explorer.exe desktop barrier is absent. """ op_started = time.perf_counter() - if not await broker.check_access(): + authority_ticket = await broker.issue_input_ticket() + if authority_ticket is None: raise HTTPException(status_code=423, detail="Agent control denied by policy") await broker.report_agent_activity() @@ -549,6 +555,8 @@ async def key_press(data: KeyModel): }, ) + if not await broker.validate_input_ticket(authority_ticket): + raise HTTPException(status_code=423, detail="Agent control revoked before input dispatch") result = await _send_keys( keys=data.keys, window_id=target_win_id, diff --git a/formal/README.md b/formal/README.md new file mode 100644 index 00000000..4c5844b7 --- /dev/null +++ b/formal/README.md @@ -0,0 +1,59 @@ +# Cross-layer formal verification — first public-safe execution slice + +**Authority:** `SemperSupra/WineBot` source and owning MVP DLE PR #158. **Status:** candidate; TLC/CI evidence required before acceptance. This is not a runtime fix and does not qualify private WinInspect. + +## Actual system boundaries + +| Model | Source surfaces | Atomicity problem | Acceptance property | +| --- | --- | --- | --- | +| `ControlLease.tla` | `api/core/broker.py`, `api/routers/input.py`, brokered WinInspect input | check-permission vs later physical input | an old queued epoch is discarded after STOP_NOW/revocation | +| `SessionHandover.tla` | `api/routers/lifecycle.py`, `api/utils/files.py`, Wine profile link, broker | separately written pointer, profile symlink, session state, broker | crash recovery converges all ownership projections to committed session | +| `ReleaseAdmission.tla` | private WinInspect #468, approved projection receipt, public product binary, WineBot #166 | source/evidence/artifact/consumer-pin mismatch | accepted source generation matches qualification, projection, build and consumer pin | + +The models intentionally do **not** assert that the current production implementation satisfies these properties. The existing `asyncio.Lock` and `threading.RLock` are in-process protections, not host/guest or crash-atomic transactions. `api/core/operations.py` is memory-only and can lose operation state on process restart. The session transition marker is a stepwise journal, not an end-to-end atomic commit. Input checking and input effect require an independently proven fencing point. + +## Method and execution + +- Start with finite explicit-state TLA+ safety models checked by TLC, one worker and short bounded execution per model, in the existing **public repository** on free public GitHub-hosted Ubuntu. No local/sovereign runner admission, no private source or secrets, and no paid private Actions minutes. +- TLA+ v1.7.4 `tla2tools.jar` is pinned by exact release URL **and release-published SHA-1**. SHA-1 is only a published legacy release checksum: before treating this as a production supply-chain attestation, pin a stronger independently trusted SHA-256 or signed provenance. This check verifies the known release asset, not source authenticity. +- Run `ControlLease`, `SessionHandover`, and `ReleaseAdmission` TLC invariants in one bounded static workflow. A nonzero exit, missing jar, timeout, TLA+ syntax error, state-invariant counterexample, or negative-control test failure must fail CI. +- Run separate stdlib Python fault/negative controls to ensure stale queued input and interrupted handover are detectable, and a stale artifact tuple is refused. These are scenario-level independent checks, **not** proofs against the implementation. +- Require real source-code mapping and fault injection before marking any product behavior verified. Future phases: broker epoch/fencing point; handover intent+reconciliation startup; durable operations; recording commit/replay; atomic release authority. + +## Adversarial model-checker sentinel + +`ControlLeaseUnsafe.tla` intentionally models the check-to-effect hazard: an agent queues input while authorized, then STOP_NOW revokes authority, but an unchecked consumer still executes the queued action. The dedicated CI negative-control step **must receive a TLC counterexample for `NoUnauthorizedEffect`**; parser errors, timeouts or unexpected successful model checks fail the build instead. This sentinel does not prove an exploitable live dispatch, only that the formal oracle rejects the bad ordering. Source review of `api/routers/input.py` shows `broker.check_access()` before later `await run_async_command()` or `await _send_keys()`; no generation token accompanies that eventual effect. Qualify an actual commit-time fencing fix separately with controlled synthetic input. + +`SessionHandoverUnsafe.tla` is the companion crash-recovery negative control. It changes only the active-session pointer, crashes, then incorrectly declares the system idle without replay or compensation. TLC must find a `ConvergedAtRest` counterexample, distinguishing a source model with an actual recovery transition from one that simply assumes a clean restart. This still does not prove the Python implementation can recover; its observed marker readback/replay mechanism must be built and tested separately. + +## Required invariants + +**Control:** STOP_NOW invalidates queued older epochs; no agent effect may execute on an expired/superseded lease. One authoritative grant epoch; no assumption that an API's prior check atomically covers external Wine effects. + +**Handover:** Only one committed session owner; after a successful commit or recovery all pointer/profile/broker projections converge; a crash mid-handover is either safely compensated or an incomplete operation is visibly recoverable. No silently succeeded partial handover. + +**Release:** Every admission binds exact private source generation, reviewed projection, independently qualified public binary and WineBot consumer pin. Changing any upstream component invalidates downstream acceptance until requalified. + +## State-machine scope limits and next implementation batch + +This first slice deliberately abstracts remote processes and filesystem details into boolean or finite states and does not prove cross-process fencing, directory fsync, durable credentials, actual Windows Wine11 behavior, or read-only HWND identity. TLC proves only the bounded model and modeled transitions. A known-good TLC result must never be reported as WinInspect #468 C++ CTest PASS or MVP release admission. + +Next implement a trace adapter from real `api/routers/lifecycle.py` checkpoints and `api/core/broker.py` to the modeled actions; inject restart/kill between `write_session_dir`, `link_wine_user_dir`, `write_session_state` and `broker.update_session` on disposable synthetic fixtures; check post-restart convergence. Test two concurrent grant/revoke/STOP_NOW actors with delayed input commit and a generation token. Never enable actual unsafe agent input as a negative control. + +## Evidence and DLE reconciliation + +Every run must record GitHub workflow run/job and commit SHA, TLC tool version/hash, `Spec` and invariant names, distinct/generated states, first counterexample if any, actual unit test result, and whether the verdict is `MODEL_PASS`, `MODEL_FAIL`, `NOT_RUN`, or `PRODUCT_UNQUALIFIED`. The public workflow emits fixed synthetic diagnostic markers only. Follow PR #158 and the formal-work PR for source lineage, reviews, and closure; no new scheduler or second authoritative workset. + +## Concrete route interleaving — first code-to-model refinement + +The source-owned test `tests/test_input_revocation_interleaving.py` uses the production `click_at` coroutine and real `InputBroker` but replaces X11 execution with a pure synthetic command fixture. A barrier suspends the window lookup **after** the first broker permission check, performs real broker `STOP_NOW` revocation and confirms access denied, then allows the route to complete. It originally demonstrated a queued click after `STOP_NOW`; it is now a **safety assertion** that the click does **not** reach the synthetic effect and instead returns HTTP 423. The same test path also checks queued keyboard dispatch and invalidation of authority tickets on session turnover and lease expiration. It does not simulate a physical input event or prove an OS-level kill switch. + +**Remediation contract:** Each asynchronous input request needs a session-scoped immutable authority token / generation, effective expiry, and a consumer-side enforcement point as close to the external effect as possible. A second check in an API route alone narrows but does not close the TOCTOU window if the called backend asynchronously queues unguarded work. Test human STOP_NOW, ordinary user override, lease expiry, session handover, delayed backend starts, process crash/restart, and possible already-in-flight input, including explicit semantics for actions that cannot be recalled. Do not make `STOP_NOW` wait indefinitely for a long-running input process. The first runtime mitigation in `api/core/broker.py` issues an epoch ticket on admission, revokes it whenever authority changes, and `api/routers/input.py` verifies the ticket directly before beginning a mouse or keyboard backend call. This closes the reproduced pre-dispatch interleaving but does **not** guarantee a process already started can be stopped; real native consumer-side fencing/cancellation still requires a separate design and qualification. + +## Session-handover recovery evidence (source review) + +In current public `api/routers/lifecycle.py`, `_write_transition_marker` writes `session.transition.json` during resume and `_clear_transition_marker` removes it after completion or caught exception. A direct source search of this file found marker writes/removals and no recovery reader of the marker at startup. The exception rollback tries to restore selected session pointer/state, but a process termination after `write_session_dir` and before profile linkage / broker update never reaches the exception handler. Thus a marker alone is not a proven restart-reconciliation protocol. Before accepting a change, add a reader/validator for the durable intent (schema, owner generation, previous and target identity), recover to a single authoritative owner on startup, and make crash injection exercise each physical write boundary and directory-sync durability. This is a code-inspection finding, not proof of an observed production crash or data loss. + +## Absolute STOP_NOW admission in all policy modes + +Code review found another production policy ordering gap: `InputBroker.check_access()` previously returned `True` for a non-interactive session and could return via the agent-only mode before considering the `STOP_NOW` intent. An invalidated ticket blocked *old* queued work, but a *new* ticket could be issued after an emergency stop in headless/agent-only mode. The mitigation now checks `STOP_NOW` before any policy-mode shortcut and refuses both new tickets and existing stale tickets. `tests/test_input_revocation_interleaving.py` explicitly exercises both headless/HYBRID and headless/AGENT_ONLY mode with a previously authorized ticket. This remains an in-process admission defense; already-committed native input requires consumer-side fencing. diff --git a/formal/tests/test_model_contracts.py b/formal/tests/test_model_contracts.py new file mode 100644 index 00000000..d265ce6f --- /dev/null +++ b/formal/tests/test_model_contracts.py @@ -0,0 +1,129 @@ +"""Bounded deterministic negative controls for the public formal models. + +This is NOT a replacement for TLC; it tests the intended fault scenarios +independently, with synthetic data and no private source or external effects. +""" +import unittest +from collections import deque +from dataclasses import dataclass, replace + + +@dataclass(frozen=True) +class Lease: + epoch: int = 1 + granted: bool = False + stopped: bool = False + queued: int = 0 + effects: int = 0 + + +def lease_next(s: Lease): + if not s.granted and not s.stopped and s.epoch < 4: + yield "grant", replace(s, granted=True, epoch=s.epoch + 1) + if s.granted and not s.stopped and not s.queued: + yield "queue", replace(s, queued=s.epoch) + if s.granted and s.epoch < 4: + yield "stop", replace(s, granted=False, stopped=True, epoch=s.epoch + 1) + if s.stopped and not s.queued: + yield "ack", replace(s, stopped=False) + if s.queued and s.granted and not s.stopped and s.queued == s.epoch: + # Boolean observed effect, not an unbounded count: finite state space. + yield "effect", replace(s, queued=0, effects=1) + if s.queued and (not s.granted or s.stopped or s.queued != s.epoch): + yield "discard", replace(s, queued=0) + + +def explore(init, next_fn, invariant): + seen = {init} + queue = deque([(init, ())]) + while queue: + state, trace = queue.popleft() + if not invariant(state): + return trace, len(seen) + for name, successor in next_fn(state): + if successor not in seen: + seen.add(successor) + queue.append((successor, trace + (name,))) + return None, len(seen) + + +@dataclass(frozen=True) +class Handover: + phase: str = "idle" + committed: str = "A" + pointer: str = "A" + profile: str = "A" + broker: str = "A" + intent: bool = False + + +def handover_next(s: Handover): + if s.phase == "idle" and s.committed == "A": + yield "prepare", replace(s, phase="prepared", intent=True) + if s.phase == "prepared": + yield "pointer", replace(s, phase="pointer_written", pointer="B") + if s.phase == "pointer_written": + yield "profile", replace(s, phase="profile_linked", profile="B") + if s.phase == "profile_linked": + yield "broker", replace(s, phase="broker_switched", broker="B") + if s.phase == "broker_switched": + yield "commit", replace(s, phase="committed", committed="B", intent=False) + if s.phase in {"prepared", "pointer_written", "profile_linked", "broker_switched"}: + yield "crash", replace(s, phase="recovering") + if s.phase == "recovering": + yield "recover", Handover() + + +def converged_when_idle(s: Handover): + return s.phase not in {"idle", "committed"} or ( + s.pointer == s.profile == s.broker == s.committed and not s.intent + ) + + +class ModelContractTests(unittest.TestCase): + def test_lease_finite_model_has_no_nonfenced_effect(self): + counterexample, count = explore( + Lease(), + lease_next, + lambda s: s.effects >= 0 and not (s.stopped and s.granted), + ) + self.assertIsNone(counterexample) + self.assertGreater(count, 5) + + def test_stale_queued_input_is_discarded_after_stop(self): + state = Lease(epoch=2, granted=True, queued=2) + stopped = dict(lease_next(state))["stop"] + self.assertNotIn("effect", dict(lease_next(stopped))) + self.assertIn("discard", dict(lease_next(stopped))) + + def test_unfenced_negative_control_is_detected(self): + state = Lease(epoch=2, granted=True, queued=2) + stopped = dict(lease_next(state))["stop"] + # Deliberately simulate a broken dispatcher that acts on any queue. + unsafe_effect = stopped.queued > 0 + self.assertTrue(unsafe_effect) + self.assertFalse(stopped.granted) + + def test_handover_crash_at_each_precommit_step_converges(self): + current = Handover() + for action in ("prepare", "pointer", "profile", "broker"): + current = dict(handover_next(current))[action] + interrupted = dict(handover_next(current))["crash"] + recovered = dict(handover_next(interrupted))["recover"] + self.assertEqual(recovered, Handover()) + + def test_handover_bounded_model_never_claims_partial_commit(self): + counterexample, count = explore(Handover(), handover_next, converged_when_idle) + self.assertIsNone(counterexample) + self.assertGreater(count, 8) + + def test_release_requires_same_source_generation(self): + source = 2 + qualified, projected, built, pinned, approved = 1, 1, 1, 1, True + self.assertFalse( + approved and qualified == projected == built == pinned == source + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/formal/tla/ControlLease.cfg b/formal/tla/ControlLease.cfg new file mode 100644 index 00000000..97c0c91d --- /dev/null +++ b/formal/tla/ControlLease.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CONSTANT MaxEpoch = 4 +INVARIANTS TypeOK NoUnauthorizedEffect NoAgentWhileStopped diff --git a/formal/tla/ControlLease.tla b/formal/tla/ControlLease.tla new file mode 100644 index 00000000..76909c56 --- /dev/null +++ b/formal/tla/ControlLease.tla @@ -0,0 +1,70 @@ +---------------------------- MODULE ControlLease ---------------------------- +EXTENDS Naturals, TLC + +\* Bounded safety model: authority revocation and queued input are separate +\* steps. The broker must fence input at EFFECT time, not just queue time. +CONSTANT MaxEpoch +ASSUME MaxEpoch \in Nat \ {0} + +VARIABLES epoch, granted, stopped, queued, lastEffect, effectWasAuthorized +vars == <> + +Init == + /\ epoch = 1 + /\ granted = FALSE + /\ stopped = FALSE + /\ queued = 0 + /\ lastEffect = 0 + /\ effectWasAuthorized = TRUE + +Grant == + /\ ~granted /\ ~stopped /\ epoch < MaxEpoch + /\ epoch' = epoch + 1 + /\ granted' = TRUE + /\ UNCHANGED <> + +QueueInput == + /\ granted /\ ~stopped /\ queued = 0 + /\ queued' = epoch + /\ UNCHANGED <> + +StopNow == + /\ granted /\ epoch < MaxEpoch + /\ epoch' = epoch + 1 + /\ granted' = FALSE + /\ stopped' = TRUE + /\ UNCHANGED <> + +AcknowledgeStop == + /\ stopped /\ queued = 0 + /\ stopped' = FALSE + /\ UNCHANGED <> + +ExecuteInput == + /\ queued # 0 /\ granted /\ ~stopped /\ queued = epoch + /\ lastEffect' = queued + /\ effectWasAuthorized' = granted /\ ~stopped /\ queued = epoch + /\ queued' = 0 + /\ UNCHANGED <> + +DiscardStale == + /\ queued # 0 /\ (~granted \/ stopped \/ queued # epoch) + /\ queued' = 0 + /\ UNCHANGED <> + +Next == Grant \/ QueueInput \/ StopNow \/ AcknowledgeStop + \/ ExecuteInput \/ DiscardStale + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ epoch \in 1..MaxEpoch + /\ granted \in BOOLEAN + /\ stopped \in BOOLEAN + /\ queued \in 0..MaxEpoch + /\ lastEffect \in 0..MaxEpoch + /\ effectWasAuthorized \in BOOLEAN + +NoUnauthorizedEffect == effectWasAuthorized +NoAgentWhileStopped == stopped => ~granted +============================================================================= diff --git a/formal/tla/ControlLeaseUnsafe.cfg b/formal/tla/ControlLeaseUnsafe.cfg new file mode 100644 index 00000000..bf0054a7 --- /dev/null +++ b/formal/tla/ControlLeaseUnsafe.cfg @@ -0,0 +1,2 @@ +SPECIFICATION Spec +INVARIANT NoUnauthorizedEffect diff --git a/formal/tla/ControlLeaseUnsafe.tla b/formal/tla/ControlLeaseUnsafe.tla new file mode 100644 index 00000000..73891041 --- /dev/null +++ b/formal/tla/ControlLeaseUnsafe.tla @@ -0,0 +1,39 @@ +------------------------ MODULE ControlLeaseUnsafe ------------------------- +\* Deliberately BROKEN negative control. TLC MUST find a counterexample: +\* queue under agent authority, STOP_NOW revokes, stale action executes anyway. +VARIABLES granted, queued, stopped, unauthorizedEffect +vars == <> + +Init == + /\ granted = FALSE + /\ queued = FALSE + /\ stopped = FALSE + /\ unauthorizedEffect = FALSE + +Grant == + /\ ~granted /\ ~stopped + /\ granted' = TRUE + /\ UNCHANGED <> + +Queue == + /\ granted /\ ~queued + /\ queued' = TRUE + /\ UNCHANGED <> + +Revoke == + /\ granted + /\ granted' = FALSE + /\ stopped' = TRUE + /\ UNCHANGED <> + +UnsafeExecute == + /\ queued + /\ unauthorizedEffect' = ~granted \/ stopped + /\ queued' = FALSE + /\ UNCHANGED <> + +Next == Grant \/ Queue \/ Revoke \/ UnsafeExecute +Spec == Init /\ [][Next]_vars + +NoUnauthorizedEffect == ~unauthorizedEffect +============================================================================= diff --git a/formal/tla/ReleaseAdmission.cfg b/formal/tla/ReleaseAdmission.cfg new file mode 100644 index 00000000..8918ac92 --- /dev/null +++ b/formal/tla/ReleaseAdmission.cfg @@ -0,0 +1,2 @@ +SPECIFICATION Spec +INVARIANTS TypeOK NoStaleAcceptedArtifact diff --git a/formal/tla/ReleaseAdmission.tla b/formal/tla/ReleaseAdmission.tla new file mode 100644 index 00000000..a1c243fc --- /dev/null +++ b/formal/tla/ReleaseAdmission.tla @@ -0,0 +1,71 @@ +------------------------- MODULE ReleaseAdmission -------------------------- +EXTENDS Naturals + +\* Abstract artifact generation IDs, not actual content digests. +\* Every evidence link must bind to the SAME exact source generation. +VARIABLES source, qualified, projected, built, pinned, approved, phase +vars == <> +Stages == {"candidate", "qualified", "projected", "built", "pinned", "accepted"} + +Init == + /\ source = 1 + /\ qualified = 0 + /\ projected = 0 + /\ built = 0 + /\ pinned = 0 + /\ approved = FALSE + /\ phase = "candidate" + +Qualify == + /\ phase = "candidate" + /\ qualified' = source + /\ phase' = "qualified" + /\ UNCHANGED <> + +ApproveAndProject == + /\ phase = "qualified" /\ qualified = source + /\ projected' = source + /\ approved' = TRUE + /\ phase' = "projected" + /\ UNCHANGED <> + +Build == + /\ phase = "projected" /\ approved /\ projected = source + /\ built' = source + /\ phase' = "built" + /\ UNCHANGED <> + +Pin == + /\ phase = "built" /\ built = source + /\ pinned' = source + /\ phase' = "pinned" + /\ UNCHANGED <> + +Accept == + /\ phase = "pinned" + /\ qualified = source /\ projected = source + /\ built = source /\ pinned = source /\ approved + /\ phase' = "accepted" + /\ UNCHANGED <> + +SourceChanges == + /\ phase # "accepted" /\ source = 1 + /\ source' = 2 + /\ approved' = FALSE + /\ phase' = "candidate" + /\ UNCHANGED <> + +Next == Qualify \/ ApproveAndProject \/ Build \/ Pin \/ Accept \/ SourceChanges +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ source \in {1,2} + /\ qualified \in 0..2 /\ projected \in 0..2 + /\ built \in 0..2 /\ pinned \in 0..2 + /\ approved \in BOOLEAN /\ phase \in Stages + +NoStaleAcceptedArtifact == + (phase = "accepted") => + (approved /\ qualified = source /\ projected = source /\ + built = source /\ pinned = source) +============================================================================= diff --git a/formal/tla/SessionHandover.cfg b/formal/tla/SessionHandover.cfg new file mode 100644 index 00000000..664875ea --- /dev/null +++ b/formal/tla/SessionHandover.cfg @@ -0,0 +1,2 @@ +SPECIFICATION Spec +INVARIANTS TypeOK ConvergedAtRest NoFalseCommit diff --git a/formal/tla/SessionHandover.tla b/formal/tla/SessionHandover.tla new file mode 100644 index 00000000..85129101 --- /dev/null +++ b/formal/tla/SessionHandover.tla @@ -0,0 +1,89 @@ +-------------------------- MODULE SessionHandover --------------------------- +EXTENDS TLC + +\* Logical committed owner is distinct from tentative pointer/profile/broker. +\* Crash recovery must converge all projections back to the committed owner. +Sessions == {"A", "B"} +Phases == {"idle", "prepared", "pointer_written", "profile_linked", + "broker_switched", "committed", "recovering"} + +VARIABLES phase, committed, pointer, profile, broker, intent +vars == <> + +Init == + /\ phase = "idle" + /\ committed = "A" + /\ pointer = "A" + /\ profile = "A" + /\ broker = "A" + /\ intent = FALSE + +Prepare == + /\ phase = "idle" /\ committed = "A" + /\ phase' = "prepared" + /\ intent' = TRUE + /\ UNCHANGED <> + +WritePointer == + /\ phase = "prepared" + /\ phase' = "pointer_written" + /\ pointer' = "B" + /\ UNCHANGED <> + +LinkProfile == + /\ phase = "pointer_written" + /\ phase' = "profile_linked" + /\ profile' = "B" + /\ UNCHANGED <> + +SwitchBroker == + /\ phase = "profile_linked" + /\ phase' = "broker_switched" + /\ broker' = "B" + /\ UNCHANGED <> + +Commit == + /\ phase = "broker_switched" + /\ pointer = "B" /\ profile = "B" /\ broker = "B" + /\ committed' = "B" + /\ phase' = "committed" + /\ intent' = FALSE + /\ UNCHANGED <> + +Crash == + /\ phase \in {"prepared", "pointer_written", "profile_linked", + "broker_switched"} + /\ phase' = "recovering" + /\ UNCHANGED <> + +Recover == + /\ phase = "recovering" + /\ pointer' = committed + /\ profile' = committed + /\ broker' = committed + /\ phase' = "idle" + /\ intent' = FALSE + /\ UNCHANGED committed + +Next == Prepare \/ WritePointer \/ LinkProfile \/ SwitchBroker + \/ Commit \/ Crash \/ Recover + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ phase \in Phases + /\ committed \in Sessions + /\ pointer \in Sessions + /\ profile \in Sessions + /\ broker \in Sessions + /\ intent \in BOOLEAN + +ConvergedAtRest == + (phase \in {"idle", "committed"}) => + (pointer = committed /\ profile = committed /\ + broker = committed /\ ~intent) +NoFalseCommit == + (phase = "committed") => + (committed = "B" /\ pointer = "B" /\ + profile = "B" /\ broker = "B") +============================================================================= diff --git a/formal/tla/SessionHandoverUnsafe.cfg b/formal/tla/SessionHandoverUnsafe.cfg new file mode 100644 index 00000000..a7f35c4f --- /dev/null +++ b/formal/tla/SessionHandoverUnsafe.cfg @@ -0,0 +1,2 @@ +SPECIFICATION Spec +INVARIANT ConvergedAtRest diff --git a/formal/tla/SessionHandoverUnsafe.tla b/formal/tla/SessionHandoverUnsafe.tla new file mode 100644 index 00000000..5efebd7e --- /dev/null +++ b/formal/tla/SessionHandoverUnsafe.tla @@ -0,0 +1,37 @@ +---------------------- MODULE SessionHandoverUnsafe ---------------------- +\* Deliberately BROKEN crash-recovery model. After pointer replacement the +\* process dies, then an unprepared startup declares IDLE without reconciling +\* the profile and broker. TLC must expose a split-owner resting state. +VARIABLES phase, committed, pointer, profile, broker +vars == <> + +Init == + /\ phase = "idle" + /\ committed = "A" + /\ pointer = "A" + /\ profile = "A" + /\ broker = "A" + +Prepare == + /\ phase = "idle" + /\ phase' = "prepared" + /\ UNCHANGED <> + +WritePointer == + /\ phase = "prepared" + /\ pointer' = "B" + /\ phase' = "pointer_written" + /\ UNCHANGED <> + +CrashWithoutRecovery == + /\ phase = "pointer_written" + /\ phase' = "idle" + /\ UNCHANGED <> + +Next == Prepare \/ WritePointer \/ CrashWithoutRecovery +Spec == Init /\ [][Next]_vars + +ConvergedAtRest == + (phase = "idle") => + (pointer = committed /\ profile = committed /\ broker = committed) +============================================================================= diff --git a/tests/test_input_revocation_interleaving.py b/tests/test_input_revocation_interleaving.py new file mode 100644 index 00000000..23a01876 --- /dev/null +++ b/tests/test_input_revocation_interleaving.py @@ -0,0 +1,162 @@ +"""Deterministic safety regression for broker revocation before input dispatch. + +No external xdotool, Wine, or real input processes are executed. +""" +import asyncio +import time +from unittest.mock import patch + +from fastapi import HTTPException + +from api.core.broker import InputBroker +from api.core.models import ClickModel, ControlMode, ControlPolicyMode, UserIntent +from api.routers import input as input_router + + +def test_stop_now_between_window_search_and_click_blocks_stale_effect(): + async def exercise(): + admitted = asyncio.Event() + release_search = asyncio.Event() + observed = [] + broker = InputBroker() + broker.state.interactive = True + broker.state.control_mode = ControlMode.AGENT + broker.state.effective_control_mode = ControlPolicyMode.HYBRID + broker.state.user_intent = UserIntent.WAIT + broker.state.lease_expiry = time.time() + 60 + + async def synthetic_command(command, **_kwargs): + if "search" in command: + admitted.set() + await asyncio.wait_for(release_search.wait(), timeout=3) + return {"ok": True, "stdout": "42", "stderr": ""} + if "click" in command: + observed.append((tuple(command), broker.get_state().user_intent)) + return {"ok": True, "stdout": "42", "stderr": ""} + + with ( + patch.object(input_router, "broker", broker), + patch.object(input_router, "run_async_command", side_effect=synthetic_command), + patch.object(input_router, "_require_active_session", return_value="/tmp/synthetic"), + patch.object(input_router, "append_input_event"), + patch.object(input_router, "append_trace_event"), + patch.object(input_router, "emit_operation_timing"), + ): + task = asyncio.create_task( + input_router.click_at( + ClickModel(x=1, y=1, window_title="Synthetic") + ) + ) + await asyncio.wait_for(admitted.wait(), timeout=3) + await broker.set_user_intent(UserIntent.STOP_NOW) + assert not await broker.check_access() + release_search.set() + try: + await asyncio.wait_for(task, timeout=3) + except HTTPException as exc: + status = exc.status_code + else: + status = 200 + + return observed, status + + observed, status = asyncio.run(exercise()) + assert status == 423 + assert observed == [] + + +def test_stop_now_between_key_window_lookup_and_dispatch_blocks_key_effect(): + from api.core.models import KeyModel + + async def exercise(): + entered_lookup = asyncio.Event() + resume_lookup = asyncio.Event() + effects = [] + broker = InputBroker() + broker.state.interactive = True + broker.state.control_mode = ControlMode.AGENT + broker.state.effective_control_mode = ControlPolicyMode.HYBRID + broker.state.user_intent = UserIntent.WAIT + broker.state.lease_expiry = time.time() + 60 + + async def lookup(command, **_kwargs): + if "search" in command: + entered_lookup.set() + await asyncio.wait_for(resume_lookup.wait(), timeout=3) + return {"ok": True, "stdout": "42", "stderr": ""} + + async def dispatch(**_kwargs): + effects.append("key-sent") + return {"ok": True, "backend": "xdotool"} + + with ( + patch.object(input_router, "broker", broker), + patch.object(input_router, "run_async_command", side_effect=lookup), + patch.object(input_router, "_send_keys", side_effect=dispatch), + patch.object(input_router, "_require_active_session", return_value="/tmp/synthetic"), + patch.object(input_router, "append_input_event"), + patch.object(input_router, "append_trace_event"), + patch.object(input_router, "emit_operation_timing"), + ): + task = asyncio.create_task( + input_router.key_press( + KeyModel(keys="F1", window_title="Synthetic", backend="xdotool") + ) + ) + await asyncio.wait_for(entered_lookup.wait(), timeout=3) + await broker.set_user_intent(UserIntent.STOP_NOW) + resume_lookup.set() + try: + await asyncio.wait_for(task, timeout=3) + except HTTPException as exc: + status = exc.status_code + else: + status = 200 + return status, effects + + status, effects = asyncio.run(exercise()) + assert status == 423 + assert effects == [] + + +def test_input_ticket_invalidates_on_session_handover_and_lease_expiry(): + async def exercise(): + broker = InputBroker() + broker.state.interactive = True + broker.state.control_mode = ControlMode.AGENT + broker.state.effective_control_mode = ControlPolicyMode.HYBRID + broker.state.lease_expiry = time.time() + 60 + ticket = await broker.issue_input_ticket() + assert ticket is not None + assert await broker.validate_input_ticket(ticket) + await broker.update_session("new-session", interactive=True) + assert not await broker.validate_input_ticket(ticket) + + broker.state.interactive = True + broker.state.control_mode = ControlMode.AGENT + broker.state.effective_control_mode = ControlPolicyMode.HYBRID + broker.state.lease_expiry = time.time() + 60 + new_ticket = await broker.issue_input_ticket() + assert new_ticket is not None + broker.state.lease_expiry = time.time() - 1 + assert not await broker.validate_input_ticket(new_ticket) + + asyncio.run(exercise()) + + +def test_stop_now_blocks_new_tickets_in_headless_and_agent_only(): + async def exercise(): + for mode in (ControlPolicyMode.HYBRID, ControlPolicyMode.AGENT_ONLY): + broker = InputBroker() + broker.state.interactive = False + broker.state.control_mode = ControlMode.AGENT + broker.state.effective_control_mode = mode + assert await broker.check_access() + initial = await broker.issue_input_ticket() + assert initial is not None + await broker.set_user_intent(UserIntent.STOP_NOW) + assert not await broker.check_access() + assert await broker.issue_input_ticket() is None + assert not await broker.validate_input_ticket(initial) + + asyncio.run(exercise())