diff --git a/.github/workflows/cre-wine11-oci-bridge.yml b/.github/workflows/cre-wine11-oci-bridge.yml new file mode 100644 index 00000000..4092aaa9 --- /dev/null +++ b/.github/workflows/cre-wine11-oci-bridge.yml @@ -0,0 +1,52 @@ +name: CRE x WineBot Wine 11 OCI Bridge Smoke + +on: + pull_request: + paths: + - '.github/workflows/cre-wine11-oci-bridge.yml' + - 'scripts/cre/**' + - 'docs/cre-wine11-oci-bridge.md' + +permissions: {} + +env: + DOCKER_BUILD_RECORD_UPLOAD: 'false' + +concurrency: + group: winebot-cre-bridge-${{ github.ref }} + cancel-in-progress: false + +defaults: + run: + shell: bash -euo pipefail {0} + +jobs: + smoke: + if: >- + github.event_name == 'pull_request' && + github.repository == 'SemperSupra/WineBot' && + github.event.pull_request.head.repo.full_name == github.repository + strategy: + fail-fast: false + matrix: + mode: [runtime, instrumented] + runs-on: ubuntu-24.04 + timeout-minutes: 45 + permissions: + contents: read + env: + CRE_SOURCE_SHA: ${{ github.event.pull_request.head.sha }} + steps: + - name: Checkout exact public source without retained credentials + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + - name: Reclaim disposable build space + run: sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /usr/share/swift + - name: Verify Python and shell syntax + run: | + python3 -B -c 'import ast; ast.parse(open("scripts/cre/sidecar_probe.py", encoding="utf-8").read())' + bash -n scripts/cre/qualify-oci-bridge.sh + - name: Build exact Wine 11 mode and exercise separate CRE-compatible sidecar + run: bash scripts/cre/qualify-oci-bridge.sh '${{ matrix.mode }}' diff --git a/api/routers/input.py b/api/routers/input.py index 85e46f33..1cf5ad75 100644 --- a/api/routers/input.py +++ b/api/routers/input.py @@ -257,37 +257,69 @@ async def _send_keys( script_id = uuid.uuid4().hex[:8] script_path = os.path.join(session_dir, "scripts", f"key_{script_id}.ahk") - os.makedirs(os.path.dirname(script_path), exist_ok=True) - script_lines = [ "#NoTrayIcon", "#NoEnv", "#SingleInstance Force", "SetKeyDelay, 20, 20", ] - # Prefer AHK native title matching (window_title) over X11 IDs. - # X11 window IDs from xdotool do not correspond to AHK HWNDs. - if window_title: + # Resolve a literal title to exactly one visible native HWND. Never let a + # failed target request degrade to Send on the current foreground window. + # An untyped window_id may belong to X11, so it is not a native selector. + if window_title is not None: + if ( + not window_title.strip() + or len(window_title) > 1024 + or any(ord(char) < 32 or ord(char) == 127 for char in window_title) + ): + return {"ok": False, "backend": "ahk", "error": "ahk_target_invalid", "stderr": ""} + # Encode title as data, not an AHK command parameter or selector. + # Chr expressions avoid AHK escape and selector interpretation. + title_expression = " . ".join(f"Chr({ord(char)})" for char in window_title) script_lines.extend([ - 'WinActivate, %s' % window_title, - 'WinWaitActive, %s,, 2' % window_title, - ]) - elif window_id: - hex_id = window_id - if window_id.startswith("0x"): - hex_id = window_id # already hex - script_lines.extend([ - "WinActivate, ahk_id %s" % hex_id, - "WinWaitActive, ahk_id %s,, 2" % hex_id, + f"requested := {title_expression}", + "target := 0", + "WinGet, matches, List", + "Loop, %matches%", + "{", + " candidate := matches%A_Index%", + " WinGetTitle, actualTitle, ahk_id %candidate%", + " if (InStr(actualTitle, requested, true) = 1)", + " {", + " if (target)", + " ExitApp, 42", + " target := candidate", + " }", + "}", + "if (!target)", + " ExitApp, 42", + "WinGet, targetPID, PID, ahk_id %target%", + "if (!targetPID)", + " ExitApp, 42", + "WinActivate, ahk_id %target%", + "WinWaitActive, ahk_id %target%,, 2", + "if (ErrorLevel)", + " ExitApp, 42", + "WinGet, currentPID, PID, ahk_id %target%", + "WinGetTitle, currentTitle, ahk_id %target%", + "if (currentPID != targetPID || InStr(currentTitle, requested, true) != 1)", + " ExitApp, 42", + 'if (!WinActive("ahk_id " . target))', + " ExitApp, 42", ]) + elif window_id is not None: + return {"ok": False, "backend": "ahk", "error": "ahk_native_title_required", "stderr": ""} script_lines.append("Send, %s" % ahk_keys) script_lines.append("ExitApp") - with open(script_path, "w") as f: + os.makedirs(os.path.dirname(script_path), exist_ok=True) + with open(script_path, "w", encoding="utf-8") as f: f.write("\n".join(script_lines) + "\n") cmd = ["ahk", to_wine_path(script_path)] result = safe_command(cmd, timeout=timeout) + if not result.get("ok") and result.get("exit_code") == 42: + return {"ok": False, "backend": "ahk", "error": "ahk_target_unresolved_or_inactive", "stderr": ""} return { "ok": result.get("ok", False), "backend": "ahk", diff --git a/docs/cre-wine11-oci-bridge.md b/docs/cre-wine11-oci-bridge.md new file mode 100644 index 00000000..b5cda060 --- /dev/null +++ b/docs/cre-wine11-oci-bridge.md @@ -0,0 +1,163 @@ +# CRE × WineBot 11 — OCI bridge smoke (R084) + +This is a source-exact, public-only cross-product **interface feasibility** test, +not a release of the private CRE runtime. It makes two separate, parallel +standard free-tier hosted builds from the same pinned WineHQ 11 WineBot source: +one ordinary runtime and one instrumented image. + +## Placement + +The WineBot target runs in its existing read-only, resource-limited Docker +container with six external synthetic fixture volumes. A **separate** CRE- +compatible probe runs as a container with only the WineBot internal session +network, UID/GID 1000, read-only root, all capabilities dropped, no privilege +escalation, capped memory/PIDs/CPU, and one role-specific API token per process. +It does not share WineBot state volumes, the Docker socket or host PID namespace. +An independent third container, with network disabled and a read-only fixture +volume, checks the actual saved Notepad data. + +The sidecar currently reuses the locally built WineBot OCI filesystem to avoid +a third, unpinned interpreter image. The Python probe is a narrowly scoped +public implementation of the **integration surface**, not the private CRE +workspace binary, a production CRE sidecar image, or a general debugger. +It does not add a competing scheduler, credential issuer or control broker. + +## What is exercised + +| Boundary | Runtime | Instrumented | +| --- | --- | --- | +| Exact source and passive winebot.runtime/1 discovery | Required | Required | +| Native Wine 11 Notepad GUI, granted brokered AHK keyboard and save | Required | Required | +| Observer-only credential and denied keyboard/trace mutation | Required | Required | +| Windows AHK hook keydown+keyup, independent of broker key-sent | Must be absent | Required | +| Operator toggle of Windows hook stop/start with readback | Disabled | Required | +| Disabled hook emits no fresh window key events during a distinct independently verified real GUI save | Not applicable | Required | +| Restarted hook emits fresh keydown/up during independently verified restoration of original text | Not applicable | Required | +| WinInspect observation capability discovery | 409 disabled | Not-installed, unverified | +| STOP_NOW, denied fresh grant/renewal and complete targeted edit/save, unchanged independent saved content | Required | Required | +| Still-running AHK sensor emits no fresh fixture-window keys during denied edit/save | Not applicable | Required | +| Independent persisted byte check from a network-none container | Required | Required | +| No host Docker socket, guest data mount, capabilities or writable root in the probe | Required | Required | + +The actual control action remains mediated by WineBot; the probe cannot bypass +the broker. The observer cannot actuate. Published logs use fixed stage markers; +credentials, screenshots, event payloads, process contents and private CRE +source are never published. Only disposable generated test volumes are removed. + +## What is *not* qualified + +The private CRE instrumented runtime is **not built or deployed** by this test. +The CRE workspace's frozen API 1.1 and cre.products/1 remain with their owner. +WinInspect v0.5.0/wire 0.4.0 is not admitted; no genuine WinInspect provider or +event feed is claimed. Dynamic watchpoint/GDB attachment to Wine internals, +Wine server/kernel/syscall and driver hooks, arbitrary vantage-point selection, +QEMU/VHE GPU/MMIO/DMA/IRQ, native WinBot oracle, independently authenticated +multi-actor control, hostile guest isolation, native assistive technology, +virtual-machine fidelity and physical hardware remain separate gates. + +For those deeper vantages, prefer a separately approved host or VM monitor +and typed least-authority relay; **do not** add Docker privileged mode, host +PID or SYS_PTRACE to the default target/observer just to make a test pass. +Linux containers isolate processes; they are not substitutes for a hypervisor +or a physical device probe. + +## Reproduction and custody + +The workflow at .github/workflows/cre-wine11-oci-bridge.yml is PR-only, +same-repository-only, and executes two mode jobs in parallel on public hosted +Ubuntu 24.04, each with a hard 45-minute timeout. The entrypoint is +scripts/cre/qualify-oci-bridge.sh; it checks exact commit identity, source +cleanliness and the unconditional R075 publication hold before any build. +A partial or stale receipt is never treated as success. + +The hook differential uses the existing Windows event timestamp filter and window scope. A separate network-none verifier checks the initial, disabled-sensor and final saved data; stale hook records cannot satisfy the restarted-sensor predicate. It does not establish arbitrary key fidelity, reliable capture of every transition, or synchronized remote clocks. + +Acceptance requires both actual built-mode CI jobs to pass (not merely syntax +checks), fixed independent sensor and actuator stage markers and byte readback. +New registry publication, hardware approval and protected-main merge are +forbidden. All eight pre-hardware gates remain open; status is +NOT_READY_FOR_HARDWARE_TEST. + +Authoritative handoffs: +- WineBot: https://github.com/mark-e-deyoung/winebot-research/issues/3 +- CRE: https://github.com/mark-e-deyoung/ghidra-tools/issues/4 +- WineBot owning delivery PR: https://github.com/SemperSupra/WineBot/pull/250 + +## R084 follow-on: positive retirement and engine-version checks + +The final `qualified` marker now requires independent actual `wine --version` +major 11 or later and successful Docker provider inventory **after** explicit +Compose teardown and removal of this run's six synthetic external volumes. +Exact pre-teardown Compose container IDs, the Compose project label, the unique +sidecar/verifier workcell label and names, and both expected network and volume +names must be absent from successful inventories. An inventory failure is a +failed qualification, not evidence of absence. Emergency cleanup remains best +effort on failure and cannot generate PASS. No global prune or deletion of +unrelated objects; this checks Docker-scoped retirement, not arbitrary host +process or hardware retirement. The verifier checks decoded fixture file text, +not a fixed encoding or byte-identical cross-platform file representation. + +## R084 follow-on: post-STOP denied-effect witness + +The independent verifier checks saved content immediately before STOP and +again after a complete denied targeted edit/save sequence. The synthetic +writer must receive refusal for renewal and for a fresh valid acknowledged +grant, followed by 423 for each key request; the session must still report +STOP, USER control and no lease. Instrumented mode also requires its previously +positive Windows hook to remain running and report no fresh fixture-window +keydown/up during the bounded denied sequence. The runtime mode checks saved +content and broker state, not independent absence of keyboard delivery. +This is a bounded same-session effect witness; it does not prove every +in-memory GUI state remained unchanged, all events were captured, the control +broker survives crashes, or arbitrary actors are isolated. + +## R084 follow-on: selectable application vantage + +The fixture now starts two actual Wine Notepad windows with separate synthetic +files. The restricted observer discovers both through the existing X11 +`/windows` inventory and requires disjoint nonempty numeric X11 identifiers. +The brokered writer selects the second title, checks both identities remain +observable, and edits/saves only that window. The network-none verifier checks +the second file changed and the original did not; both are checked again after +STOP. In instrumented mode the independent AHK hook must record fresh +keydown/up for the selected sibling and none for the original during the +bounded operation. Runtime does not claim independent Windows key sensing. +This correlates two application-level observation sources and independently +checked effects. X11 identifiers are not Windows HWNDs; title matching is not +a proof of arbitrary unique native targeting or capture of every event. +No private CRE runtime, new provider, system-call, debugger, VM or hardware +vantage is added. No identifiers, event payloads or fixture files are uploaded. + +## R084 follow-on: lease expiry and explicit recovery + +Before selecting the second window, renew the existing hybrid-control grant +for two seconds and wait for actual elapsed time. A complete targeted edit/save +must be denied with 423, renewal must be denied with 403, and the same session +must report USER control, no lease and WAIT rather than STOP. The independent +network-none verifier checks both original and sibling saved text unchanged. +Instrumented mode requires no fresh hook events for either fixture window +during the denied sequence while the hook remains active. A new acknowledged +challenge/grant must then succeed; the existing real sibling edit, hook pair +and independently verified saved contents establish recovery of useful +actuation before the separate STOP experiment. Runtime claims no independent +key sensing. This is a bounded same-session lease-expiry and recovery witness, +not durable authority across process crashes, concurrent actor isolation, or +arbitrary host/VM/device instrumentation. + +## R084 follow-on: unresolved target fail-closed witness + +While a valid acknowledged lease remains active and both positively exercised +fixture windows remain live, request a fixed nonexistent window title using +explicit X11 and AHK keyboard backends. A complete synthetic edit/save sequence +must receive target/dispatch refusal (not lease denial), and instrumented mode +must see no fresh fixture-window hook events. Independently verify both saved +texts unchanged even if a backend reports unexpected success. Fixed result +markers identify the backend and refusal/hook predicate without publishing +raw event or response data. An actual failure is a production-owner blocker, +not permission to relax this test or modify other workcells. X11 identifiers +and AHK title matching remain distinct; this does not prove arbitrary native +handle, stale-window race or in-flight cancellation behavior. + +### Unresolved-target failure containment + +The exact predecessor `61783783c388b4e6720a67f2fada80022c1611a5` failed the AHK missing-window refusal in both Wine 11 modes (public Actions run [46414370762](https://github.com/SemperSupra/WineBot/actions/runs/46414370762)). Instrumented AHK hook absence and independent sibling saved-content preservation also failed; xdotool refusal passed. This is a production actuator targeting defect, not permission to repair the actuator in this workcell. The negative assertions remain mandatory. The runner now attempts both independent readbacks, STOP and the same confirmed Docker retirement even after a missing-target failure. A successful STOP or retirement never turns an actuator/effect failure into qualification. Post-STOP content checks retain the original expected content; a pre-existing mismatch can therefore still fail them. This is failure-path evidence, not a production fix or arbitrary vantage integration. No raw evidence, registry push or bridge artifact upload. diff --git a/scripts/cre/qualify-oci-bridge.sh b/scripts/cre/qualify-oci-bridge.sh new file mode 100644 index 00000000..c934624a --- /dev/null +++ b/scripts/cre/qualify-oci-bridge.sh @@ -0,0 +1,272 @@ +#!/usr/bin/env bash +# Source-exact, public-only CRE-compatible OCI sidecar vs real WineBot GUI. +# Parallel mode selection is owned by the workflow matrix; no registry writes. +set -euo pipefail +export DOCKER_BUILD_RECORD_UPLOAD=false + +fail() { printf 'WINEBOT_CRE_BRIDGE mode=%s stage=%s result=fail\n' "${mode:-unknown}" "$1" >&2; exit 1; } +[[ $# == 1 ]] || fail invalid_arguments +mode=$1 +[[ $mode == runtime || $mode == instrumented ]] || fail invalid_mode +[[ ${GITHUB_ACTIONS:-} == true && ${GITHUB_EVENT_NAME:-} == pull_request ]] || fail public_pr_only +[[ ${GITHUB_RUN_ID:-} =~ ^[0-9]+$ && ${GITHUB_RUN_ATTEMPT:-} =~ ^[0-9]+$ ]] || fail missing_run_identity +source_sha=$(git rev-parse HEAD) +[[ $source_sha =~ ^[a-f0-9]{40}$ && $source_sha == "${CRE_SOURCE_SHA:-}" ]] || fail source_mismatch +git diff --quiet --exit-code || fail modified_source +[[ -f scripts/cre/sidecar_probe.py ]] || fail missing_probe +# A separate source owner gates every publication; smoke must never enable it. +if output=$(env GITHUB_EVENT_NAME=push GITHUB_REF=refs/heads/rdte/r066-installer-integrated-20261127 \ + bash scripts/ci/publish-candidate-images.sh 2>&1); then + fail publication_accepted +fi +[[ $output == 'WINE11_CANDIDATE stage=pre_hardware_admission_required result=fail' ]] || fail publication_guard_changed + +work=$(mktemp -d) +project="winebot-cre-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}-${mode}" +probe_name="${project}-sidecar" +verify_name="${project}-verifier" +workcell_label="org.winebot.cre.workcell=$project" +created_volumes=() +started=0 +cleanup() { + # Emergency cleanup only touches exact names owned by this run. + for owned_name in "$probe_name" "$verify_name"; do + if [[ $(docker inspect --type container --format '{{index .Config.Labels "org.winebot.cre.workcell"}}' "$owned_name" 2>/dev/null) == "$project" ]]; then + docker rm -f "$owned_name" >/dev/null 2>&1 || true + fi + done + if ((started)); then + docker compose -p "$project" -f compose/disposable.yml down --remove-orphans > /dev/null 2>&1 || true + fi + for volume in "${created_volumes[@]}"; do + docker volume rm "$volume" >/dev/null 2>&1 || true + done + rm -rf "$work" +} +trap cleanup EXIT + +# Use the same admitted public WineHQ 11 base and exact local source as the +# owning candidate workflow, but one mode per standard runner in parallel. +docker build --file docker/base.Dockerfile --target runtime \ + --tag winebot-base:cre-bridge . > "$work/base-build.log" 2>&1 || fail base_build +build_date=$(date -u +%Y-%m-%dT%H:%M:%SZ) +docker build --file docker/Dockerfile --target "intent-$mode" \ + --build-arg BASE_IMAGE=winebot-base:cre-bridge \ + --build-arg "VCS_REF=$source_sha" --build-arg "BUILD_DATE=$build_date" \ + --build-arg SOURCE_REPO=https://github.com/SemperSupra/WineBot \ + --tag "winebot:cre-bridge-$mode" . > "$work/mode-build.log" 2>&1 || fail mode_build +export WINEBOT_RUNTIME_IMAGE +WINEBOT_RUNTIME_IMAGE=$(docker image inspect --format '{{.Id}}' "winebot:cre-bridge-$mode") +[[ $WINEBOT_RUNTIME_IMAGE =~ ^sha256:[a-f0-9]{64}$ ]] || fail missing_local_image +export WINEBOT_RUNTIME_MODE="$mode" +export WINEBOT_API_TOKEN='cre-wine11-public-synthetic-writer' +export WINEBOT_API_READONLY_TOKEN='cre-wine11-public-synthetic-observer' +export WINEBOT_VNC_PASSWORD='cre-wine11-public-synthetic-vnc' +export WINEBOT_PREFIX_VOLUME="$project-prefix" +export WINEBOT_HOME_VOLUME="$project-home" +export WINEBOT_CONFIG_VOLUME="$project-config" +export WINEBOT_USERDATA_VOLUME="$project-userdata" +export WINEBOT_ARTIFACT_VOLUME="$project-artifacts" +export WINEBOT_SHARED_VOLUME="$project-shared" +volumes=("$WINEBOT_PREFIX_VOLUME" "$WINEBOT_HOME_VOLUME" "$WINEBOT_CONFIG_VOLUME" \ + "$WINEBOT_USERDATA_VOLUME" "$WINEBOT_ARTIFACT_VOLUME" "$WINEBOT_SHARED_VOLUME") +for volume in "${volumes[@]}"; do + if docker volume inspect "$volume" >/dev/null 2>&1; then fail occupied_volume; fi + docker volume create "$volume" >/dev/null || fail create_volume + created_volumes+=("$volume") +done +compose=(docker compose -p "$project" -f compose/disposable.yml) +"${compose[@]}" config --quiet >/dev/null 2>&1 || fail invalid_compose +started=1 +"${compose[@]}" up --no-build --detach --wait --wait-timeout 240 >"$work/start.log" 2>&1 || fail winebot_start +cid=$("${compose[@]}" ps -q winebot) +[[ -n $cid && $(docker inspect --format '{{.Image}}' "$cid") == "$WINEBOT_RUNTIME_IMAGE" ]] || fail wrong_target +[[ $(docker inspect --format '{{.HostConfig.ReadonlyRootfs}}' "$cid") == true ]] || fail writable_winebot +wine_version=$(timeout -k 3s 10s docker exec "$cid" wine --version 2>"$work/wine-version.log") || fail actual_wine_version +[[ $wine_version =~ ^wine-([0-9]+)\. ]] || fail actual_wine_version +(( BASH_REMATCH[1] >= 11 )) || fail actual_wine_below_11 +printf 'WINEBOT_CRE_BRIDGE mode=%s stage=actual_wine11plus result=pass\n' "$mode" +network="${project}_session" +[[ $(docker network inspect --format '{{.Internal}}' "$network") == true ]] || fail target_network_not_internal + +# A real Windows GUI application, not a mocked API. Do not emit raw app logs. +if ! timeout -k 5s 80s docker exec -i "$cid" python3 - >"$work/fixture.log" 2>&1 <<'PY' +import os +import subprocess +import time +from pathlib import Path + +for filename, seed in ( + ('cre-wine11-fixture.txt', 'seed\n'), + ('cre-wine11-sibling.txt', 'sibling seed\n'), +): + path = Path('/userdata') / filename + path.write_text(seed, encoding='utf-8') + with open(os.devnull, 'wb') as quiet: + subprocess.Popen(['wine', 'notepad.exe', 'Z:\\userdata\\' + filename], + stdout=quiet, stderr=quiet) + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + result = subprocess.run( + ['xdotool', 'search', '--onlyvisible', '--name', filename], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=3) + if result.returncode == 0: + break + time.sleep(0.2) + else: + raise AssertionError('notepad_missing') +print('CRE_FIXTURE_READY') +PY +then + fail original_gui_unavailable +fi +grep -Fxq 'CRE_FIXTURE_READY' "$work/fixture.log" || fail original_gui_unavailable +session=$(docker exec "$cid" sh -c 'basename "$(cat /tmp/winebot_current_session)"') || fail missing_session +[[ $session =~ ^[A-Za-z0-9_-]{1,95}$ ]] || fail invalid_session + +# Probe is a distinct locked-down container with a single API credential, +# no guest state/volume mounts, no Docker socket and no extra network. +run_sidecar() { + local phase=$1 role=$2 token log + case "$role" in + observer) token=$WINEBOT_API_READONLY_TOKEN ;; + operator) token=$WINEBOT_API_TOKEN ;; + *) fail invalid_probe_role ;; + esac + log="$work/$phase.log" + if ! timeout -k 5s 65s docker run --rm --name "$probe_name" \ + --network "$network" --label "$workcell_label" --user 1000:1000 \ + --read-only --cap-drop ALL --security-opt no-new-privileges:true \ + --pids-limit 32 --memory 128m --memory-swap 128m --cpus 0.5 \ + --mount "type=bind,src=$PWD/scripts/cre/sidecar_probe.py,dst=/cre-probe.py,readonly" \ + --env "CRE_FIXTURE_TOKEN=$token" --env "CRE_FIXTURE_SOURCE=$source_sha" \ + --env "CRE_FIXTURE_SESSION=$session" \ + --entrypoint python3 "$WINEBOT_RUNTIME_IMAGE" \ + -B /cre-probe.py "$mode" "$phase" >"$log" 2>&1; then + if [[ $phase == missing-target ]]; then + # Report only the fixed allowlisted result markers, never raw logs. + grep -E "^WINEBOT_CRE_BRIDGE mode=$mode check=missing_(xdotool|ahk)_(refusal|hook_absence) result=(pass|fail)$" "$log" || true + printf 'WINEBOT_CRE_BRIDGE mode=%s phase=missing-target result=fail\n' "$mode" + return 1 + fi + printf 'WINEBOT_CRE_BRIDGE mode=%s stage=%s_probe result=fail\n' "$mode" "$phase" >&2 + return 1 + fi + if [[ $phase == missing-target ]]; then + grep -E "^WINEBOT_CRE_BRIDGE mode=$mode check=missing_(xdotool|ahk)_(refusal|hook_absence) result=(pass|fail)$" "$log" || fail missing_target_receipt + fi + if ! grep -Fxq "WINEBOT_CRE_BRIDGE mode=$mode phase=$phase result=pass" "$log"; then + printf 'WINEBOT_CRE_BRIDGE mode=%s stage=%s_receipt result=fail\n' "$mode" "$phase" >&2 + return 1 + fi + printf 'WINEBOT_CRE_BRIDGE mode=%s phase=%s result=pass\n' "$mode" "$phase" +} + +# Independent read-only byte check in a THIRD container, outside WineBot and +# CRE, without API credentials, Docker socket, guest process namespace or net. +verify_saved() { + local expected=$1 stage=$2 filename=${3:-cre-wine11-fixture.txt} + case "$filename" in + cre-wine11-fixture.txt|cre-wine11-sibling.txt) ;; + *) fail invalid_verifier_fixture ;; + esac + if ! timeout -k 5s 35s docker run --rm --name "$verify_name" --label "$workcell_label" --network none --user 1000:1000 \ + --read-only --cap-drop ALL --security-opt no-new-privileges:true \ + --pids-limit 16 --memory 96m --memory-swap 96m --cpus 0.25 \ + --mount "type=volume,src=$WINEBOT_USERDATA_VOLUME,dst=/verify,readonly" \ + --env "CRE_EXPECTED_TEXT=$expected" --env "CRE_VERIFY_FILENAME=$filename" \ + --entrypoint python3 "$WINEBOT_RUNTIME_IMAGE" -B -c ' +import os +import time +from pathlib import Path +deadline = time.monotonic() + 8 +while True: + raw = (Path("/verify") / os.environ["CRE_VERIFY_FILENAME"]).read_bytes() + text = raw.decode("utf-16") if raw.startswith((b"\xff\xfe", b"\xfe\xff")) else raw.decode("utf-8-sig") + if text == os.environ["CRE_EXPECTED_TEXT"]: + break + assert time.monotonic() < deadline + time.sleep(0.2) +print("CRE_INDEPENDENT_BYTES_PASS") +' >"$work/verify.log" 2>&1; then + printf 'WINEBOT_CRE_BRIDGE mode=%s stage=%s result=fail\n' "$mode" "$stage" >&2 + return 1 + fi + if ! grep -Fxq 'CRE_INDEPENDENT_BYTES_PASS' "$work/verify.log"; then + printf 'WINEBOT_CRE_BRIDGE mode=%s stage=%s result=fail\n' "$mode" "$stage" >&2 + return 1 + fi + printf 'WINEBOT_CRE_BRIDGE mode=%s stage=%s result=pass\n' "$mode" "$stage" +} + +run_sidecar inventory observer +run_sidecar actuate operator +run_sidecar observe observer +verify_saved 'CRE WineBot source-exact actuator witness' initial_bytes +if [[ $mode == instrumented ]]; then + run_sidecar sensor-off operator + verify_saved 'CRE sensor disabled witness' disabled_sensor_bytes + run_sidecar sensor-on operator +fi +verify_saved 'CRE WineBot source-exact actuator witness' pre_stop_bytes +verify_saved $'sibling seed\n' sibling_seed cre-wine11-sibling.txt +# Expiry is distinct from explicit STOP: actual elapsed time, denied effect, +# independent state readback, then a fresh authorized grant and positive edit. +run_sidecar lease-expire operator +verify_saved 'CRE WineBot source-exact actuator witness' expired_original_unchanged +verify_saved $'sibling seed\n' expired_sibling_unchanged cre-wine11-sibling.txt +run_sidecar lease-regrant operator +run_sidecar target-pair operator +verify_saved 'CRE second window selected' sibling_selected cre-wine11-sibling.txt +verify_saved 'CRE WineBot source-exact actuator witness' original_unchanged +# Keep every missing-target assertion mandatory, but do not abandon STOP +# or confirmed retirement on the first independent mismatch. A failed +# assertion must remain a terminal non-qualification after cleanup. +missing_target_ok=1 +run_sidecar missing-target operator || missing_target_ok=0 +verify_saved 'CRE WineBot source-exact actuator witness' missing_target_original_unchanged || missing_target_ok=0 +verify_saved 'CRE second window selected' missing_target_sibling_unchanged cre-wine11-sibling.txt || missing_target_ok=0 +stop_ok=1 +run_sidecar stop operator || stop_ok=0 +verify_saved 'CRE WineBot source-exact actuator witness' independent_bytes || stop_ok=0 +verify_saved 'CRE second window selected' sibling_after_stop cre-wine11-sibling.txt || stop_ok=0 +[[ $(docker inspect --format '{{.State.OOMKilled}} {{.RestartCount}} {{.State.Running}}' "$cid") == 'false 0 true' ]] || fail target_died +# Do not declare qualification while cleanup is merely a best-effort EXIT +# trap. Require positive successful provider inventories and exact absence. +# This is Docker-scoped retirement only, not host/guest process attestation. +project_ids=$(docker ps -aq --no-trunc --filter "label=com.docker.compose.project=$project") || fail retirement_inventory_before +grep -Fxq -- "$cid" <<<"$project_ids" || fail retirement_missing_target +if ! "${compose[@]}" down --remove-orphans >"$work/down.log" 2>&1; then + fail retirement_compose_down +fi +started=0 +for volume in "${created_volumes[@]}"; do + docker volume rm "$volume" >>"$work/down.log" 2>&1 || fail retirement_volume_remove +done +all_ids=$(docker ps -aq --no-trunc) || fail retirement_container_inventory +while IFS= read -r owned_id; do + [[ -n $owned_id ]] || continue + if grep -Fxq -- "$owned_id" <<<"$all_ids"; then fail retirement_container_present; fi +done <<<"$project_ids" +compose_left=$(docker ps -aq --no-trunc --filter "label=com.docker.compose.project=$project") || fail retirement_compose_inventory +probe_left=$(docker ps -aq --no-trunc --filter "label=$workcell_label") || fail retirement_probe_inventory +[[ -z $compose_left && -z $probe_left ]] || fail retirement_owned_container_present +names=$(docker ps -a --format '{{.Names}}') || fail retirement_name_inventory +for owned_name in "$probe_name" "$verify_name"; do + if grep -Fxq -- "$owned_name" <<<"$names"; then fail retirement_named_container_present; fi +done +networks=$(docker network ls --format '{{.Name}}') || fail retirement_network_inventory +for owned_network in "$network" "${project}_front"; do + if grep -Fxq -- "$owned_network" <<<"$networks"; then fail retirement_network_present; fi +done +remaining_volumes=$(docker volume ls --format '{{.Name}}') || fail retirement_volume_inventory +for volume in "${created_volumes[@]}"; do + if grep -Fxq -- "$volume" <<<"$remaining_volumes"; then fail retirement_volume_present; fi +done +created_volumes=() +printf 'WINEBOT_CRE_BRIDGE mode=%s stage=retirement_confirmed_absent result=pass\n' "$mode" +# A cleanup success cannot promote a failed actuator or effect assertion. +((missing_target_ok)) || fail missing_target_refusal_or_observation +((stop_ok)) || fail stop_or_post_stop_effect +printf 'WINEBOT_CRE_BRIDGE mode=%s stage=qualified source=%s boundary=public-oci-interface-only result=pass\n' \ + "$mode" "$source_sha" diff --git a/scripts/cre/sidecar_probe.py b/scripts/cre/sidecar_probe.py new file mode 100644 index 00000000..12e2c42a --- /dev/null +++ b/scripts/cre/sidecar_probe.py @@ -0,0 +1,395 @@ +"""A public-safe CRE *interface* probe in a separate restricted OCI container. + +This is not the private CRE runtime. It deliberately exercises existing +WineBot sensors and the brokered actuator, rather than granting raw ptrace or +mounting the guest's prefix. Only fixed synthetic fixture operations exist. +""" + +import json +import os +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path + +MODE, PHASE = sys.argv[1:3] +SESSION = os.environ.get("CRE_FIXTURE_SESSION", "") +SOURCE = os.environ.get("CRE_FIXTURE_SOURCE", "") +TOKEN = os.environ.get("CRE_FIXTURE_TOKEN", "") +TEXT = "CRE WineBot source-exact actuator witness" +OFF_TEXT = "CRE sensor disabled witness" +WINDOW = "cre-wine11-fixture.txt" +SECOND_WINDOW = "cre-wine11-sibling.txt" +SECOND_TEXT = "CRE second window selected" +HOST = "http://winebot:8000" + + +def failed(kind, _value, _trace): + # Never print raw exception text, headers, target output or credential. + print(f"WINEBOT_CRE_BRIDGE mode={MODE} phase={PHASE} category={kind.__name__} result=fail", flush=True) + + +sys.excepthook = failed + + +def rpc(path, *, body=None, token=TOKEN): + headers = {"X-API-Key": token} if token else {} + payload = None + if body is not None: + headers["Content-Type"] = "application/json" + payload = json.dumps(body, separators=(",", ":")).encode("utf-8") + req = urllib.request.Request(HOST + path, data=payload, headers=headers) + try: + with urllib.request.urlopen(req, timeout=8) as response: + return response.status, json.loads(response.read(262144)) + except urllib.error.HTTPError as error: + return error.code, None + + +def assert_containment(): + assert os.getuid() == 1000 + assert Path("/proc/self/status").is_file() + status = Path("/proc/self/status").read_text(encoding="ascii") + assert "CapEff:\t0000000000000000" in status + assert "CapBnd:\t0000000000000000" in status + assert os.statvfs("/").f_flag & os.ST_RDONLY + assert not Path("/var/run/docker.sock").exists() + assert not Path("/wineprefix/system.reg").exists() + assert not Path("/userdata/cre-wine11-fixture.txt").exists() + assert "API_TOKEN" not in os.environ + assert "API_READONLY_TOKEN" not in os.environ + + +def fixed_discovery(): + status, data = rpc("/health/runtime") + assert status == 200 and data["contract"] == "winebot.runtime/1" + assert data["mode"] == MODE and data["source_revision"] == SOURCE + assert data["release_channel"] == "candidate" + assert data["wininspect"]["installed"] is False + assert data["wininspect"]["wire_compatible"] is False + assert data["wininspect"]["event_delivery"] == "unverified" + assert data["wininspect"]["state"] == ("not-installed" if MODE == "instrumented" else "disabled") + if MODE == "runtime": + assert data["sensors"]["input_trace"] == "disabled" + assert data["sensors"]["recording"] == "disabled" + assert rpc("/health/runtime", token="")[0] in (401, 403) + status, capabilities = rpc("/observation/capabilities") + if MODE == "runtime": + assert status == 409 + else: + assert status == 200 and capabilities["contract"] == "winebot.observation/1" + assert capabilities["actuation_authority"] is False + assert capabilities["event_delivery"] == "unverified" + assert capabilities["provider"]["wire_compatible"] is False + + +def wait_trace(expected): + deadline = time.monotonic() + 6 + while time.monotonic() < deadline: + status, trace = rpc("/input/trace/windows/status") + assert status == 200 + if trace["running"] is expected: + return trace + time.sleep(0.2) + raise AssertionError("trace_state") + + +def run_actuator(): + assert rpc(f"/sessions/{SESSION}/control")[0] == 200 + code, challenge = rpc(f"/sessions/{SESSION}/control/challenge", body={}) + assert code == 200 and isinstance(challenge["token"], str) + code, _ = rpc(f"/sessions/{SESSION}/control/grant", body={ + "lease_seconds": 60, "user_ack": True, + "challenge_token": challenge["token"], + }) + assert code == 200 + send_text(TEXT) + + +def send_text(text, window=WINDOW): + for key in ("ctrl+a", text, "ctrl+s"): + code, result = rpc("/input/key", body={ + "keys": key, "window_title": window, "backend": "ahk", + }) + assert code == 200 and result["backend"] == "ahk" + time.sleep(0.2) + + +def read_sensor(): + assert rpc("/input/key", body={"keys": "must-not-arrive"})[0] == 403 + assert rpc("/input/trace/windows/start", body={"backend": "ahk"})[0] == 403 + deadline = time.monotonic() + 8 + while True: + code, events = rpc("/input/events?source=windows&limit=200") + assert code == 200 and isinstance(events["events"], list) + observed = { + item.get("event") for item in events["events"] + if item.get("tool") == "ahk_hook" and WINDOW in item.get("window_title", "") + } + if MODE == "runtime": + assert not observed + assert wait_trace(False)["running"] is False + return + if {"keydown", "keyup"} <= observed: + assert wait_trace(True)["backend"] == "ahk" + return + assert time.monotonic() < deadline + time.sleep(0.2) + + +def fresh_window_events(since_ms, window=WINDOW): + code, response = rpc(f"/input/events?source=windows&limit=200&since_epoch_ms={since_ms}") + assert code == 200 and isinstance(response["events"], list) + return { + item["event"] + for item in response["events"] + if item.get("tool") == "ahk_hook" + and window in item.get("window_title", "") + and item.get("event") in {"keydown", "keyup"} + and type(item.get("timestamp_epoch_ms")) is int + and item["timestamp_epoch_ms"] >= since_ms + } + + +def sensor_off(): + assert MODE == "instrumented" + assert wait_trace(True)["running"] is True + code, response = rpc("/input/trace/windows/stop", body={}) + assert code == 200 and response["status"] == "stopped" + assert wait_trace(False)["running"] is False + # Allow the terminating sampler to drain. The independent verifier checks + # that the intervening real GUI save changed bytes, not just API status. + time.sleep(0.5) + since = time.time_ns() // 1_000_000 + send_text(OFF_TEXT) + deadline = time.monotonic() + 1.5 + while time.monotonic() < deadline: + assert not fresh_window_events(since), "disabled_sensor_emitted_fresh_key_event" + time.sleep(0.2) + assert wait_trace(False)["running"] is False + + +def sensor_on(): + assert MODE == "instrumented" + assert wait_trace(False)["running"] is False + code, response = rpc("/input/trace/windows/start", body={"backend": "ahk"}) + assert code == 200 and response["status"] == "started" + assert wait_trace(True)["backend"] == "ahk" + # A running PID is not enough: fresh, time-bounded events for this window + # must be observed after a second real, independently verified GUI save. + time.sleep(0.5) + since = time.time_ns() // 1_000_000 + send_text(TEXT) + deadline = time.monotonic() + 8 + while not {"keydown", "keyup"} <= fresh_window_events(since): + assert time.monotonic() < deadline, "restored_sensor_missing_fresh_key_pair" + time.sleep(0.2) + + +def inventory_pair(): + # X11 inventory is a distinct producer from the Windows AHK hook. + code, response = rpc("/windows") + assert code == 200 and isinstance(response["windows"], list) + assert response["count"] == len(response["windows"]) + result = {} + for title in (WINDOW, SECOND_WINDOW): + ids = { + item["id"] + for item in response["windows"] + if title in item.get("title", "") + and isinstance(item.get("id"), str) + and item["id"].isdigit() + } + assert ids, "fixture_x11_window_missing" + result[title] = ids + assert result[WINDOW].isdisjoint(result[SECOND_WINDOW]), "ambiguous_window_identity" + return result + + +def lease_expire(): + control = f"/sessions/{SESSION}/control" + code, state = rpc(control) + assert code == 200 and state["control_mode"] == "AGENT" + assert state["lease_expiry"] is not None and state["user_intent"] == "WAIT" + assert rpc(control + "/renew", body={"lease_seconds": 2})[0] == 200 + code, state = rpc(control) + assert code == 200 and state["control_mode"] == "AGENT" + assert state["lease_expiry"] is not None + if MODE == "instrumented": + assert wait_trace(True)["backend"] == "ahk" + # Wait past the renewed duration, without a synthetic clock or STOP. + time.sleep(2.5) + since = time.time_ns() // 1_000_000 + for key in ("ctrl+a", "CRE expired lease forbidden edit", "ctrl+s"): + code, _ = rpc("/input/key", body={ + "keys": key, "window_title": WINDOW, "backend": "ahk", + }) + assert code == 423, "expired_lease_input_admitted" + time.sleep(0.2) + assert rpc(control + "/renew", body={"lease_seconds": 60})[0] == 403 + code, state = rpc(control) + assert code == 200 and state["session_id"] == SESSION + assert state["user_intent"] == "WAIT", "expiry_conflated_with_stop" + assert state["control_mode"] == "USER" and state["lease_expiry"] is None + if MODE == "instrumented": + deadline = time.monotonic() + 2 + while time.monotonic() < deadline: + assert not fresh_window_events(since, WINDOW), "expired_lease_emitted_original_keys" + assert not fresh_window_events(since, SECOND_WINDOW), "expired_lease_emitted_sibling_keys" + time.sleep(0.2) + assert wait_trace(True)["backend"] == "ahk" + + +def lease_regrant(): + control = f"/sessions/{SESSION}/control" + code, state = rpc(control) + assert code == 200 and state["control_mode"] == "USER" + assert state["user_intent"] == "WAIT" and state["lease_expiry"] is None + code, challenge = rpc(control + "/challenge", body={}) + assert code == 200 and isinstance(challenge["token"], str) + assert rpc(control + "/grant", body={ + "lease_seconds": 60, "user_ack": True, + "challenge_token": challenge["token"], + })[0] == 200 + code, state = rpc(control) + assert code == 200 and state["session_id"] == SESSION + assert state["control_mode"] == "AGENT" and state["lease_expiry"] is not None + + +def target_pair(): + before = inventory_pair() + if MODE == "instrumented": + assert wait_trace(True)["backend"] == "ahk" + time.sleep(0.5) + since = time.time_ns() // 1_000_000 + send_text(SECOND_TEXT, window=SECOND_WINDOW) + after = inventory_pair() + for title in (WINDOW, SECOND_WINDOW): + assert before[title] & after[title], "fixture_window_identity_changed" + if MODE == "instrumented": + deadline = time.monotonic() + 8 + while True: + assert not fresh_window_events(since, WINDOW), "sibling_edit_reached_original" + if {"keydown", "keyup"} <= fresh_window_events(since, SECOND_WINDOW): + break + assert time.monotonic() < deadline, "sibling_hook_missing_fresh_key_pair" + time.sleep(0.2) + assert wait_trace(True)["backend"] == "ahk" + + +def missing_target(): + # A valid lease is deliberately present: policy denial would not prove + # fail-closed target resolution. The two live windows are positive controls. + control = f"/sessions/{SESSION}/control" + code, state = rpc(control) + assert code == 200 and state["control_mode"] == "AGENT" + assert state["user_intent"] == "WAIT" and state["lease_expiry"] is not None + before = inventory_pair() + absent = "CRE synthetic nonexistent window 84" + code, listing = rpc("/windows") + assert code == 200 + assert not any(absent in item.get("title", "") for item in listing["windows"]) + if MODE == "instrumented": + assert wait_trace(True)["backend"] == "ahk" + problems = False + for backend in ("xdotool", "ahk"): + time.sleep(0.5) + since = time.time_ns() // 1_000_000 + # Fixed harmless synthetic edit/save; xdotool and AHK both accept x. + # No request uses an actual valid target title or native handle. + statuses = [] + for key in ("ctrl+a", "x", "ctrl+s"): + code, _ = rpc("/input/key", body={ + "keys": key, "window_title": absent, "backend": backend, + }) + statuses.append(code) + refused = all(code in (400, 404, 409, 422, 500) for code in statuses) + outcome = "pass" if refused else "fail" + print(f"WINEBOT_CRE_BRIDGE mode={MODE} check=missing_{backend}_refusal result={outcome}", flush=True) + problems = problems or not refused + if MODE == "instrumented": + fresh = False + deadline = time.monotonic() + 2 + while time.monotonic() < deadline: + fresh = fresh or bool(fresh_window_events(since, WINDOW) | fresh_window_events(since, SECOND_WINDOW)) + time.sleep(0.2) + assert wait_trace(True)["backend"] == "ahk" + outcome = "fail" if fresh else "pass" + print(f"WINEBOT_CRE_BRIDGE mode={MODE} check=missing_{backend}_hook_absence result={outcome}", flush=True) + problems = problems or fresh + after = inventory_pair() + assert all(before[title] & after[title] for title in (WINDOW, SECOND_WINDOW)) + code, state = rpc(control) + assert code == 200 and state["control_mode"] == "AGENT" + assert state["lease_expiry"] is not None and state["user_intent"] == "WAIT" + assert not problems, "unresolved_target_refusal_or_sensor_failure" + + +def stop_and_deny(): + control = f"/sessions/{SESSION}/control" + code, _ = rpc(f"/sessions/{SESSION}/user_intent", body={"intent": "STOP_NOW"}) + assert code == 200 + if MODE == "instrumented": + # An absent hook event is meaningful only if the known active sensor + # remains running. The preceding sensor-on phase proves fresh delivery. + assert wait_trace(True)["backend"] == "ahk" + time.sleep(0.5) + since = time.time_ns() // 1_000_000 + # The synthetic operator has a writer credential but STOP must prohibit + # renewing and even a fresh valid acknowledged grant. + assert rpc(control + "/renew", body={"lease_seconds": 60})[0] == 403 + code, challenge = rpc(control + "/challenge", body={}) + assert code == 200 and isinstance(challenge["token"], str) + code, _ = rpc(control + "/grant", body={ + "lease_seconds": 60, "user_ack": True, + "challenge_token": challenge["token"], + }) + assert code == 403 + # Attempt a whole edit/save against the same positively qualified target, + # rather than an untargeted single key that might not change saved data. + for key in ("ctrl+a", "CRE STOP forbidden edit", "ctrl+s"): + code, _ = rpc("/input/key", body={ + "keys": key, "window_title": WINDOW, "backend": "ahk", + }) + assert code == 423 + code, state = rpc(control) + assert code == 200 and state["session_id"] == SESSION + assert state["user_intent"] == "STOP_NOW" + assert state["control_mode"] == "USER" and state["lease_expiry"] is None + if MODE == "instrumented": + deadline = time.monotonic() + 2 + while time.monotonic() < deadline: + assert not fresh_window_events(since), "denied_edit_emitted_fresh_key_event" + time.sleep(0.2) + assert wait_trace(True)["backend"] == "ahk" + + +assert MODE in ("runtime", "instrumented") +assert PHASE in ("actuate", "observe", "inventory", "sensor-off", "sensor-on", "lease-expire", "lease-regrant", "target-pair", "missing-target", "stop") +assert len(SOURCE) == 40 and all(c in "0123456789abcdef" for c in SOURCE) +assert SESSION and len(SESSION) < 96 and all(c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-" for c in SESSION) +assert TOKEN and len(TOKEN) < 512 +assert_containment() +fixed_discovery() +if PHASE == "actuate": + run_actuator() +elif PHASE == "observe": + read_sensor() +elif PHASE == "inventory": + inventory_pair() +elif PHASE == "lease-expire": + lease_expire() +elif PHASE == "lease-regrant": + lease_regrant() +elif PHASE == "target-pair": + target_pair() +elif PHASE == "missing-target": + missing_target() +elif PHASE == "sensor-off": + sensor_off() +elif PHASE == "sensor-on": + sensor_on() +else: + stop_and_deny() +print(f"WINEBOT_CRE_BRIDGE mode={MODE} phase={PHASE} result=pass", flush=True) diff --git a/tests/test_input_keyboard_conformance.py b/tests/test_input_keyboard_conformance.py index e8ed03af..47f2ad4b 100644 --- a/tests/test_input_keyboard_conformance.py +++ b/tests/test_input_keyboard_conformance.py @@ -337,3 +337,76 @@ def test_xdotool_delivery_mode_not_silently_changed(window_id, expected): ) assert result["ok"] is True command.assert_awaited_once_with(expected, timeout=2) + + +@pytest.mark.parametrize("title,window_id,error", [ + ("", None, "ahk_target_invalid"), + (" \t", None, "ahk_target_invalid"), + ("bad\nline", None, "ahk_target_invalid"), + ("x" * 1025, None, "ahk_target_invalid"), + (None, "12345", "ahk_native_title_required"), + (None, "0x1234", "ahk_native_title_required"), +]) +def test_ahk_rejects_invalid_or_untyped_target_without_dispatch( + title, window_id, error, tmp_path +): + import asyncio + + from api.routers.input import _send_keys + + with patch("api.routers.input.safe_command") as command: + result = asyncio.run( + _send_keys("z", window_id, title, "ahk", str(tmp_path), 2) + ) + assert result == {"ok": False, "backend": "ahk", "error": error, "stderr": ""} + command.assert_not_called() + assert not list(tmp_path.iterdir()) + + +def test_ahk_target_guard_precedes_send_and_propagates_refusal(tmp_path): + import asyncio + + from api.routers.input import _send_keys + + with patch("api.routers.input.to_wine_path", side_effect=lambda path: path), patch( + "api.routers.input.safe_command", + return_value={"ok": False, "exit_code": 42, "stderr": "untrusted diagnostic"}, + ) as command: + result = asyncio.run( + _send_keys("z", "12345", 'A,% ahk_id "x"', "ahk", str(tmp_path), 4) + ) + assert result == { + "ok": False, + "backend": "ahk", + "error": "ahk_target_unresolved_or_inactive", + "stderr": "", + } + script, = (tmp_path / "scripts").glob("*.ahk") + source = script.read_text(encoding="utf-8") + assert 'A,% ahk_id "x"' not in source + assert "requested := Chr(65) . Chr(44) . Chr(37)" in source + assert "WinGet, matches, List" in source + assert "if (target)\n ExitApp, 42" in source + assert "if (!target)\n ExitApp, 42" in source + assert "WinWaitActive, ahk_id %target%,, 2\nif (ErrorLevel)\n ExitApp, 42" in source + assert "currentPID != targetPID" in source + assert source.index('if (!WinActive("ahk_id " . target))') < source.index("Send, z") + assert source.count("Send, z") == 1 + command.assert_called_once_with(["ahk", str(script)], timeout=4) + + +def test_ahk_intentional_untargeted_input_remains_distinct(tmp_path): + import asyncio + + from api.routers.input import _send_keys + + with patch("api.routers.input.to_wine_path", side_effect=lambda path: path), patch( + "api.routers.input.safe_command", return_value={"ok": True}, + ): + result = asyncio.run( + _send_keys("z", None, None, "ahk", str(tmp_path), 2) + ) + assert result["ok"] is True + script, = (tmp_path / "scripts").glob("*.ahk") + source = script.read_text(encoding="utf-8") + assert "WinActivate" not in source and "Send, z" in source