Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 62 additions & 2 deletions packages/flow/openadapt_flow/backends/win_agent/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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]
Expand Down
12 changes: 10 additions & 2 deletions packages/flow/tests/e2e/test_native_keyboard_lease.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
150 changes: 148 additions & 2 deletions packages/flow/tests/test_structural_value_completeness.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 == []
Loading