From 740fceb345eb548794bcbc35740eb8565583722b Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 09:29:31 -0500 Subject: [PATCH] fix(flow): let the strict UIA census pass a password field it cannot match Since #2291 the strict census stopped at any control whose IsPassword was True, wherever it sat on the desktop. The read endpoint then reported the cut-short census as match=ambiguous, reason=not_unique with whatever it had found so far. In the hosted Patient Notes test the window holds one patientHeader and a planted password box, so every structural read refused as "ambiguous, candidate_count=1, not_unique". An affirmatively protected control (IsPassword True, or a native password edit) is now ruled out from AutomationId and control type alone when the locator's id or role cannot match it and it has no subtree. Its Name and value are never read. A locator that could still name it, an unreadable selector, any unknown sensitivity status, or a second real match still refuses as before. A census cut short now reports reason=census_incomplete instead of not_unique, so a single candidate no longer reads as a duplicate. --- .../backends/win_agent/server.py | 64 +++++++- .../tests/e2e/test_native_keyboard_lease.py | 12 +- .../test_structural_value_completeness.py | 150 +++++++++++++++++- 3 files changed, 220 insertions(+), 6 deletions(-) diff --git a/packages/flow/openadapt_flow/backends/win_agent/server.py b/packages/flow/openadapt_flow/backends/win_agent/server.py index d65c8f03ac..53fc9b1448 100644 --- a/packages/flow/openadapt_flow/backends/win_agent/server.py +++ b/packages/flow/openadapt_flow/backends/win_agent/server.py @@ -1182,6 +1182,54 @@ def _candidate( return candidate +def _affirmatively_protected(native_api: Any, error: Exception) -> bool: + """True only for a positive password verdict, never an unknown status.""" + # Identity with the helper's own enum members; an older helper without + # them never qualifies, so its stops are unchanged. + stage = getattr(error, "census_stage", None) + stages = getattr(native_api, "SensitivityStage", None) + protected = getattr(getattr(native_api, "EditEvidence", None), "PROTECTED", None) + if stage is None or stages is None: + return False + if stage is getattr(stages, "PROVIDER_REFUSAL", None): + return True + return ( + protected is not None + and stage is getattr(stages, "NATIVE_EDIT", None) + and getattr(error, "edit_evidence", None) is protected + ) + + +def _protected_node_excluded(locator: dict[str, Any], control: object) -> bool: + """Whether a password control provably cannot match ``locator``. + + Only AutomationId and control type are read: neither is field content. A + locator that could still name the control (role+name only, or a matching + id and role) cannot rule it out, and neither can an unreadable selector or + a subtree, so those keep the census incomplete. + """ + automation_id = _control_value(control, "AutomationId", None) + type_name = _control_value(control, "ControlTypeName", None) + if not isinstance(automation_id, str) or not isinstance(type_name, str): + return False + role = ( + "button" + if type_name == "SplitButtonControl" + else _CONTROL_TO_ROLE.get(type_name) + ) + expected_id, expected_role = locator.get("automation_id"), locator.get("role") + if not ( + (expected_id is not None and (automation_id or None) != expected_id) + or (expected_role is not None and role != expected_role) + ): + return False + children = _control_value(control, "GetChildren", None) + try: + return callable(children) and not list(children()) + except Exception: # noqa: BLE001 - an unknown subtree may hide a match + return False + + def _find_candidates( locator: dict[str, Any], auto: Any, *, strict_walk: bool = False ) -> tuple[list[tuple[Any, dict[str, Any]]], bool]: @@ -1238,7 +1286,17 @@ def incomplete(stage: str, error: Exception | None = None): # turn a partial query into unique value authority. try: native_api = _native_value_api() - native_api.require_non_sensitive_structure(control) + try: + native_api.require_non_sensitive_structure(control) + except native_api.ValueUnavailable as exc: + if not ( + _affirmatively_protected(native_api, exc) + and _protected_node_excluded(locator, control) + ): + raise + # A password field the locator provably cannot name is + # no candidate. Its Name and value are never read. + continue facts = { key: _read_control_value(control, key, None) for key in ("AutomationId", "Name", "ControlTypeName") @@ -1980,7 +2038,9 @@ def _perform_uia_initialized( "value_identity": None, "read_scope": read_locator, "preview_text": None, - "reason": "not_unique", + # A census cut short is not evidence of a second match: keep the + # refusal, but name it so one candidate never reads as a duplicate. + "reason": "census_incomplete" if truncated else "not_unique", } if unique: control, candidate = found[0] diff --git a/packages/flow/tests/e2e/test_native_keyboard_lease.py b/packages/flow/tests/e2e/test_native_keyboard_lease.py index f5e30090ee..851642e4a9 100644 --- a/packages/flow/tests/e2e/test_native_keyboard_lease.py +++ b/packages/flow/tests/e2e/test_native_keyboard_lease.py @@ -173,7 +173,11 @@ def _read(backend, automation_id: str) -> str: if match != "unique" or count != 1: # WindowsBackend validated the match and count. Keep provider text, # previews and unrecognized reason strings out of the failure report. - reason = "not_unique" if result["reason"] == "not_unique" else "unclassified" + reason = ( + result["reason"] + if result["reason"] in {"not_unique", "census_incomplete"} + else "unclassified" + ) pytest.fail( f"UIA census refused (match={match}, candidate_count={count}, reason={reason})", pytrace=False, @@ -198,7 +202,11 @@ def _read_label(backend, automation_id: str) -> str: pytest.fail("UIA structural read unavailable", pytrace=False) match, count = result["match"], result["candidate_count"] if match != "unique" or count != 1: - reason = "not_unique" if result["reason"] == "not_unique" else "unclassified" + reason = ( + result["reason"] + if result["reason"] in {"not_unique", "census_incomplete"} + else "unclassified" + ) pytest.fail( f"UIA census refused (match={match}, candidate_count={count}, reason={reason})", pytrace=False, diff --git a/packages/flow/tests/test_structural_value_completeness.py b/packages/flow/tests/test_structural_value_completeness.py index 468649f708..880cf48099 100644 --- a/packages/flow/tests/test_structural_value_completeness.py +++ b/packages/flow/tests/test_structural_value_completeness.py @@ -263,7 +263,7 @@ def property_value(property_id, _): request = {"locator": {"automation_id": "field"}} monkeypatch.delenv("OAFLOW_AGENT_TRACE_CENSUS", raising=False) refusal = perform("read", request) - assert refusal["reason"] == "not_unique" and not refusal["complete"] + assert refusal["reason"] == "census_incomplete" and not refusal["complete"] assert capsys.readouterr().err == "" original_calls = list(calls) calls.clear() @@ -356,7 +356,7 @@ def password_char(*_): request = {"locator": {"automation_id": "field"}} monkeypatch.delenv("OAFLOW_AGENT_TRACE_CENSUS", raising=False) refusal = perform("read", request) - assert refusal["reason"] == "not_unique" and not refusal["complete"] + assert refusal["reason"] == "census_incomplete" and not refusal["complete"] assert capsys.readouterr().err == "" original_calls = list(calls) calls.clear() @@ -740,3 +740,149 @@ def test_non_value_windowless_structural_controls_do_not_abort_strict_census( result = perform("read", {"locator": {"automation_id": "field"}}) assert result["match"] == "unique" assert result["complete"] is True and result["text"] == "exact" + + +class _PasswordControl(_Control): + """An affirmatively protected field that records any content access.""" + + def __init__(self, automation_id, *, children=()): + super().__init__( + "EditControl", value="synthetic secret", password=True, children=children + ) + self.AutomationId = automation_id + self.content_reads = [] + + @property + def Name(self): + self.content_reads.append("Name") + return "Password" + + @Name.setter + def Name(self, _value): + pass + + def GetValuePattern(self): + self.content_reads.append("value") + return super().GetValuePattern() + + +def _census(monkeypatch, *children): + import sys + + window = _window(*children) + perform = _agent(monkeypatch, window) + sys.modules["uiautomation"].GetRootControl = lambda: window + return perform + + +def _protect_natively(monkeypatch, password): + """IsPassword unsupported, but the native edit is a password edit.""" + from openadapt_flow.backends.win_agent import native_value + from tests.test_approval_form_fields import _UNSUPPORTED_PROPERTY + + password.IsPassword = _UNSUPPORTED_PROPERTY + original = native_value._native_edit_evidence + monkeypatch.setattr( + native_value, + "_native_edit_evidence", + lambda control: ( + native_value.EditEvidence.PROTECTED + if control is password + else original(control) + ), + ) + + +@pytest.mark.parametrize("protection", ["provider_refusal", "native_edit_protected"]) +def test_one_target_beside_a_password_field_is_unique(monkeypatch, protection): + # The hosted Patient Notes failure: one patientHeader, and a password box + # elsewhere in the window, refused as match=ambiguous, candidate_count=1. + target = _Control("TextControl", value="Patient: Ada Lovelace") + target.AutomationId = "field" + password = _PasswordControl("secret") + if protection == "native_edit_protected": + _protect_natively(monkeypatch, password) + answer = _census(monkeypatch, target, password)( + "read", {"locator": {"automation_id": "field"}} + ) + assert answer["match"] == "unique" and answer["candidate_count"] == 1 + assert answer["complete"] is True and answer["reason"] is None + assert answer["text"] == "Patient: Ada Lovelace" + assert password.content_reads == [] + + +def test_a_password_field_of_another_role_does_not_stop_the_census(monkeypatch): + target = _Control("ButtonControl", name="Save") + target.AutomationId = "field" + password = _PasswordControl("field") + answer = _census(monkeypatch, target, password)( + "read", {"locator": {"automation_id": "field", "role": "button"}} + ) + assert answer["match"] == "unique" and answer["candidate_count"] == 1 + assert answer["reason"] != "census_incomplete" + assert password.content_reads == [] + + +@pytest.mark.parametrize( + "locator,password_id,subtree,stage", + [ + ({"automation_id": "field"}, "field", False, "sensitivity_provider_refusal"), + ( + {"automation_id": "field", "role": "textbox"}, + "field", + False, + "sensitivity_provider_refusal", + ), + ( + {"role": "textbox", "name": "Password"}, + "secret", + False, + "sensitivity_provider_refusal", + ), + ({"automation_id": "field"}, "secret", True, "sensitivity_provider_refusal"), + ( + {"automation_id": "field"}, + "field", + False, + "sensitivity_native_edit/other_type/protected", + ), + ], +) +def test_a_password_field_the_locator_could_name_still_stops_the_census( + monkeypatch, capsys, locator, password_id, subtree, stage +): + target = _Control("EditControl", value="exact", name=locator.get("name", "")) + target.AutomationId = locator.get("automation_id", "") + children = (_Control("TextControl"),) if subtree else () + password = _PasswordControl(password_id, children=children) + if stage.startswith("sensitivity_native_edit"): + _protect_natively(monkeypatch, password) + perform = _census(monkeypatch, target, password) + monkeypatch.setenv("OAFLOW_AGENT_TRACE_CENSUS", "1") + answer = perform("read", {"locator": locator}) + # One match seen before the stop: refused, and named as an incomplete + # census rather than a duplicate. + assert answer["match"] == "ambiguous" and answer["candidate_count"] == 1 + assert answer["reason"] == "census_incomplete" + assert answer["complete"] is False and answer["text"] is None + assert answer["point"] is None and answer["preview_text"] is None + assert password.content_reads == [] + assert capsys.readouterr().err.splitlines() == [ + f"[win-agent] strict census stop: {stage}" + ] + + +def test_two_matching_controls_beside_a_password_field_still_refuse(monkeypatch): + first = _Control("EditControl", value="first") + first.AutomationId = "field" + second = _Control("EditControl", value="second") + second.AutomationId = "field" + password = _PasswordControl("secret") + answer = _census(monkeypatch, first, password, second)( + "read", {"locator": {"automation_id": "field"}} + ) + assert answer["match"] == "ambiguous" and answer["candidate_count"] == 2 + assert answer["reason"] == "not_unique" + assert answer["complete"] is False and answer["text"] is None + assert answer["point"] is None and answer["preview_text"] is None + assert password.content_reads == []