diff --git a/.github/workflows/desktop-replay.yml b/.github/workflows/desktop-replay.yml index 0b10d9f25b..f1424c7cc0 100644 --- a/.github/workflows/desktop-replay.yml +++ b/.github/workflows/desktop-replay.yml @@ -32,6 +32,7 @@ on: - packages/flow/tests/e2e/test_windows_hosted_replay.py - packages/flow/tests/e2e/test_native_keyboard_lease.py - packages/flow/tests/e2e/test_windows_hosted_governed.py + - packages/flow/tests/e2e/test_windows_qualification_campaign.py - packages/flow/tests/_approver_keys.py - packages/flow/tests/conftest.py - packages/flow/tests/e2e/conftest.py @@ -241,6 +242,22 @@ jobs: echo "governed step outcome: $GOVERNED_OUTCOME" python ../../scripts/ci/check_windows_governed_safety.py \ "$RUNNER_TEMP/windows-governed-evidence.json" + - name: Qualify native Windows with real faults and complete record read-back + env: + OAFLOW_WINDOWS_HOSTED_E2E: "1" + OAFLOW_WINDOWS_QUALIFICATION_EVIDENCE: ${{ runner.temp }}/windows-qualification-evidence.json + run: | + pytest -v -rs -p no:cacheprovider --basetemp="$RUNNER_TEMP/wq" \ + tests/e2e/test_windows_qualification_campaign.py --junitxml=runs/windows-qualification-junit.xml + python - <<'PYCODE' + import json, os + import xml.etree.ElementTree as ET + cases = list(ET.parse("runs/windows-qualification-junit.xml").getroot().iter("testcase")) + assert len(cases) == 1 and not any(c.find(tag) is not None for c in cases for tag in ("skipped", "failure", "error")) + evidence = json.load(open(os.environ["OAFLOW_WINDOWS_QUALIFICATION_EVIDENCE"])) + assert evidence["completed"] and len(evidence["result"]["cases"]) == 18 and evidence["admission_verified"] + assert all(case["passed"] for case in evidence["result"]["cases"]) + PYCODE - name: Keep the evidence if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -249,6 +266,11 @@ jobs: path: | ${{ runner.temp }}/windows-replay-evidence.json ${{ runner.temp }}/windows-governed-evidence.json + ${{ runner.temp }}/windows-qualification-evidence.json + ${{ runner.temp }}/wq/**/report.json + ${{ runner.temp }}/wq/**/result.json + ${{ runner.temp }}/wq/**/agent.log + ${{ runner.temp }}/wq/**/*.png ${{ runner.temp }}/nkl-editable/*.json ${{ runner.temp }}/nkl-editable/*.xml ${{ runner.temp }}/nkl-editable/*.log diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 046a342325..259e07b4c3 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -265,6 +265,7 @@ improvising or retrying when something is off. | Citrix from outside the session, pixels only (`remote_display`), the fallback when nothing can be installed inside | Exploratory | A Citrix stand-in with no DOM: 3 healthy runs, 3 stops on drift | [LIMITS.md](packages/flow/docs/LIMITS.md) | | Chain programs across surfaces, passing confirmed values | Released | Synthetic | `openadapt-flow compose`, `process`; [PROCESS_CONTRACT.md](packages/flow/docs/PROCESS_CONTRACT.md) | | One program that switches surfaces, tabs and popups mid-run | Released ([#1197](https://github.com/OpenAdaptAI/OpenAdapt/pull/1197)) | Real Chromium; Windows switch on a mock | [#1197](https://github.com/OpenAdaptAI/OpenAdapt/pull/1197) | +| Qualify a native Windows program with the normal case and five faults through an opt-in authenticated agent; bind the observed executable and machine/OS environment and judge declared inserts or field updates from complete record snapshots | In this change | Synthetic unit and transport tests; real Windows campaign evidence required before release | `qualify/windows.py`, `qualify/record_oracle.py`, [QUALIFY_A_WORKFLOW.md](packages/flow/docs/QUALIFY_A_WORKFLOW.md) | | Record and replay native or listed browser choices using one generic contract; require one enabled semantic match and exact committed-field read-back, and refuse unmapped held-out labels before selection; retain browser dialog answers with producer-document and dialog-kind checks | Experimental, PR [#2295](https://github.com/OpenAdaptAI/OpenAdapt/pull/2295) | Synthetic Chromium fixtures cover native, ARIA, plain lists, searchable libraries, asynchronous options, cascades and calendars; historical measurement SHAs and configurations are listed separately. Real-app evidence is partial: OpenEMR native choices read back, and OpenMRS relationship choices recorded/compiled; neither completed a verified save because an existing identity guard stopped the run. Governed receipt-bound choices refuse before input. | [CHOICES.md](packages/flow/docs/CHOICES.md), [benchmark/choice_widgets](packages/flow/benchmark/choice_widgets/README.md) | | Halt when a workflow qualified with page structure runs on a pixels-only surface | Released | Synthetic | `openadapt-flow qualify` | | Stop before acting when another shown row has the same identity; when the rows carry an app-owned record id (a `data-*` id, the row link), act on the row with the recorded id; on a surface that cannot count the rows, stop before any step that leads into a write | Released ([#1504](https://github.com/OpenAdaptAI/OpenAdapt/pull/1504)) | Real browser (headless Chromium worklist with identical rows) | `runtime/identity_census.py`; `PlaywrightBackend.identity_candidates_at` | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 4fa9618bc4..cebf37efa5 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -17,6 +17,17 @@ ## Unreleased +### Native Windows qualification + +- Native Windows qualification campaigns use the observed Windows environment + and opt-in, authenticated UIA/physical fault staging. Fault overlays are + bounded, have no application write handlers and are cleaned up after trials. + This keeps the existing machine/OS qualification binding; it does not make + admissions portable across fresh workers. +- Qualification read-back checks complete before/after row multisets for + inserts and declared field updates. A changed sibling, extra or missing + row, duplicate row, undeclared field change or unavailable read refuses. + ### Encryption at rest by default - Recordings (web, the quickstart and tutorial, and desktop once converted), diff --git a/packages/flow/docs/LIMITS.md b/packages/flow/docs/LIMITS.md index 12e12611c4..97bc717116 100644 --- a/packages/flow/docs/LIMITS.md +++ b/packages/flow/docs/LIMITS.md @@ -14,6 +14,17 @@ For the current evidence behind each capability claim, see [`VERIFICATION.md`](VERIFICATION.md). For the package-wide evidence map, see [`PRODUCT_STATUS.md`](PRODUCT_STATUS.md). +## Native Windows qualification campaigns + +`qualify` can run the normal case and five faults through a native Windows +session hook with an authenticated, explicitly enabled fault agent. The native +screen mutations currently support buttons with an AutomationId or exact +role/name; other controls refuse. RDP and Citrix campaign fault staging is +separate and remains unavailable. The executable, machine and exact OS build +are part of the qualification boundary, so this does not qualify arbitrary +fresh workers. A script-hosted application's own code is covered by its +declared version, not the host executable's hash. + ## Validated on Every published result used synthetic patients, claims and records. diff --git a/packages/flow/docs/QUALIFY_A_WORKFLOW.md b/packages/flow/docs/QUALIFY_A_WORKFLOW.md index 5577f5d6c2..4d4e339b71 100644 --- a/packages/flow/docs/QUALIFY_A_WORKFLOW.md +++ b/packages/flow/docs/QUALIFY_A_WORKFLOW.md @@ -300,11 +300,28 @@ certified bundle once, as the runner would, into `runs/qual-1/certified-run/`. ## Limits -- Web only today. The ambiguity, wrong-identity and stale-identity faults are - staged in the browser, on the save button the bundle's own selector finds. - A fault driver for pixel surfaces (Windows, RDP, Citrix) is the next piece; - until it exists, `qualify` refuses `app.target` other than `web`. The two - effect faults do not depend on the surface. +- Browser campaigns stage screen faults on the save control's page. Native + Windows campaigns (`app.target: windows`) use an authenticated in-guest + agent started with `--allow-qualification-faults`, plus `app.session` to + return its backend. The save needs an AutomationId or exact role/name; + the native driver currently supports buttons. Its own temporary WinForms + overlays add real duplicate UIA targets, change the identity at the save, + or cover the surface after identity verification. Ordinary UIA and frame + reads must observe the change before the driver signs it. The overlays have + no save handlers, expire after three minutes and are removed after each run. + The routes are absent unless explicitly enabled and require authentication. + RDP, Citrix, macOS and Linux campaign screen faults remain unsupported. +- A native campaign binds the observed executable digest and the exact + machine/OS environment. A fresh Windows installation or an OS update needs + another qualification; this does not grant an admission to arbitrary EC2 + workers. For an app hosted by a script interpreter or shared runtime, the + executable digest covers the host. The declared application version must + be updated and qualified again when the application's own code changes. +- Independent record snapshots cover inserts and declared field updates. + Inserts may add only the selected rows; updates may change only their named + fields on uniquely selected existing rows. All other rows, fields and row + multiplicities must remain identical. An unreadable after-snapshot is + indeterminate, including when the before-snapshot was empty. - A web workflow can't yet be qualified for a remote-display surface. With `app.surface: remote_display` the cases run with structure lookups off, and the browser delivers a click only through an action bound to the page diff --git a/packages/flow/openadapt_flow/backends/win_agent/qualification_faults.py b/packages/flow/openadapt_flow/backends/win_agent/qualification_faults.py new file mode 100644 index 0000000000..d9c2aa9b9f --- /dev/null +++ b/packages/flow/openadapt_flow/backends/win_agent/qualification_faults.py @@ -0,0 +1,342 @@ +"""Opt-in native qualification overlays, with read-back and bounded lifetime. + +The helper only paints test controls. It never sends input to the application +or changes what UI Automation returns. Every mutation must be observed through +the ordinary UIA and screenshot paths before a receipt is returned. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import subprocess +import time +import uuid +from typing import Any, Callable + +# Fixed program, supplied with JSON through stdin. No client string is compiled +# as PowerShell. The form does not activate: the application/session observation +# stays the one being tested. Its buttons have no input handlers or save path. +_OVERLAY_PS = r""" +$ErrorActionPreference = 'Stop' +Add-Type -AssemblyName System.Windows.Forms +Add-Type -AssemblyName System.Drawing +Add-Type -ReferencedAssemblies System.Windows.Forms -TypeDefinition @' +using System.Windows.Forms; +public class QualificationOverlay : Form { + protected override bool ShowWithoutActivation { get { return true; } } + protected override CreateParams CreateParams { + get { var cp = base.CreateParams; cp.ExStyle |= 0x08000000; return cp; } + } +} +'@ +[Console]::InputEncoding = [Text.Encoding]::UTF8 +$c = [Console]::In.ReadToEnd() | ConvertFrom-Json +$f = New-Object QualificationOverlay +$f.FormBorderStyle = 'None' +$f.ShowInTaskbar = $false +$f.StartPosition = 'Manual' +$f.TopMost = $true +$f.Text = [string]$c.window_name +$f.BackColor = [Drawing.Color]::White +$x = [int]$c.bounds[0]; $y = [int]$c.bounds[1] +$w = [Math]::Max(120, [int]$c.bounds[2] - $x) +$h = [Math]::Max(40, [int]$c.bounds[3] - $y) +if ($c.kind -eq 'stale_identity') { + $f.Bounds = [Windows.Forms.SystemInformation]::VirtualScreen + $l = New-Object Windows.Forms.Label + $l.Name = 'qualification-stale-surface' + $l.AccessibleName = 'Qualification stale surface' + $l.Dock = 'Fill' + $l.BackColor = [Drawing.Color]::White + $f.Controls.Add($l) +} else { + $f.Location = New-Object Drawing.Point($x, $y) + $f.Size = New-Object Drawing.Size($w, ($h * 2)) + if ($c.kind -eq 'ambiguity') { + foreach ($i in 0, 1) { + $b = New-Object Windows.Forms.Button + $b.Name = [string]$c.automation_id + $b.AccessibleName = [string]$c.name + $b.Text = [string]$c.name + $b.Location = New-Object Drawing.Point(0, ($i * $h)) + $b.Size = New-Object Drawing.Size($w, $h) + $f.Controls.Add($b) + } + } else { + $left = $x; $top = $y + if ($null -ne $c.identity_bounds) { + $left = [Math]::Min($left, [int]$c.identity_bounds[0]) + $top = [Math]::Min($top, [int]$c.identity_bounds[1]) + $right = [Math]::Max($x + $w, [int]$c.identity_bounds[2]) + $bottom = [Math]::Max($y + $h, [int]$c.identity_bounds[3]) + $f.Location = New-Object Drawing.Point($left, $top) + $f.Size = New-Object Drawing.Size(($right - $left), ($bottom - $top)) + $identity = New-Object Windows.Forms.Label + $identity.Name = 'qualification-altered-identity' + $identity.Text = 'Different record 8675309 2040-12-31' + $identity.AccessibleName = $identity.Text + $identity.Location = New-Object Drawing.Point(([int]$c.identity_bounds[0] - $left), ([int]$c.identity_bounds[1] - $top)) + $identity.Size = New-Object Drawing.Size(([int]$c.identity_bounds[2] - [int]$c.identity_bounds[0]), ([int]$c.identity_bounds[3] - [int]$c.identity_bounds[1])) + $identity.Font = New-Object Drawing.Font('Segoe UI', 12) + $identity.BackColor = [Drawing.Color]::White + $identity.ForeColor = [Drawing.Color]::Black + $f.Controls.Add($identity) + } + $l = New-Object Windows.Forms.Label + $l.Name = 'qualification-altered-action' + $l.Text = 'Merge Into Existing Record' + $l.AccessibleName = $l.Text + $l.Location = New-Object Drawing.Point(($x - $left), ($y - $top)) + $l.Size = New-Object Drawing.Size($w, $h) + $l.BackColor = [Drawing.Color]::White + $l.ForeColor = [Drawing.Color]::Red + $f.Controls.Add($l) + } +} +$t = New-Object Windows.Forms.Timer +$t.Interval = 180000 +$t.Add_Tick({ $f.Close() }) +$t.Start() +[Windows.Forms.Application]::Run($f) +$t.Dispose() +$f.Dispose() +""" + + +class FaultStagingError(RuntimeError): + """No mutation receipt may be accepted for this operation.""" + + def __init__(self, code: str) -> None: + self.code = code + super().__init__(code) + + +def validate_identity_offset( + value: object, kind: str +) -> tuple[int, int, int, int] | None: + """A bounded recorded rectangle, relative to the live resolved save point.""" + if value is None: + return None + if ( + kind != "wrong_identity" + or not isinstance(value, (tuple, list)) + or len(value) != 4 + or any(isinstance(v, bool) or not isinstance(v, int) for v in value) + ): + raise ValueError( + "identity_offset requires four integer coordinates for wrong_identity" + ) + dx, dy, width, height = value + if ( + abs(dx) > 32768 + or abs(dy) > 32768 + or not 1 <= width <= 8192 + or not 1 <= height <= 8192 + or width * height > 16_777_216 + ): + raise ValueError("identity_offset is outside the bounded rectangle contract") + return dx, dy, width, height + + +def _launch_overlay(payload: dict[str, Any]) -> Any: + if os.name != "nt": + raise FaultStagingError("qualification_windows_unavailable") + encoded = base64.b64encode(_OVERLAY_PS.encode("utf-16le")).decode("ascii") + process = subprocess.Popen( + [ + "powershell.exe", + "-NoProfile", + "-NonInteractive", + "-STA", + "-EncodedCommand", + encoded, + ], + stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + creationflags=0x08000000, # CREATE_NO_WINDOW; the form is still visible. + ) + try: + assert process.stdin is not None + process.stdin.write(json.dumps(payload).encode("utf-8")) + process.stdin.close() + except BaseException: + process.terminate() + process.wait(timeout=5) + raise + return process + + +class QualificationFaultController: + """One owned overlay per agent; cleanup never accepts a client process id.""" + + def __init__( + self, + uia: Callable[[str, dict[str, Any]], dict[str, Any]], + capture: Callable[[], bytes], + *, + launch: Callable[[dict[str, Any]], Any] = _launch_overlay, + timeout_s: float = 8.0, + ) -> None: + self._uia, self._capture, self._launch = uia, capture, launch + self._timeout_s = timeout_s + self._active: tuple[str, Any] | None = None + + def close(self) -> None: + """Remove this controller's overlay when its server stops.""" + if self._active is not None: + self.clear(self._active[0]) + + def clear(self, mutation_id: str) -> dict[str, Any]: + active = self._active + if active is None or active[0] != mutation_id: + raise FaultStagingError("qualification_mutation_not_owned") + process = active[1] + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + self._active = None + return {"status": "ok", "cleared": True} + + def stage( + self, + kind: str, + locator: dict[str, Any], + *, + identity_offset: tuple[int, int, int, int] | None = None, + ) -> dict[str, Any]: + if not isinstance(kind, str) or kind not in { + "ambiguity", + "wrong_identity", + "stale_identity", + }: + raise FaultStagingError("qualification_unknown_fault") + try: + offset = validate_identity_offset(identity_offset, kind) + except ValueError as exc: + raise FaultStagingError("qualification_invalid_identity_offset") from exc + if self._active is not None: + raise FaultStagingError("qualification_mutation_active") + before = self._uia("find", {"locator": locator}) + candidates = before.get("candidates") + if ( + before.get("status") != "ok" + or before.get("match") != "unique" + or before.get("candidate_count") != 1 + or before.get("truncated") is not False + or not isinstance(candidates, list) + or len(candidates) != 1 + ): + raise FaultStagingError("qualification_target_not_unique") + candidate = candidates[0] + if not isinstance(candidate, dict) or candidate.get("role") != "button": + raise FaultStagingError("qualification_target_role_unsupported") + bounds = candidate.get("bounds") + point = candidate.get("point") + if ( + not isinstance(bounds, list) + or len(bounds) != 4 + or any( + isinstance(v, bool) or not isinstance(v, int) or abs(v) > 32768 + for v in bounds + ) + or bounds[2] <= bounds[0] + or bounds[3] <= bounds[1] + or not isinstance(point, list) + or len(point) != 2 + or any(isinstance(v, bool) or not isinstance(v, int) for v in point) + or not ( + bounds[0] <= point[0] < bounds[2] and bounds[1] <= point[1] < bounds[3] + ) + ): + raise FaultStagingError("qualification_target_geometry_unavailable") + target_point = {"x": point[0], "y": point[1]} + identity = self._uia("element-identity-at", target_point).get("identity") + if identity is None: + raise FaultStagingError("qualification_identity_unavailable") + identity_point = None + region_identity = None + identity_bounds = None + if offset is not None: + dx, dy, width, height = offset + left, top = point[0] + dx, point[1] + dy + identity_bounds = [left, top, left + width, top + height] + union_width = max(bounds[2], identity_bounds[2]) - min(bounds[0], left) + union_height = max(bounds[3], identity_bounds[3]) - min(bounds[1], top) + if ( + any(abs(v) > 32768 for v in identity_bounds) + or union_width > 8192 + or union_height > 8192 + or union_width * union_height > 16_777_216 + ): + raise FaultStagingError("qualification_identity_geometry_unavailable") + identity_point = {"x": left + width // 2, "y": top + height // 2} + region_identity = self._uia("element-identity-at", identity_point).get( + "identity" + ) + png = self._capture() + if not png.startswith(b"\x89PNG\r\n\x1a\n"): + raise FaultStagingError("qualification_capture_unavailable") + before_sha = hashlib.sha256(png).digest() + data = { + key: candidate.get(key) for key in ("automation_id", "name", "window_name") + } + for value in data.values(): + if value is not None and (not isinstance(value, str) or len(value) > 512): + raise FaultStagingError("qualification_target_identity_unavailable") + data.update(kind=kind, bounds=bounds, identity_bounds=identity_bounds) + token = uuid.uuid4().hex + process = self._launch(data) + self._active = (token, process) + try: + deadline = time.monotonic() + self._timeout_s + while time.monotonic() < deadline: + if process.poll() is not None: + raise FaultStagingError("qualification_overlay_exited") + if kind == "ambiguity": + observed = self._uia("find", {"locator": locator}) + changed = ( + observed.get("status") == "ok" + and observed.get("match") == "ambiguous" + and observed.get("truncated") is False + and isinstance(observed.get("candidate_count"), int) + and observed["candidate_count"] >= 2 + ) + else: + observed = self._uia("element-identity-at", target_point) + changed = ( + observed.get("status") == "ok" + and observed.get("identity") is not None + and observed["identity"] != identity + ) + if changed and identity_point is not None: + at_region = self._uia("element-identity-at", identity_point) + changed = ( + at_region.get("status") == "ok" + and isinstance(at_region.get("identity"), dict) + and at_region["identity"] != region_identity + and at_region["identity"].get("automation_id") + in { + "qualification-altered-identity", + "qualification-altered-action", + } + ) + frame = self._capture() + if ( + changed + and frame.startswith(b"\x89PNG\r\n\x1a\n") + and hashlib.sha256(frame).digest() != before_sha + ): + return {"status": "ok", "mutation_id": token, "kind": kind} + time.sleep(0.1) + raise FaultStagingError("qualification_mutation_not_observed") + except BaseException: + self.clear(token) + raise diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index 491853072c..81cb9b7abc 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -2511,6 +2511,8 @@ class AgentConfig: certfile: Optional[str] = None keyfile: Optional[str] = None allow_legacy_exec: bool = False + #: Test-only native overlays; requires authentication and defaults off. + allow_qualification_faults: bool = False def authed(self) -> bool: """True when a bearer token is required.""" @@ -2522,6 +2524,8 @@ def tls_enabled(self) -> bool: def __post_init__(self) -> None: """Reject a half-configured TLS pair (fail closed, never silent HTTP).""" + if self.allow_qualification_faults and not self.token: + raise ValueError("qualification faults require an authenticated agent") if bool(self.certfile) != bool(self.keyfile): raise ValueError( "TLS needs BOTH certfile and keyfile (got only one) -- refusing " @@ -3003,6 +3007,7 @@ def make_handler_class( uia_fn: UiaFn = _perform_uia, context_fn: ContextFn = _execution_context_identity, legacy_fn: LegacyFn = _perform_legacy_calls, + fault_controller: Any = None, ) -> type[BaseHTTPRequestHandler]: """Build the request-handler class bound to ``config`` and ``grab_fn``. @@ -3010,6 +3015,25 @@ def make_handler_class( deterministic fake frame (no mss / no live desktop). """ + faults = None + fault_error: tuple[type[Exception], ...] = () + if config.allow_qualification_faults: + try: + from openadapt_flow.backends.win_agent.qualification_faults import ( + FaultStagingError, + QualificationFaultController, + validate_identity_offset, + ) + except ModuleNotFoundError: + # launch_agent deploys this script and its helper side by side. + from win_agent_qualification_faults import ( # type: ignore[no-redef,import-not-found] + FaultStagingError, + QualificationFaultController, + validate_identity_offset, + ) + fault_error = (FaultStagingError,) + faults = fault_controller or QualificationFaultController(uia_fn, grab_fn) + keyboards = None keyboard_errors: tuple[type[Exception], ...] = () keyboard_refusals: tuple[type[Exception], ...] = () @@ -3055,6 +3079,7 @@ def deliver_keyboard(data: dict[str, Any]) -> dict[str, Any]: ) class AgentHandler(BaseHTTPRequestHandler): + qualification_fault_controller = faults server_version = "OAFlowWinAgent/1.0" def log_message(self, *args: object) -> None: # noqa: D401 - silence @@ -3114,6 +3139,11 @@ def do_GET(self) -> None: # noqa: N802 - stdlib naming "window_bounds_v1", "uia_authoring_tree_v1", "native_focus_v1", + *( + ["qualification_faults_v1"] + if faults is not None + else [] + ), *( ["legacy_waa_input_v1"] if config.allow_legacy_exec @@ -3165,6 +3195,13 @@ def do_POST(self) -> None: # noqa: N802 - stdlib naming "/uia/read": ("uia", "read"), "/uia/tree": ("uia", "tree"), } + if faults is not None: + typed_routes.update( + { + "/qualification/fault": ("qualification", "stage"), + "/qualification/clear": ("qualification", "clear"), + } + ) if keyboards is not None: typed_routes.update( { @@ -3230,6 +3267,58 @@ def do_POST(self) -> None: # noqa: N802 - stdlib naming if self.path in typed_routes: kind, operation = typed_routes[self.path] try: + if kind == "qualification": + assert faults is not None + if operation == "clear": + data = _exact_object( + data, + required=frozenset({"mutation_id"}), + label="qualification cleanup", + ) + token = data["mutation_id"] + if ( + not isinstance(token, str) + or len(token) != 32 + or any(c not in "0123456789abcdef" for c in token) + ): + raise AgentRequestError( + 400, "invalid_schema", "invalid mutation id" + ) + result = faults.clear(token) + else: + data = _exact_object( + data, + required=frozenset({"kind", "locator"}), + optional=frozenset({"identity_offset"}), + label="qualification fault", + ) + kind_value = data["kind"] + if not isinstance(kind_value, str) or kind_value not in { + "ambiguity", + "wrong_identity", + "stale_identity", + }: + raise AgentRequestError( + 400, "invalid_schema", "unknown qualification fault" + ) + try: + offset = validate_identity_offset( + data.get("identity_offset"), kind_value + ) + except ValueError as exc: + raise AgentRequestError( + 400, "invalid_schema", str(exc) + ) from exc + locator = _locator_payload(data["locator"]) + result = ( + faults.stage( + kind_value, locator, identity_offset=offset + ) + if offset is not None + else faults.stage(kind_value, locator) + ) + self._send_json(200, result) + return if kind == "keyboard-lease": assert keyboards is not None if operation == "observe": @@ -3380,6 +3469,16 @@ def do_POST(self) -> None: # noqa: N802 - stdlib naming if kind == "context" else uia_fn(operation, data) ) + except fault_error as exc: + self._send_json( + 409, + { + "status": "error", + "code": str(exc), + "error": "qualification mutation was refused", + }, + ) + return except keyboard_uncertain as exc: self._send_json(500, exc.payload()) # type: ignore[attr-defined] return @@ -3484,6 +3583,7 @@ def create_server( uia_fn: UiaFn = _perform_uia, context_fn: ContextFn = _execution_context_identity, legacy_fn: LegacyFn = _perform_legacy_calls, + fault_controller: Any = None, ) -> HTTPServer: """Build (but do not start) the COM-affine agent HTTP server. @@ -3500,15 +3600,25 @@ def create_server( """ config = config or AgentConfig() handler = make_handler_class( - config, grab_fn, input_fn, uia_fn, context_fn, legacy_fn + config, grab_fn, input_fn, uia_fn, context_fn, legacy_fn, fault_controller ) + # UIAutomation controls and patterns are apartment/thread-affine. A # single-threaded HTTPServer keeps every request on the serve_forever # thread; _perform_uia initializes that thread's COM apartment per request. - server = HTTPServer((config.host, config.port), handler) + class AgentServer(HTTPServer): + def server_close(self) -> None: + try: + faults = getattr(handler, "qualification_fault_controller", None) + if faults is not None: + faults.close() + finally: + super().server_close() + + server = AgentServer((config.host, config.port), handler) if config.tls_enabled(): - # Keep this deployed script genuinely self-contained: launch_agent() - # copies only server.py into the guest, not the openadapt_flow package. + # Normal runs deploy this script without the package. Qualification + # explicitly deploys its bounded helper beside it. # The control plane mints the cert; the guest needs stdlib ssl only. import ssl # noqa: PLC0415 @@ -3567,6 +3677,11 @@ def main(argv: Optional[list[str]] = None) -> None: "--allow-legacy-exec is the deprecated spelling." ), ) + parser.add_argument( + "--allow-qualification-faults", + action="store_true", + help="TEST ONLY: authenticated, bounded native qualification overlays", + ) args = parser.parse_args(argv) config = AgentConfig( host=args.host, @@ -3575,6 +3690,7 @@ def main(argv: Optional[list[str]] = None) -> None: certfile=args.certfile, keyfile=args.keyfile, allow_legacy_exec=args.allow_legacy_exec, + allow_qualification_faults=args.allow_qualification_faults, ) server = create_server(config) scheme = "https" if config.tls_enabled() else "http" diff --git a/packages/flow/openadapt_flow/backends/windows_backend.py b/packages/flow/openadapt_flow/backends/windows_backend.py index 1b6d52b418..aaae0fcfe0 100644 --- a/packages/flow/openadapt_flow/backends/windows_backend.py +++ b/packages/flow/openadapt_flow/backends/windows_backend.py @@ -1297,6 +1297,76 @@ def structural_locator_at(self, x: int, y: int) -> Optional[StructuralLocator]: window_name=value.get("window_name"), ) + def stage_qualification_fault( + self, + kind: str, + locator: StructuralLocator, + *, + identity_offset: tuple[int, int, int, int] | None = None, + ) -> str: + """Stage one opt-in native test fault; absence never counts as success.""" + if not isinstance(kind, str) or kind not in { + "ambiguity", + "wrong_identity", + "stale_identity", + }: + raise ValueError("unknown Windows qualification fault") + from openadapt_flow.backends.win_agent.qualification_faults import ( + validate_identity_offset, + ) + + offset = validate_identity_offset(identity_offset, kind) + payload: dict[str, Any] = { + "kind": kind, + "locator": { + key: getattr(locator, key) + for key in ("automation_id", "role", "name", "window_name") + }, + } + if offset is not None: + payload["identity_offset"] = list(offset) + result = self._qualification_request("/qualification/fault", payload) + token = result.get("mutation_id") + if ( + set(result) != {"status", "mutation_id", "kind"} + or result.get("kind") != kind + or not isinstance(token, str) + or re.fullmatch(r"[a-f0-9]{32}", token) is None + ): + raise RuntimeError("Windows qualification fault receipt is invalid") + return token + + def clear_qualification_fault(self, mutation_id: str) -> None: + """Remove only the overlay named by this campaign's staging receipt.""" + if ( + not isinstance(mutation_id, str) + or re.fullmatch(r"[a-f0-9]{32}", mutation_id) is None + ): + raise ValueError("invalid Windows qualification mutation id") + result = self._qualification_request( + "/qualification/clear", {"mutation_id": mutation_id} + ) + if result != {"status": "ok", "cleared": True}: + raise RuntimeError("Windows qualification cleanup receipt is invalid") + + def _qualification_request(self, path: str, payload: dict) -> dict: + try: + response = self._session.post( + f"{self.server_url}{path}", json=payload, **self._request_kwargs() + ) + data = response.json() + except (requests.RequestException, ValueError) as exc: + raise RuntimeError( + "Windows qualification operation is unavailable" + ) from exc + if ( + response.status_code != 200 + or not isinstance(data, dict) + or data.get("status") != "ok" + ): + raise RuntimeError("Windows qualification operation was refused") + return data + def locate_structural( self, locator: StructuralLocator ) -> Optional[StructuralHandle]: diff --git a/packages/flow/openadapt_flow/qualify/__init__.py b/packages/flow/openadapt_flow/qualify/__init__.py index e702c7c369..11bd83b23d 100644 --- a/packages/flow/openadapt_flow/qualify/__init__.py +++ b/packages/flow/openadapt_flow/qualify/__init__.py @@ -22,6 +22,10 @@ ) from openadapt_flow.qualify.environment import WebEnvironmentObserver from openadapt_flow.qualify.faults import WebFaultDriver +from openadapt_flow.qualify.windows import ( + WindowsEnvironmentObserver, + WindowsFaultDriver, +) __all__ = [ "CASES", @@ -33,6 +37,8 @@ "VerifyConfig", "WebEnvironmentObserver", "WebFaultDriver", + "WindowsEnvironmentObserver", + "WindowsFaultDriver", "load_verify_config", "parse_verify_config", "qualify", diff --git a/packages/flow/openadapt_flow/qualify/campaign.py b/packages/flow/openadapt_flow/qualify/campaign.py index 947fc44269..4b39897e63 100644 --- a/packages/flow/openadapt_flow/qualify/campaign.py +++ b/packages/flow/openadapt_flow/qualify/campaign.py @@ -52,6 +52,7 @@ resolve_deployment_surface, surface_offers_structure, ) +from openadapt_flow.qualify import surfaces from openadapt_flow.qualify.config import ( CASE_IDS, RULE_CASE_PREFIX, @@ -59,14 +60,6 @@ QualifyConfigError, VerifyConfig, ) -from openadapt_flow.qualify.environment import ( - WEB_OBSERVER_CONTRACT_SHA256, - WEB_OBSERVER_ID, - WebEnvironmentObserver, - web_environment_digest, - web_environment_payload, -) -from openadapt_flow.qualify.faults import WebFaultDriver from openadapt_flow.qualify.keys import LocalTestKey, new_local_test_key from openadapt_flow.subroutines import SubroutineLibrary, uses_subroutines from openadapt_flow.verification import VerificationTier @@ -335,10 +328,14 @@ def check_ready( """Every problem that would stop the campaign, found before it runs.""" problems: list[str] = [] - if config.app.target != "web": + if config.app.target not in {"web", "windows"}: + problems.append( + f"app.target {config.app.target!r}: qualification fault staging is " + "available for web and native Windows targets only" + ) + if config.app.target == "windows" and not config.app.session: problems.append( - f"app.target {config.app.target!r}: qualify runs web campaigns today; " - "the pixel-surface fault driver for Windows, RDP and Citrix is not built" + "app.target windows needs app.session returning an opt-in native backend" ) if ( config.app.reset is None @@ -384,14 +381,20 @@ def check_ready( f"save step {save.id} has an unconfirmed placeholder record check" ) structural = save.anchor.structural if save.anchor is not None else None + native = config.app.target == "windows" + if native and structural is not None and structural.role not in {None, "button"}: + problems.append("native qualification fault staging supports button saves only") if save.anchor is not None and ( structural is None - or not (structural.selector or (structural.role and structural.name)) + or not ( + (structural.automation_id if native else structural.selector) + or (structural.role and structural.name) + ) ): problems.append( - f"save step {save.id} has no structural locator (a selector, or a " - "role and a name): the web fault driver needs it for the ambiguity " - "and identity faults" + f"save step {save.id} has no structural locator " + f"({'automation_id' if native else 'selector'}, or role and name): " + "the fault driver needs it for ambiguity and identity faults" ) problems.extend(business_rule_problems(workflow, config, save, params)) return problems @@ -405,8 +408,8 @@ def check_ready( @dataclass class CampaignSetup: runner_key: LocalTestKey - driver: WebFaultDriver - observer: WebEnvironmentObserver + driver: Any + observer: Any environment: dict[str, Any] @@ -444,23 +447,11 @@ def configure_project( from openadapt_flow.runtime.authorization import runtime_inputs_digest app = config.app - capabilities = sorted( - { - "headless_chromium" if app.headless else "headed_chromium", - "independent_system_of_record", - "playwright_dom", - } - ) boundary = EnvironmentBoundary( - target_kind="web", application=app.name, - application_identity=app.origin, application_version=app.version, - environment_observer_id=WEB_OBSERVER_ID, - environment_observer_contract_sha256=WEB_OBSERVER_CONTRACT_SHA256, - environment_digest=web_environment_digest(environment), runtime_version=FLOW_VERSION, - required_capabilities=capabilities, + **surfaces.boundary_fields(config, environment), ) # Re-qualifying a bundle that already has a project (a sealed copy, a # repaired copy, or one certified before) replaces the project with a new @@ -524,7 +515,9 @@ def configure_project( key_id=runner_key.key_id, public_key_base64=runner_key.public_key_base64, ) - driver = WebFaultDriver(workflow, key_id=f"{campaign_id}-fault-driver") + driver = surfaces.fault_driver( + workflow, config, key_id=f"{campaign_id}-fault-driver" + ) set_trusted_fault_driver_key( workflow, key_id=driver.attestation_key_id, @@ -545,9 +538,7 @@ def configure_project( return CampaignSetup( runner_key=runner_key, driver=driver, - observer=WebEnvironmentObserver( - application_version=app.version, headless=app.headless - ), + observer=surfaces.observer(config), environment=environment, ) @@ -571,21 +562,6 @@ def _records_reader( return None -def _same_field(record: Mapping[str, Any], key: str, want: Any) -> bool: - """Whether ``record[key]`` equals ``want``, by text. - - A null equals only a field that is there and null: ``str(None)`` is - ``"None"``, which would match the text ``"None"`` or a missing field. - """ - - if key not in record: - return False - have = record[key] - if have is None or want is None: - return have is None and want is None - return str(have) == str(want) - - def _canon(record: Mapping[str, Any]) -> str: return json.dumps(record, sort_keys=True, default=str) @@ -594,10 +570,10 @@ class RecordReadback: """Read the system of record before and after a trial; judge the trial. ``exact_record``: exactly the expected number of records match the save's - selector, every declared field equals its expected value, and no record - that existed before changed. ``no_mutation``: nothing matches and no - record changed. Uses the configured verifier's own read path (REST today); - other kinds fall back to the run report and say so. + selector and no other changes occurred, or exactly the declared fields + of selected existing rows changed. ``no_mutation``: complete before/after + multisets are equal. Unavailable reads and unsupported effects refuse. + Verifiers without a records read fall back to the report and say so. """ def __init__(self, verifier: Any, save: Any, params: Mapping[str, str]) -> None: @@ -639,64 +615,17 @@ def judge(self, oracle_kind: str, report: RunReport) -> dict[str, Any]: "silent_incorrect_success": bool(not passed and report.success), "effect_verdict": "INDETERMINATE", } - after = self._read() or [] - written = next( - (e for e in self._effects if e.kind.value == "record_written"), None - ) - selector = { - k: v.literal if hasattr(v, "literal") else v - for k, v in ((written.match if written else {}) or {}).items() - } - - def matches(rec: Mapping[str, Any], sel: Mapping[str, Any]) -> bool: - return all(_same_field(rec, k, v) for k, v in sel.items()) + from openadapt_flow.qualify.record_oracle import judge_records - matched = [rec for rec in after if selector and matches(rec, selector)] - after_set = {_canon(rec) for rec in after} - changed_existing = [rec for rec in self.before if _canon(rec) not in after_set] - field_checks = [] - for effect in self._effects: - if effect.kind.value != "field_equals" or effect.field is None: - continue - want = effect.value.literal if effect.value is not None else None - ok = len(matched) == 1 and _same_field(matched[0], effect.field, want) - field_checks.append({"field": effect.field, "match": ok}) - expected = written.expected_count if written else 1 - exact = ( - len(matched) == expected - and not changed_existing - and all(item["match"] for item in field_checks) - ) - nothing = ( - not matched and not changed_existing and len(after) == len(self.before) - ) - if oracle_kind == "exact_record": - passed = exact - observed = "exact_record" if passed else "record_mismatch" - elif oracle_kind == "no_mutation": - passed = ( - not matched and not changed_existing and len(after) == len(self.before) - ) - observed = "no_mutation" if passed else "unexpected_mutation" - else: - raise QualifyError(f"unknown oracle kind {oracle_kind!r}") return { **base, - "read_path": "system_of_record verifier records read", - "independent": True, - "passed": passed, - "observed": observed, - # RFC-0002 verdict of the read itself, whatever the case expected. - "effect_verdict": "CONFIRMED" if exact else "REFUTED", - "landed": "exact" if exact else ("none" if nothing else "some"), - "records_before": len(self.before), - "records_after": len(after), - "matching_records": len(matched), - "existing_records_changed": len(changed_existing), - "fields_matched": sum(item["match"] for item in field_checks), - "fields_expected": len(field_checks), - "field_check": field_checks, - "silent_incorrect_success": bool(not passed and report.success), + **judge_records( + self.before, + self._read(), + self._effects, + oracle_kind, + success=report.success, + ), } @@ -843,9 +772,7 @@ def _run( params=dict(ctx.params), bundle_dir=bundle_dir, run_dir=ctx.run_dir, - execution_target_kind="web", - execution_origin=config.app.origin, - execution_entry_url=backend.page.url, + **surfaces.execution_fields(backend, config), run_id=ctx.run_id, ) marks["task_end"] = time.time() @@ -853,8 +780,11 @@ def _run( hooks.after_run(ctx, backend, report) return report, verifier finally: - close() - marks["browser_closed"] = time.time() + try: + surfaces.cleanup_faults(fault_driver, backend) + finally: + close() + marks["browser_closed"] = time.time() def _judge_trial( @@ -1437,11 +1367,7 @@ def qualify( ) backend, close = opener() try: - environment = web_environment_payload( - backend, - application_version=config.app.version, - headless=config.app.headless, - ) + environment = surfaces.environment_payload(backend, config) finally: close() setup = configure_project( @@ -1456,9 +1382,10 @@ def qualify( save_qualified_workflow(workflow, bundle_dir) workflow = Workflow.load(bundle_dir) save = next(s for s in workflow.steps if s.id == save.id) - runner_id = ( - hooks.runner_id - or f"openadapt-flow/qualify-web-{'headless' if config.app.headless else 'headed'}" + runner_id = hooks.runner_id or ( + "openadapt-flow/qualify-windows" + if config.app.target == "windows" + else f"openadapt-flow/qualify-web-{'headless' if config.app.headless else 'headed'}" ) policy_name = certify or config.campaign.policy @@ -1619,6 +1546,7 @@ def authorize( verify_sha256=verify_sha, verifier_identity=verifier_id, fault_driver_version=setup.driver.contract_sha256[:16], + fault_driver_kind=f"{config.app.target}-generic", cases=case_entries, ), ) @@ -1744,6 +1672,7 @@ def authorize( verify_sha256=verify_sha, verifier_identity=verifier_id, fault_driver_version=setup.driver.contract_sha256[:16], + fault_driver_kind=f"{config.app.target}-generic", cases=case_entries, ), ) @@ -1753,6 +1682,7 @@ def authorize( verify_sha256=verify_sha, verifier_identity=verifier_id, fault_driver_version=setup.driver.contract_sha256[:16], + fault_driver_kind=f"{config.app.target}-generic", cases=case_entries, ) result_path = write_json(out / "qualification" / "result.json", qresult) @@ -1844,7 +1774,7 @@ def authorize( notes=notes, reports=reports, observer=setup.observer, - environment_digest=web_environment_digest(environment), + environment_digest=surfaces.environment_digest(environment, config), result=qresult, admission_note=admission_note, lookup=lookup_record, diff --git a/packages/flow/openadapt_flow/qualify/record_oracle.py b/packages/flow/openadapt_flow/qualify/record_oracle.py new file mode 100644 index 0000000000..e894623668 --- /dev/null +++ b/packages/flow/openadapt_flow/qualify/record_oracle.py @@ -0,0 +1,174 @@ +"""Judge complete record snapshots against declared insert or field-update effects.""" + +from __future__ import annotations + +import json +from collections import Counter +from typing import Any, Mapping + + +def _canonical(row: Mapping[str, Any]) -> str: + return json.dumps(row, sort_keys=True, default=str) + + +def _value(value: Any) -> Any: + return value.resolve({}) if callable(getattr(value, "resolve", None)) else value + + +def _matches(row: Mapping[str, Any], selector: Mapping[str, Any]) -> bool: + return bool(selector) and all( + key in row + and ( + (row[key] is None and _value(want) is None) + or ( + row[key] is not None + and _value(want) is not None + and str(row[key]) == str(_value(want)) + ) + ) + for key, want in selector.items() + ) + + +def _one_to_one(rows: list[dict[str, Any]], selectors: list[dict[str, Any]]) -> bool: + if len(rows) != len(selectors): + return False + assigned: dict[int, int] = {} + + def match(index: int, seen: set[int]) -> bool: + for i, row in enumerate(rows): + if i in seen or not _matches(row, selectors[index]): + continue + seen.add(i) + if i not in assigned or match(assigned[i], seen): + assigned[i] = index + return True + return False + + return all(match(index, set()) for index in range(len(selectors))) + + +def judge_records( + before: list[dict[str, Any]], + after: list[dict[str, Any]] | None, + effects: list[Any], + oracle_kind: str, + *, + success: bool, +) -> dict[str, Any]: + """Every row and its multiplicity must match the permitted effect model. + + Inserts must add only the selected new rows and retain every old row. + Field updates must transform exactly the selected existing rows, changing + only named fields. Unknown effect kinds and unavailable reads refuse. + """ + if oracle_kind not in {"exact_record", "no_mutation"}: + raise ValueError(f"unknown oracle kind {oracle_kind!r}") + if after is None: + return { + "read_path": "system_of_record verifier records read", + "independent": True, + "passed": False, + "observed": "read_unavailable", + "effect_verdict": "INDETERMINATE", + "landed": "unknown", + "silent_incorrect_success": bool(success), + } + old, new = Counter(map(_canonical, before)), Counter(map(_canonical, after)) + unchanged = old == new + written = [effect for effect in effects if effect.kind.value == "record_written"] + fields = [effect for effect in effects if effect.kind.value == "field_equals"] + supported = all( + effect.kind.value in {"record_written", "field_equals", "exact_new_set"} + for effect in effects + ) + exact, matched, checks = False, [], [] + if len(written) == 1: + insert = written[0] + matched = [row for row in after if _matches(row, insert.match)] + additions = new - old + added_rows = [ + json.loads(row) for row, count in additions.items() for _ in range(count) + ] + for effect in fields: + selected = [row for row in after if _matches(row, effect.match)] + checks.append( + { + "field": effect.field, + "match": bool( + len(selected) == 1 + and effect.field is not None + and _matches(selected[0], {effect.field: _value(effect.value)}) + ), + } + ) + set_checks = [ + effect for effect in effects if effect.kind.value == "exact_new_set" + ] + exact_set = all( + _one_to_one(added_rows, effect.new_records) for effect in set_checks + ) + exact = bool( + supported + and exact_set + and not (old - new) + and len(matched) == insert.expected_count + and len(added_rows) == insert.expected_count + and all(_matches(row, insert.match) for row in added_rows) + and all(check["match"] for check in checks) + ) + elif ( + not written + and fields + and all(effect.kind.value == "field_equals" for effect in effects) + ): + expected = [dict(row) for row in before] + for effect in fields: + indexes = [i for i, row in enumerate(before) if _matches(row, effect.match)] + selected = [row for row in after if _matches(row, effect.match)] + valid = bool( + len(indexes) == 1 + and len(selected) == 1 + and effect.field is not None + and effect.value is not None + ) + if valid: + index = indexes[0] + expected[index][effect.field] = selected[0].get(effect.field) + checks.append( + { + "field": effect.field, + "match": bool( + valid + and _matches(selected[0], {effect.field: _value(effect.value)}) + ), + } + ) + matched = [ + row + for row in after + if any(_matches(row, effect.match) for effect in fields) + ] + exact = bool( + all(check["match"] for check in checks) + and Counter(map(_canonical, expected)) == new + ) + passed = exact if oracle_kind == "exact_record" else unchanged + return { + "read_path": "system_of_record verifier records read", + "independent": True, + "passed": passed, + "observed": ("exact_record" if exact else "record_mismatch") + if oracle_kind == "exact_record" + else ("no_mutation" if unchanged else "unexpected_mutation"), + "effect_verdict": "CONFIRMED" if exact else "REFUTED", + "landed": "exact" if exact else ("none" if unchanged else "some"), + "records_before": len(before), + "records_after": len(after), + "matching_records": len(matched), + "existing_records_changed": sum((old - new).values()), + "fields_matched": sum(check["match"] for check in checks), + "fields_expected": len(checks), + "field_check": checks, + "silent_incorrect_success": bool(not passed and success), + } diff --git a/packages/flow/openadapt_flow/qualify/result.py b/packages/flow/openadapt_flow/qualify/result.py index 2732384f28..b4fde3d7fd 100644 --- a/packages/flow/openadapt_flow/qualify/result.py +++ b/packages/flow/openadapt_flow/qualify/result.py @@ -281,6 +281,7 @@ def build_result( verifier_identity: str, fault_driver_version: str, cases: list[dict[str, Any]], + fault_driver_kind: str = FAULT_DRIVER_KIND, verifier_model_calls: int = 0, ) -> dict[str, Any]: """``openadapt.qualification-result/v1`` from the project's report.""" @@ -318,7 +319,7 @@ def build_result( "passed": passed, "verify_config_sha256": verify_sha256, "verifier_identity": verifier_identity, - "fault_driver": {"kind": FAULT_DRIVER_KIND, "version": fault_driver_version}, + "fault_driver": {"kind": fault_driver_kind, "version": fault_driver_version}, "cases": cases, "silent_incorrect_success_count": silent, "over_halt_count": over_halt, diff --git a/packages/flow/openadapt_flow/qualify/surfaces.py b/packages/flow/openadapt_flow/qualify/surfaces.py new file mode 100644 index 0000000000..0eae299254 --- /dev/null +++ b/packages/flow/openadapt_flow/qualify/surfaces.py @@ -0,0 +1,109 @@ +"""Backend-specific campaign plumbing; application knowledge stays in data.""" + +from __future__ import annotations + +from typing import Any + +from openadapt_flow.qualify.environment import ( + WebEnvironmentObserver, + web_environment_digest, + web_environment_payload, +) +from openadapt_flow.qualify.faults import WebFaultDriver +from openadapt_flow.qualify.windows import ( + WindowsEnvironmentObserver, + WindowsFaultDriver, +) + + +def observer(config: Any) -> Any: + if config.app.target == "windows": + return WindowsEnvironmentObserver(application_version=config.app.version) + return WebEnvironmentObserver( + application_version=config.app.version, + headless=config.app.headless, + ) + + +def fault_driver(workflow: Any, config: Any, *, key_id: str) -> Any: + kind = WindowsFaultDriver if config.app.target == "windows" else WebFaultDriver + return kind(workflow, key_id=key_id) + + +def environment_payload(backend: Any, config: Any) -> dict[str, Any]: + if config.app.target == "windows": + if not callable(getattr(backend, "stage_qualification_fault", None)): + raise ValueError("Windows qualification needs an opt-in native fault agent") + capabilities: set[str] = set( + getattr(backend, "agent_capabilities", lambda: ())() + ) + if not { + "qualification_faults_v1", + "uia_v1", + "context_environment_v1", + "native_keyboard_lease_v1", + } <= set(capabilities): + raise ValueError( + "Windows qualification needs enabled fault, UIA, environment and native keyboard lease capabilities" + ) + return observer(config).observe(backend, "windows").model_dump(mode="json") + return web_environment_payload( + backend, + application_version=config.app.version, + headless=config.app.headless, + ) + + +def environment_digest(environment: dict[str, Any], config: Any) -> str: + return ( + environment["environment_digest"] + if config.app.target == "windows" + else web_environment_digest(environment) + ) + + +def boundary_fields(config: Any, environment: dict[str, Any]) -> dict[str, Any]: + observed = observer(config) + return { + "target_kind": config.app.target, + "application_identity": ( + environment["application_identity"] + if config.app.target == "windows" + else config.app.origin + ), + "environment_observer_id": observed.observer_id, + "environment_observer_contract_sha256": observed.contract_sha256, + "environment_digest": environment_digest(environment, config), + "required_capabilities": ( + [ + "native_windows", + "uia_v1", + "native_keyboard_lease_v1", + "independent_system_of_record", + ] + if config.app.target == "windows" + else sorted( + { + "headless_chromium" if config.app.headless else "headed_chromium", + "independent_system_of_record", + "playwright_dom", + } + ) + ), + } + + +def execution_fields(backend: Any, config: Any) -> dict[str, Any]: + if config.app.target == "windows": + return {"execution_target_kind": "windows"} + return { + "execution_target_kind": "web", + "execution_origin": config.app.origin, + "execution_entry_url": backend.page.url, + } + + +def cleanup_faults(driver: Any, backend: Any) -> None: + cleanup = getattr(driver, "cleanup", None) + if callable(cleanup): + cleanup(backend) diff --git a/packages/flow/openadapt_flow/qualify/windows.py b/packages/flow/openadapt_flow/qualify/windows.py new file mode 100644 index 0000000000..f12a8243e0 --- /dev/null +++ b/packages/flow/openadapt_flow/qualify/windows.py @@ -0,0 +1,138 @@ +"""Windows campaign observations and real, opt-in native fault staging. + +The observer retains the native backend's machine/OS and executable binding. +It does not make qualifications portable to another Windows installation. +For runtime-hosted applications the executable digest covers the host, not +scripts or application libraries; the application version remains declared. +""" + +from __future__ import annotations + +import hashlib +import json +from typing import Any, Literal + +from openadapt_flow.qualification_environment import ( + BackendQualificationEnvironmentObserver, + QualificationEnvironmentObservation, +) +from openadapt_flow.qualify.faults import WebFaultDriver + +WINDOWS_OBSERVER_ID = "openadapt.qualify.windows-environment" +WINDOWS_OBSERVER_CONTRACT_SHA256 = hashlib.sha256( + b"openadapt.qualify.windows-environment/v1\n" + b"atomic native application, executable digest, session and machine/OS digest; " + b"declared application version bound with observed executable and environment" +).hexdigest() +WINDOWS_FAULT_DRIVER_ID = "openadapt.qualify.windows-faults" +WINDOWS_FAULT_DRIVER_CONTRACT_SHA256 = hashlib.sha256( + b"openadapt.qualify.windows-faults/v2\n" + b"opt-in authenticated real UIA/physical overlays from the recorded locator; " + b"ambiguity@target_resolution; wrong_identity@recorded_identifier_region; " + b"stale_identity@actuation_revalidation; weak_effect@effect_strength; " + b"missing_effect@effect_verifier; owned cleanup" +).hexdigest() + + +class WindowsEnvironmentObserver: + """Observe each newly opened native backend without trusting config identity.""" + + observer_id = WINDOWS_OBSERVER_ID + contract_sha256 = WINDOWS_OBSERVER_CONTRACT_SHA256 + + def __init__(self, *, application_version: str) -> None: + self._version = application_version + + def observe( + self, + backend: Any, + target_kind: Literal["web", "windows", "macos", "linux", "rdp", "citrix"], + ) -> QualificationEnvironmentObservation: + if target_kind != "windows": + raise ValueError("the Windows campaign observer needs a Windows target") + observed = BackendQualificationEnvironmentObserver(backend).observe( + backend, target_kind + ) + binding = { + "native_environment": observed.environment_digest, + "application": observed.application_identity, + "executable": observed.application_version, + "declared_version": self._version, + } + digest = hashlib.sha256( + json.dumps(binding, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + return observed.model_copy( + update={ + "application_version": self._version, + "environment_digest": digest, + } + ) + + +class WindowsFaultDriver(WebFaultDriver): + """Reuse surface-independent receipt/effect faults, stage native screen faults.""" + + driver_id = WINDOWS_FAULT_DRIVER_ID + contract_sha256 = WINDOWS_FAULT_DRIVER_CONTRACT_SHA256 + + def __init__(self, workflow: Any, **kwargs: Any) -> None: + super().__init__(workflow, **kwargs) + self._staged: list[tuple[Any, str]] = [] + + @staticmethod + def mutation_bytes(kind: str) -> bytes: + return f"{WINDOWS_FAULT_DRIVER_ID}/{kind}/v2\n".encode("ascii") + + def _screen_fault(self, context: Any) -> str | None: + from openadapt_flow.qualification_drills import _settled_screenshot + from openadapt_flow.qualification_faults import sha256_bytes + + step = self._steps.get(context.step_id) + anchor = step.anchor if step is not None else None + locator = anchor.structural if anchor is not None else None + stage = getattr(context.backend, "stage_qualification_fault", None) + if context.actuation_path != "gui" or not callable(stage): + self.declined = "native_fault_staging_unavailable" + return None + if ( + anchor is None + or locator is None + or not (locator.automation_id or (locator.role and locator.name)) + ): + self.declined = "native_save_locator_unavailable" + return None + if context.fault_kind == "wrong_identity" and anchor.identifier_region is None: + self.declined = "native_identity_region_unavailable" + return None + try: + if context.fault_kind == "wrong_identity": + assert anchor.identifier_region is not None + x, y, width, height = anchor.identifier_region + click_x, click_y = anchor.click_point + mutation_id = stage( + context.fault_kind, + locator, + identity_offset=(x - click_x, y - click_y, width, height), + ) + else: + mutation_id = stage(context.fault_kind, locator) + self._staged.append((context.backend, mutation_id)) + capture = ( + getattr(context, "capture_frame", None) or context.backend.screenshot + ) + frame = _settled_screenshot(capture) + if frame is None: + self.declined = "native_fault_did_not_settle" + return None + return sha256_bytes(frame) + except Exception: + self.declined = "native_fault_staging_failed" + return None + + def cleanup(self, backend: Any) -> None: + """Clear only overlays this campaign staged; cleanup failure is a refusal.""" + owned = [item for item in self._staged if item[0] is backend] + for _, mutation_id in owned: + backend.clear_qualification_fault(mutation_id) + self._staged.remove((backend, mutation_id)) diff --git a/packages/flow/scripts/desktop/winrm_lab.py b/packages/flow/scripts/desktop/winrm_lab.py index ce53323c8a..1c0023aa9a 100644 --- a/packages/flow/scripts/desktop/winrm_lab.py +++ b/packages/flow/scripts/desktop/winrm_lab.py @@ -512,6 +512,7 @@ def launch_agent( port: int = 5000, wait_s: float = 40.0, server_path: Optional[Path] = None, + allow_qualification_faults: bool = False, ): """Deploy and start ``win_agent`` on the desktop with a pinned TLS cert. @@ -556,6 +557,11 @@ def launch_agent( Path(agent_server.__file__).with_name(helper + ".py"), rf"{guest_dir}\win_agent_{helper}.py", ) + if allow_qualification_faults: + helper = Path(server_path or agent_server.__file__).with_name( + "qualification_faults.py" + ) + self.push_file(helper, rf"{guest_dir}\win_agent_qualification_faults.py") bundle = generate_self_signed_cert([self.host]) try: self.push_file(Path(bundle.certfile), rf"{guest_dir}\agent-cert.pem") @@ -565,7 +571,8 @@ def launch_agent( self.launch_interactive( f'"{python}" "{guest_dir}\\win_agent_server.py" --host 0.0.0.0 ' f"--port {port} --token {token} " - f'--certfile "{guest_dir}\\agent-cert.pem" --keyfile "{guest_dir}\\agent-key.pem"', + f'--certfile "{guest_dir}\\agent-cert.pem" --keyfile "{guest_dir}\\agent-key.pem"' + + (" --allow-qualification-faults" if allow_qualification_faults else ""), name="OAFlowAgent", ) endpoint = AgentEndpoint( diff --git a/packages/flow/tests/e2e/test_windows_hosted_replay.py b/packages/flow/tests/e2e/test_windows_hosted_replay.py index 3b2859da24..9a3c9c626d 100644 --- a/packages/flow/tests/e2e/test_windows_hosted_replay.py +++ b/packages/flow/tests/e2e/test_windows_hosted_replay.py @@ -117,7 +117,7 @@ def stop_app(self) -> None: self.app.wait(timeout=30) self.app = None - def start_agent(self): + def start_agent(self, *, allow_qualification_faults: bool = False): from openadapt_flow.backends.win_agent.tls import generate_self_signed_cert from openadapt_flow.backends.windows_backend import WindowsBackend @@ -138,6 +138,11 @@ def start_agent(self): cert.certfile, "--keyfile", cert.keyfile, + *( + ["--allow-qualification-faults"] + if allow_qualification_faults + else [] + ), ], stdout=log, stderr=subprocess.STDOUT, diff --git a/packages/flow/tests/e2e/test_windows_qualification_campaign.py b/packages/flow/tests/e2e/test_windows_qualification_campaign.py new file mode 100644 index 0000000000..04a15fca61 --- /dev/null +++ b/packages/flow/tests/e2e/test_windows_qualification_campaign.py @@ -0,0 +1,215 @@ +"""All six native qualification cases against real WinForms and SQLite. + +This is an opt-in Windows-only integration test. The existing synthetic form +is recorded through the real TLS-pinned win_agent, then qualified with real +UIA/physical screen mutations. Independent complete SQLite snapshots judge +each save, and the final local admission must be signed and bound to Windows. +""" + +from __future__ import annotations + +import json +import os +import time +from pathlib import Path + +import pytest + +from tests.e2e.test_windows_hosted_replay import ( + DEMO_NOTE, + DEMO_SEARCH, + RUN_E2E, + TARGET_ID, + _Host, + _points, +) + +pytestmark = [ + pytest.mark.skipif(not RUN_E2E, reason="opt-in native Windows campaign"), + pytest.mark.timeout(900), +] + + +def test_native_windows_campaign_reads_back_normal_and_all_faults( + tmp_path, monkeypatch +): + from openadapt_flow.adapters.desktop_recorder import record_desktop_demo + from openadapt_flow.compiler import compile_recording + from openadapt_flow.ir import ActionKind, StructuralLocator + from openadapt_flow.qualify import QualifyHooks, parse_verify_config, qualify + + monkeypatch.setenv("OPENADAPT_BUNDLE_KEY", "synthetic-windows-qualification-key") + host = _Host(tmp_path) + evidence = {"cases": {}, "completed": False} + try: + backend = host.start_agent(allow_qualification_faults=True) + assert "qualification_faults_v1" in backend.agent_capabilities() + host.launch_app() + points = _points(backend) + + def demonstrate(rec): + rec.click(*points["searchBox"]) + rec.type_text(DEMO_SEARCH) + rec.press("Enter") + time.sleep(0.4) + rec.click(*points["searchButton"]) + time.sleep(0.4) + rec.click(*points["noteBox"]) + rec.type_text(DEMO_NOTE, param="note") + rec.click(*points["saveButton"]) + time.sleep(0.4) + + recording = record_desktop_demo(backend, tmp_path / "recording", demonstrate) + # The demonstrator marks the record identity, just as record --identifier + # does. The real UIA rectangle supplies the crop; no identity gate is relaxed. + header = backend.locate_structural( + StructuralLocator(automation_id="patientHeader") + ) + assert header is not None and header.region is not None + meta_path = recording / "meta.json" + metadata = json.loads(meta_path.read_text(encoding="utf-8")) + metadata["identifier_region"] = [int(value) for value in header.region] + meta_path.write_text(json.dumps(metadata), encoding="utf-8") + assert ( + next(row for row in host.rows() if row["id"] == TARGET_ID)["note"] + == DEMO_NOTE + ) + bundle = tmp_path / "compiled" + workflow = compile_recording( + recording, bundle, name="native-qualification-fixture" + ) + clicks = [step for step in workflow.steps if step.action is ActionKind.CLICK] + assert all(step.identity_armed for step in clicks) + save = clicks[-1] + save.risk = "irreversible" + workflow.save(bundle) + config = parse_verify_config( + { + "schema_version": "openadapt.verify/v1", + "app": { + "target": "windows", + "surface": "remote_in_session", + "name": "Synthetic native notes", + "url": "windows://synthetic-notes", + "version": "in-tree-fixture-v1", + "session": "fixture:open_session", + "reset": {"command": "unused (hook provided)"}, + }, + "verifier": { + "kind": "sql", + "sqlite_database": str(host.root / "patients.db"), + "sql_query": "SELECT id, first, last, dob, note FROM patients", + }, + "save_step": save.id, + "effects": [ + { + "kind": "field_equals", + "match": {"id": {"literal": "1"}}, + "field": "note", + "value": {"literal": DEMO_NOTE}, + "idempotency_key": {"literal": DEMO_NOTE}, + "key_field": "note", + "risk": "reversible", + "probe": "read complete SQLite rows", + } + ], + "inputs": {"params": {"note": DEMO_NOTE}}, + "campaign": {"trials": 3, "policy": "clinical-write"}, + }, + env={}, + ) + baseline = [] + + def reset(): + host.launch_app() + points = _points(backend) + backend.click(*points["searchBox"]) + time.sleep(0.3) + baseline[:] = host.rows() + + def after_run(ctx, current_backend, report): + after = host.rows() + evidence["cases"][ctx.case_id] = { + "outcome": report.execution_outcome, + "before": list(baseline), + "after": after, + "fault_staged": report.governed_qualification_fault_driver_id, + "halts": [ + str(result.error) for result in report.results if result.error + ], + } + expected = [dict(row) for row in baseline] + if ctx.case_id == "representative": + next(row for row in expected if row["id"] == TARGET_ID)["note"] = ( + DEMO_NOTE + ) + assert report.execution_outcome == "VERIFIED" + else: + assert report.execution_outcome == "HALTED" + assert after == expected + + result = qualify( + bundle, + config, + out=tmp_path / "campaign", + certify="clinical-write", + hooks=QualifyHooks( + open_session=lambda: (backend, lambda: None), + reset=reset, + after_run=after_run, + ), + log=print, + ) + assert result.passed and result.certified and not result.partial + assert result.result["fault_driver"]["kind"] == "windows-generic" + assert len(result.result["cases"]) == 18 + assert all(case["passed"] for case in result.result["cases"]) + assert result.result["silent_incorrect_success_count"] == 0 + assert result.result["verifier_model_calls"] == 0 + from base64 import b64decode + + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey + + from openadapt_flow.qualification_admission import ( + SIGNATURE_DOMAIN, + QualificationAdmissionEnvelope, + QualificationAdmissionError, + expected_from_payload, + verify_qualification_admission, + ) + from openadapt_flow.qualification_dev_signer import LOCAL_DEV_PUBLIC_BYTES + from openadapt_flow.qualify.result import result_sha256 + + assert result.admission_note is None + admission = QualificationAdmissionEnvelope.model_validate_json( + (result.out / "qualification" / "admission.local.json").read_text() + ) + Ed25519PublicKey.from_public_bytes(LOCAL_DEV_PUBLIC_BYTES).verify( + b64decode(admission.signature, validate=True), + SIGNATURE_DOMAIN + admission.payload.canonical_bytes(), + ) + assert admission.payload.campaign.outcomes_sha256 == result_sha256( + result.result + ) + assert all( + task.observed_trials >= 3 for task in admission.payload.campaign.tasks + ) + with pytest.raises(QualificationAdmissionError, match="local-dev"): + verify_qualification_admission( + admission, + trusted_signers={}, + expected=expected_from_payload(admission.payload), + ) + evidence.update( + completed=True, + result=result.result, + admission_sha256=admission.artifact_sha256(), + admission_verified=True, + ) + + finally: + host.close() + if os.environ.get("OAFLOW_WINDOWS_QUALIFICATION_EVIDENCE"): + Path(os.environ["OAFLOW_WINDOWS_QUALIFICATION_EVIDENCE"]).write_text( + json.dumps(evidence, indent=2, default=str), encoding="utf-8" + ) diff --git a/packages/flow/tests/test_qualify_record_oracle.py b/packages/flow/tests/test_qualify_record_oracle.py new file mode 100644 index 0000000000..251d7aee5c --- /dev/null +++ b/packages/flow/tests/test_qualify_record_oracle.py @@ -0,0 +1,216 @@ +"""Planted faults for full-snapshot insert and update qualification read-back.""" + +from __future__ import annotations + +from copy import deepcopy +from types import SimpleNamespace + +import pytest + +from openadapt_flow.qualify.campaign import RecordReadback +from openadapt_flow.qualify.record_oracle import judge_records +from openadapt_flow.runtime.effects import Effect, EffectKind, ValueExpr + + +def effect(kind, **kwargs): + return Effect(kind=kind, probe="complete record read", **kwargs).resolve({}) + + +def update_effects(): + return [ + effect( + EffectKind.FIELD_EQUALS, + match={"id": ValueExpr(literal="1")}, + field="value", + value=ValueExpr(literal="new"), + ) + ] + + +BEFORE = [ + {"id": 1, "value": "old", "untouched": "keep"}, + {"id": 2, "value": "sibling", "untouched": "keep"}, +] + + +def judge(before, after, effects=None, oracle="exact_record"): + return judge_records( + before, after, effects or update_effects(), oracle, success=True + ) + + +def test_declared_update_and_unchanged_fault_case_are_distinguished(): + expected = deepcopy(BEFORE) + expected[0]["value"] = "new" + assert judge(BEFORE, expected)["passed"] + fault = judge(BEFORE, BEFORE, oracle="no_mutation") + assert fault["passed"] and fault["effect_verdict"] == "REFUTED" + assert not judge(BEFORE, BEFORE)["passed"] + + +@pytest.mark.parametrize( + "fault", + [ + "wrong_value", + "wrong_record", + "collateral_field", + "missing_record", + "added_record", + "duplicate_record", + "omitted_field", + ], +) +def test_any_undeclared_change_refuses_update(fault): + after = deepcopy(BEFORE) + after[0]["value"] = "new" + if fault == "wrong_value": + after[0]["value"] = "wrong" + if fault == "wrong_record": + after[0]["value"], after[1]["value"] = "old", "new" + if fault == "collateral_field": + after[0]["untouched"] = "changed" + if fault == "missing_record": + after.pop() + if fault == "added_record": + after.append({"id": 3, "value": "extra"}) + if fault == "duplicate_record": + after.append(dict(after[0])) + if fault == "omitted_field": + del after[0]["untouched"] + assert not judge(BEFORE, after)["passed"] + assert not judge(BEFORE, after, oracle="no_mutation")["passed"] + + +def test_read_failure_is_indeterminate_even_when_baseline_empty(): + save = SimpleNamespace(effects=update_effects()) + current = [[]] + readback = RecordReadback( + SimpleNamespace(_fetch_records=lambda: current[0]), save, {} + ) + readback.snapshot() + current[0] = None + result = readback.judge("no_mutation", SimpleNamespace(success=False)) + assert not result["passed"] and result["effect_verdict"] == "INDETERMINATE" + + +def test_insert_requires_exact_addition_and_preserves_multiplicity(): + effects = [ + effect( + EffectKind.RECORD_WRITTEN, + match={"id": ValueExpr(literal="3")}, + expected_count=1, + ) + ] + new = {"id": 3, "value": "new"} + assert judge(BEFORE, [*BEFORE, new], effects)["passed"] + for after in [ + BEFORE, + [*BEFORE, new, new], + [*BEFORE, new, {"id": 4}], + [BEFORE[0], new], + ]: + assert not judge(BEFORE, after, effects)["passed"] + duplicated_before = [*BEFORE, dict(BEFORE[0])] + assert not judge(duplicated_before, [*BEFORE, new], effects)["passed"] + + +def test_insert_exact_new_set_is_checked_independently_of_key_match(): + effects = [ + effect( + EffectKind.RECORD_WRITTEN, + match={"id": ValueExpr(literal="3")}, + expected_count=1, + ), + effect( + EffectKind.EXACT_NEW_SET, + expected_count=1, + new_records=[ + {"id": ValueExpr(literal="3"), "value": ValueExpr(literal="new")} + ], + ), + ] + assert judge(BEFORE, [*BEFORE, {"id": 3, "value": "new"}], effects)["passed"] + assert not judge(BEFORE, [*BEFORE, {"id": 3, "value": "wrong"}], effects)["passed"] + + +def test_update_supports_numeric_and_null_values_without_allowing_collateral_change(): + for value, expected in [ + (ValueExpr(literal="4", number=True), 4), + (ValueExpr(null=True), None), + ]: + effects = [ + effect( + EffectKind.FIELD_EQUALS, + match={"id": ValueExpr(literal="1")}, + field="value", + value=value, + ) + ] + after = deepcopy(BEFORE) + after[0]["value"] = expected + assert judge(BEFORE, after, effects)["passed"] + after[1]["value"] = expected + assert not judge(BEFORE, after, effects)["passed"] + + +def test_record_readback_update_state_machine_preserves_the_declared_lens(): + """The public wrapper and model agree across successive typed updates.""" + from hypothesis import given, settings + from hypothesis import strategies as st + + values = st.one_of( + st.text(max_size=16), st.none(), st.integers(min_value=-10, max_value=10) + ) + + @settings(max_examples=25, deadline=None) + @given(st.lists(values, min_size=1, max_size=8)) + def transitions(sequence): + rows = deepcopy(BEFORE) + for value in sequence: + expression = ( + ValueExpr(null=True) + if value is None + else ValueExpr(literal=str(value), number=True) + if isinstance(value, int) + else ValueExpr(literal=value) + ) + effects = [ + effect( + EffectKind.FIELD_EQUALS, + match={"id": ValueExpr(literal="1")}, + field="value", + value=expression, + ) + ] + expected = deepcopy(rows) + expected[0]["value"] = value + current = [rows] + readback = RecordReadback( + SimpleNamespace(_fetch_records=lambda: current[0]), + SimpleNamespace(effects=effects), + {}, + ) + readback.snapshot() + current[0] = list(reversed(expected)) + assert readback.judge("exact_record", SimpleNamespace(success=True))[ + "passed" + ] + for planted in [ + expected + [dict(expected[1])], + [{**expected[0], "untouched": "unauthorized"}, expected[1]], + expected[:1], + ]: + current[0] = planted + assert not readback.judge( + "exact_record", SimpleNamespace(success=True) + )["passed"] + assert not readback.judge( + "no_mutation", SimpleNamespace(success=False) + )["passed"] + current[0] = rows + assert readback.judge("no_mutation", SimpleNamespace(success=False))[ + "passed" + ] + rows = expected + + transitions() diff --git a/packages/flow/tests/test_qualify_windows.py b/packages/flow/tests/test_qualify_windows.py new file mode 100644 index 0000000000..871c3b8aed --- /dev/null +++ b/packages/flow/tests/test_qualify_windows.py @@ -0,0 +1,245 @@ +"""Native campaign contracts, including refusal when native evidence is incomplete.""" + +from __future__ import annotations + +import hashlib +from types import SimpleNamespace + +import pytest + +from openadapt_flow.ir import StructuralLocator +from openadapt_flow.qualification_faults import verify_fault_mutation_receipt +from openadapt_flow.qualify import surfaces +from openadapt_flow.qualify.campaign import ( + apply_verify_config, + check_ready, + configure_project, +) +from openadapt_flow.qualify.windows import ( + WindowsEnvironmentObserver, + WindowsFaultDriver, +) +from openadapt_flow.verification import VerificationTier +from tests.test_qualify_declarative import APP, _config, _context, _workflow + + +def native_config(): + return _config( + app={ + **APP, + "target": "windows", + "surface": "remote_in_session", + "session": "fixture:open", + "reset": {"command": "true"}, + } + ) + + +def test_native_readiness_requires_native_locator_and_session(): + workflow = _workflow() + config = native_config() + save, _ = apply_verify_config(workflow, config) + assert "automation_id" in " ".join( + check_ready(workflow, config, save, dict(workflow.params)) + ) + save.anchor.structural = StructuralLocator(automation_id="commit", role="button") + assert check_ready(workflow, config, save, dict(workflow.params)) == [] + config.app.session = None + assert "app.session" in " ".join( + check_ready(workflow, config, save, dict(workflow.params)) + ) + + +class Native: + def __init__(self): + self.identity = ("fixture-runtime", "sha256:" + "a" * 64, "b" * 64, "c" * 64) + + def qualification_environment_identity(self): + return self.identity + + +def test_native_environment_observes_machine_image_and_session_each_time(): + observed = WindowsEnvironmentObserver(application_version="fixture-1") + backend = Native() + first = observed.observe(backend, "windows") + assert first.application_identity == "fixture-runtime" + assert first.application_version == "fixture-1" + assert first.session_identity_sha256 == "b" * 64 + # Session is re-observed but not baked into the transferable environment. + backend.identity = ( + backend.identity[0], + backend.identity[1], + "d" * 64, + backend.identity[3], + ) + next_session = observed.observe(backend, "windows") + assert next_session.environment_digest == first.environment_digest + assert next_session.session_identity_sha256 != first.session_identity_sha256 + for index, replacement in [ + (0, "other-runtime"), + (1, "sha256:" + "d" * 64), + (3, "d" * 64), + ]: + value = list(Native().identity) + value[index] = replacement + backend.identity = tuple(value) + assert ( + observed.observe(backend, "windows").environment_digest + != first.environment_digest + ) + backend.identity = Native().identity + assert ( + WindowsEnvironmentObserver(application_version="fixture-2") + .observe(backend, "windows") + .environment_digest + != first.environment_digest + ) + + +@pytest.mark.parametrize( + "identity", [None, ("runtime",), ("runtime", "v", "bad", "bad")] +) +def test_native_observer_refuses_incomplete_environment(identity): + backend = Native() + backend.identity = identity + with pytest.raises(ValueError): + WindowsEnvironmentObserver(application_version="1").observe(backend, "windows") + + +def test_native_project_binds_observed_environment_and_distinct_fault_contract(): + workflow, config = _workflow(), native_config() + save, _ = apply_verify_config(workflow, config) + save.anchor.structural = StructuralLocator(automation_id="commit", role="button") + native = Native() + native.stage_qualification_fault = lambda *_: None + native.agent_capabilities = lambda: { + "qualification_faults_v1", + "uia_v1", + "context_environment_v1", + "native_keyboard_lease_v1", + } + environment = surfaces.environment_payload(native, config) + setup = configure_project( + workflow, + config, + save=save, + params=dict(workflow.params), + environment=environment, + campaign_id="native-campaign", + minimum_effect_tier=VerificationTier.INDEPENDENT_SYSTEM, + ) + bound = workflow.qualification.environment + assert bound.target_kind == "windows" + assert bound.application_identity == native.identity[0] + assert ( + bound.environment_digest + == setup.observer.observe(native, "windows").environment_digest + ) + assert "headless_chromium" not in bound.required_capabilities + assert isinstance(setup.driver, WindowsFaultDriver) + assert surfaces.execution_fields(native, config) == { + "execution_target_kind": "windows" + } + + +def test_native_fault_receipt_signs_captured_mutation_and_cleans_owned_overlay(): + workflow = _workflow() + workflow.steps[-1].anchor.structural = StructuralLocator( + automation_id="commit", role="button" + ) + workflow.steps[-1].anchor.identifier_region = (10, 10, 100, 30) + driver = WindowsFaultDriver(workflow) + staged, cleared = [], [] + backend = SimpleNamespace( + stage_qualification_fault=lambda kind, locator, **kwargs: ( + staged.append((kind, locator)) or "owned-id" + ), + clear_qualification_fault=cleared.append, + screenshot=lambda: b"changed frame", + ) + context = _context("wrong_identity", backend=backend) + mutation = driver.mutate(context) + assert mutation is not None + assert ( + mutation.receipt.after_input_sha256 + == hashlib.sha256(b"changed frame").hexdigest() + ) + assert verify_fault_mutation_receipt( + mutation.receipt, trusted_public_key_base64=driver.public_key_base64 + ) + assert staged[0][0] == "wrong_identity" + driver.cleanup(backend) + driver.cleanup(backend) + assert cleared == ["owned-id"] + + +def test_native_staging_failure_never_becomes_a_fault_receipt(): + driver = WindowsFaultDriver(_workflow()) + assert driver.mutate(_context("ambiguity", SimpleNamespace())) is None + assert driver.declined == "native_fault_staging_unavailable" + + +def test_native_environment_refuses_disabled_fault_agent_before_representative_run(): + native = Native() + native.stage_qualification_fault = lambda *_: None + native.agent_capabilities = lambda: {"uia_v1", "context_environment_v1"} + with pytest.raises(ValueError, match="enabled fault"): + surfaces.environment_payload(native, native_config()) + + +@pytest.mark.parametrize( + "recorded_click,identifier,expected", + [ + ((300, 400), (100, 200, 160, 40), (-200, -200, 160, 40)), + ((50, 60), (200, 210, 300, 30), (150, 150, 300, 30)), + ((-40, 200), (-200, 10, 100, 20), (-160, -190, 100, 20)), + ], +) +def test_native_wrong_identity_uses_the_recorded_identity_box_not_only_save_label( + recorded_click, identifier, expected +): + workflow = _workflow() + anchor = workflow.steps[-1].anchor + anchor.structural = StructuralLocator(automation_id="commit", role="button") + anchor.click_point = recorded_click + anchor.identifier_region = identifier + staged = [] + + def stage(kind, locator, *, identity_offset=None): + staged.append((kind, locator, identity_offset)) + return "owned-id" + + backend = SimpleNamespace( + stage_qualification_fault=stage, screenshot=lambda: b"changed frame" + ) + driver = WindowsFaultDriver(workflow) + assert driver._screen_fault(_context("wrong_identity", backend=backend)) is not None + assert staged[0][0] == "wrong_identity" + assert staged[0][2] == expected + + +def test_native_wrong_identity_without_recorded_region_refuses_mutation(): + workflow = _workflow() + workflow.steps[-1].anchor.structural = StructuralLocator( + automation_id="commit", role="button" + ) + workflow.steps[-1].anchor.identifier_region = None + staged = [] + backend = SimpleNamespace( + stage_qualification_fault=lambda *args, **kwargs: staged.append(args) + ) + driver = WindowsFaultDriver(workflow) + assert driver._screen_fault(_context("wrong_identity", backend=backend)) is None + assert driver.declined == "native_identity_region_unavailable" and staged == [] + + +def test_native_environment_refuses_agent_without_real_keyboard_receipts(): + native = Native() + native.stage_qualification_fault = lambda *_: None + native.agent_capabilities = lambda: { + "qualification_faults_v1", + "uia_v1", + "context_environment_v1", + } + with pytest.raises(ValueError, match="native keyboard lease"): + surfaces.environment_payload(native, native_config()) diff --git a/packages/flow/tests/test_windows_qualification_faults.py b/packages/flow/tests/test_windows_qualification_faults.py new file mode 100644 index 0000000000..68bdfa5bff --- /dev/null +++ b/packages/flow/tests/test_windows_qualification_faults.py @@ -0,0 +1,370 @@ +"""Qualification mutations require opt-in and real observations, never a claim.""" + +from __future__ import annotations + +import threading +from contextlib import contextmanager + +import pytest +import requests + +from openadapt_flow.backends.win_agent import AgentConfig, create_server +from openadapt_flow.backends.win_agent.qualification_faults import ( + FaultStagingError, + QualificationFaultController, +) +from openadapt_flow.backends.windows_backend import WindowsBackend +from openadapt_flow.ir import StructuralLocator + +PNG = b"\x89PNG\r\n\x1a\n" +TOKEN = "a" * 32 +LOCATOR = { + "automation_id": "save", + "role": "button", + "name": "Save", + "window_name": "Test", +} + + +class Process: + stopped = False + + def poll(self): + return 0 if self.stopped else None + + def terminate(self): + self.stopped = True + + def wait(self, timeout): + assert self.stopped + return 0 + + +class Surface: + """A deterministic input source; assertions test the observation requirement.""" + + staged = False + change_pixels = True + change_uia = True + truncated = False + process = None + + def launch(self, payload): + assert payload["kind"] in {"ambiguity", "wrong_identity", "stale_identity"} + self.staged = True + self.process = Process() + return self.process + + def capture(self): + return PNG + (b"changed" if self.staged and self.change_pixels else b"before") + + def uia(self, operation, payload): + changed = self.staged and self.change_uia + if operation == "find": + return { + "status": "ok", + "match": "ambiguous" if changed else "unique", + "candidate_count": 3 if changed else 1, + "truncated": self.truncated, + "candidates": [ + {**LOCATOR, "bounds": [10, 10, 110, 50], "point": [60, 30]} + ], + } + assert operation == "element-identity-at" + return {"status": "ok", "identity": {"name": "altered" if changed else "Save"}} + + def controller(self): + return QualificationFaultController( + self.uia, self.capture, launch=self.launch, timeout_s=0.02 + ) + + +@pytest.mark.parametrize("kind", ["ambiguity", "wrong_identity", "stale_identity"]) +def test_staging_requires_changed_surface_and_uia_then_cleans_only_its_process(kind): + surface = Surface() + controller = surface.controller() + receipt = controller.stage(kind, LOCATOR) + assert receipt["kind"] == kind + assert len(receipt["mutation_id"]) == 32 + with pytest.raises(FaultStagingError, match="not_owned"): + controller.clear(TOKEN) + assert not surface.process.stopped + assert controller.clear(receipt["mutation_id"]) == {"status": "ok", "cleared": True} + assert surface.process.stopped + + +@pytest.mark.parametrize("missing", ["change_pixels", "change_uia"]) +@pytest.mark.parametrize("kind", ["ambiguity", "wrong_identity", "stale_identity"]) +def test_unobserved_mutation_declines_and_removes_overlay(kind, missing): + surface = Surface() + setattr(surface, missing, False) + with pytest.raises(FaultStagingError, match="not_observed"): + surface.controller().stage(kind, LOCATOR) + assert surface.process.stopped + + +def test_incomplete_census_never_launches_a_fault(): + surface = Surface() + surface.truncated = True + with pytest.raises(FaultStagingError, match="not_unique"): + surface.controller().stage("ambiguity", LOCATOR) + assert not surface.staged + + +def test_server_shutdown_removes_overlay_and_concurrent_stage_is_refused(): + surface = Surface() + controller = surface.controller() + controller.stage("ambiguity", LOCATOR) + with pytest.raises(FaultStagingError, match="mutation_active"): + controller.stage("wrong_identity", LOCATOR) + controller.close() + assert surface.process.stopped + + +class Faults: + def __init__(self): + self.calls = [] + + def stage(self, kind, locator): + self.calls.append((kind, locator)) + return {"status": "ok", "mutation_id": TOKEN, "kind": kind} + + def clear(self, token): + self.calls.append(("clear", token)) + return {"status": "ok", "cleared": True} + + def close(self): + self.calls.append(("close",)) + + +@contextmanager +def agent(*, enabled=True, faults=None): + config = AgentConfig( + host="127.0.0.1", port=0, token="test-token", allow_qualification_faults=enabled + ) + server = create_server(config, fault_controller=faults or Faults()) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_address[1]}" + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + + +def test_fault_routes_are_absent_and_unadvertised_by_default(): + with agent(enabled=False) as url: + assert ( + "qualification_faults_v1" + not in requests.get(url + "/health").json()["capabilities"] + ) + assert requests.post(url + "/qualification/fault", json={}).status_code == 404 + + +def test_opt_in_requires_authentication_configuration_and_each_request(): + with pytest.raises(ValueError, match="authenticated"): + AgentConfig(allow_qualification_faults=True) + faults = Faults() + with agent(faults=faults) as url: + assert requests.post(url + "/qualification/fault", json={}).status_code == 401 + assert not faults.calls + + +@pytest.mark.parametrize( + "payload", + [ + {"kind": "ambiguity", "locator": LOCATOR, "command": "anything"}, + {"kind": "click", "locator": LOCATOR}, + {"kind": [], "locator": LOCATOR}, + {"kind": "ambiguity", "locator": {"selector": "#save"}}, + {"kind": "ambiguity", "locator": {"automation_id": "x" * 513}}, + ], +) +def test_route_rejects_unbounded_or_untyped_requests_before_controller(payload): + faults = Faults() + with agent(faults=faults) as url: + response = requests.post( + url + "/qualification/fault", + json=payload, + headers={"Authorization": "Bearer test-token"}, + ) + assert response.status_code == 400 + assert not faults.calls + + +def test_backend_roundtrip_stages_and_clears_without_delivering_input(): + faults = Faults() + with agent(faults=faults) as url: + with pytest.warns(UserWarning, match="plaintext"): + backend = WindowsBackend(url, auth_token="test-token") + + def forbidden(): + pytest.fail("a qualification mutation is not an application input") + + backend._qualification_input_guard = forbidden + assert ( + backend.stage_qualification_fault("ambiguity", StructuralLocator(**LOCATOR)) + == TOKEN + ) + backend.clear_qualification_fault(TOKEN) + assert faults.calls == [("ambiguity", LOCATOR), ("clear", TOKEN), ("close",)] + + +def test_backend_refuses_disabled_fault_route(): + with agent(enabled=False) as url: + with pytest.warns(UserWarning, match="plaintext"): + backend = WindowsBackend(url, auth_token="test-token") + with pytest.raises(RuntimeError, match="refused"): + backend.stage_qualification_fault("ambiguity", StructuralLocator(**LOCATOR)) + + +def test_backend_rejects_a_mismatched_receipt(): + class WrongFaults(Faults): + def stage(self, kind, locator): + return {"status": "ok", "mutation_id": TOKEN, "kind": "stale_identity"} + + with agent(faults=WrongFaults()) as url: + with pytest.warns(UserWarning, match="plaintext"): + backend = WindowsBackend(url, auth_token="test-token") + with pytest.raises(RuntimeError, match="receipt is invalid"): + backend.stage_qualification_fault("ambiguity", StructuralLocator(**LOCATOR)) + + +def test_failed_cleanup_retains_ownership_and_blocks_another_overlay(): + surface = Surface() + controller = surface.controller() + receipt = controller.stage("ambiguity", LOCATOR) + original = surface.process.terminate + + def unavailable(): + raise OSError("process cleanup temporarily unavailable") + + surface.process.terminate = unavailable + with pytest.raises(OSError): + controller.clear(receipt["mutation_id"]) + with pytest.raises(FaultStagingError, match="mutation_active"): + controller.stage("wrong_identity", LOCATOR) + surface.process.terminate = original + assert controller.clear(receipt["mutation_id"])["cleared"] + + +class RecordSurface(Surface): + record_changes = True + + def launch(self, payload): + self.launched = payload + return super().launch(payload) + + def uia(self, operation, payload): + if operation == "element-identity-at" and payload != {"x": 60, "y": 30}: + changed = self.staged and self.record_changes + return { + "status": "ok", + "identity": { + "name": "Different record 8675309" + if changed + else "Original record", + "automation_id": "qualification-altered-identity" + if changed + else "record-header", + }, + } + return super().uia(operation, payload) + + +@pytest.mark.parametrize( + "offset", [(-50, -20, 120, 30), (100, 80, 300, 45), (-200, 200, 200, 60)] +) +def test_wrong_identity_mutates_recorded_region_at_live_resolved_save(offset): + surface = RecordSurface() + controller = surface.controller() + receipt = controller.stage("wrong_identity", LOCATOR, identity_offset=offset) + dx, dy, width, height = offset + assert surface.launched["identity_bounds"] == [ + 60 + dx, + 30 + dy, + 60 + dx + width, + 30 + dy + height, + ] + assert surface.launched["bounds"] == [10, 10, 110, 50] + controller.clear(receipt["mutation_id"]) + + +def test_changed_save_label_cannot_attest_unchanged_record_identity(): + surface = RecordSurface() + surface.record_changes = False + with pytest.raises(FaultStagingError, match="not_observed"): + surface.controller().stage( + "wrong_identity", LOCATOR, identity_offset=(150, -25, 300, 30) + ) + assert surface.process.stopped + + +@pytest.mark.parametrize( + "kind,offset", + [ + ("wrong_identity", [0, 0, 0, 10]), + ("wrong_identity", [0, 0, True, 10]), + ("wrong_identity", [0, 0, 1.0, 10]), + ("wrong_identity", [0, 0, 8193, 10]), + ("wrong_identity", [0, 0, 8192, 8192]), + ("wrong_identity", [32769, 0, 1, 1]), + ("wrong_identity", [0, 0, 1, 1, 1]), + ("ambiguity", [0, 0, 120, 20]), + ("stale_identity", [0, 0, 120, 20]), + ], +) +def test_identity_rectangle_schema_refuses_unbounded_and_unrelated_mutations( + kind, offset +): + faults = Faults() + with agent(faults=faults) as url: + response = requests.post( + url + "/qualification/fault", + json={ + "kind": kind, + "locator": LOCATOR, + "identity_offset": offset, + }, + headers={"Authorization": "Bearer test-token"}, + ) + assert response.status_code == 400 + assert not faults.calls + + +def test_backend_delivers_only_recorded_relative_identity_rectangle(): + class RecordFaults(Faults): + def stage(self, kind, locator, *, identity_offset=None): + self.calls.append((kind, locator, identity_offset)) + return {"status": "ok", "mutation_id": TOKEN, "kind": kind} + + faults = RecordFaults() + with agent(faults=faults) as url: + with pytest.warns(UserWarning, match="plaintext"): + backend = WindowsBackend(url, auth_token="test-token") + backend.stage_qualification_fault( + "wrong_identity", + StructuralLocator(**LOCATOR), + identity_offset=(-80, -160, 300, 30), + ) + backend.clear_qualification_fault(TOKEN) + assert faults.calls[0] == ("wrong_identity", LOCATOR, (-80, -160, 300, 30)) + + +def test_identity_translation_cannot_escape_absolute_geometry_contract(): + surface = RecordSurface() + with pytest.raises(FaultStagingError, match="geometry_unavailable"): + surface.controller().stage( + "wrong_identity", LOCATOR, identity_offset=(32700, 0, 400, 40) + ) + assert not surface.staged + + +def test_small_identity_box_far_from_target_cannot_allocate_unbounded_union_overlay(): + surface = RecordSurface() + with pytest.raises(FaultStagingError, match="geometry_unavailable"): + surface.controller().stage( + "wrong_identity", LOCATOR, identity_offset=(-20000, -20000, 100, 30) + ) + assert not surface.staged diff --git a/packages/flow/tests/test_winrm_lab.py b/packages/flow/tests/test_winrm_lab.py index 856fe7c056..59c6e1a541 100644 --- a/packages/flow/tests/test_winrm_lab.py +++ b/packages/flow/tests/test_winrm_lab.py @@ -390,3 +390,53 @@ def fake_run(argv, **kw): with pytest.raises(lab_mod.WinRMLabError, match="guest command exited 7"): synthetic_ssh_lab.run_cmd("synthetic-command", timeout_s=90) assert len(calls) == 2 and all(call[1]["timeout"] == 90 for call in calls) + + +@pytest.mark.parametrize("enabled", [False, True]) +def test_launch_agent_deploys_fault_helper_only_on_explicit_opt_in( + monkeypatch, tmp_path, enabled +): + from types import SimpleNamespace + + from openadapt_flow.backends.parallels_vm import AgentEndpoint + from openadapt_flow.backends.win_agent import server as agent_server + from openadapt_flow.backends.win_agent import tls + + monkeypatch.setenv("OAFLOW_WINLAP_HOST", "10.0.0.2") + monkeypatch.setenv("OAFLOW_WINLAP_USER", "test-user") + monkeypatch.setenv("OAFLOW_WINLAP_SSH_KEY", "/test-key") + lab = lab_mod.WinRMLab(profile="winlap") + monkeypatch.setattr(lab, "attach_console", lambda: None) + monkeypatch.setattr(lab, "resolve_python", lambda: r"C:\Python\pythonw.exe") + monkeypatch.setattr(lab, "stop_interactive", lambda name: None) + monkeypatch.setattr(lab, "run_ps", lambda *a, **kw: None) + pushes = [] + launches = [] + monkeypatch.setattr( + lab, "push_file", lambda src, dest: pushes.append((Path(src), dest)) + ) + monkeypatch.setattr( + lab, "launch_interactive", lambda command, **kw: launches.append(command) + ) + cert_dir = tmp_path / "tls" + cert_dir.mkdir() + monkeypatch.setattr( + tls, + "generate_self_signed_cert", + lambda hosts: SimpleNamespace( + certfile=str(cert_dir / "cert.pem"), + keyfile=str(cert_dir / "key.pem"), + fingerprint="a" * 64, + ), + ) + monkeypatch.setattr( + AgentEndpoint, "backend", lambda self: SimpleNamespace(probe=lambda: True) + ) + lab.launch_agent(token="synthetic-test-token", allow_qualification_faults=enabled) + helpers = [src for src, dest in pushes if "qualification_faults" in dest] + assert helpers == ( + [Path(agent_server.__file__).with_name("qualification_faults.py")] + if enabled + else [] + ) + assert ("--allow-qualification-faults" in launches[0]) is enabled