#!/usr/bin/env python3 """Drive the fixture through AT-SPI and log the events a reader would receive. The same scenario runs against native Chromium and against the Wine Access publisher, so the two logs can be compared step by step. Usage: live_driver.py --app-name NAME --log FILE [--title TITLE] Exits non-zero if the scenario cannot run or a password character leaks. """ import argparse import subprocess import sys import time import warnings import gi gi.require_version("Atspi", "2.0") from gi.repository import Atspi, GLib # noqa: E402 warnings.filterwarnings("ignore", category=DeprecationWarning) SECRET = "Qz7Xk9Wv" # no English letter runs, so fragments cannot match event names EVENT_TYPES = [ "object:state-changed", "object:text-changed", "object:text-caret-moved", "object:text-selection-changed", "object:children-changed", "object:property-change:accessible-name", "object:property-change:accessible-description", "object:property-change:accessible-value", "window:activate", "window:deactivate", "document:load-complete", "object:active-descendant-changed", "focus:", ] # State changes that only reflect geometry or rendering, not presentation. IGNORED_STATES = {"showing", "visible"} events = [] recording = False def safe(call, default=None): try: return call() except Exception: return default def describe(accessible): if accessible is None: return "none" role = safe(lambda: accessible.get_role_name(), "?") name = safe(lambda: accessible.get_name(), "") or "" return f"{role}:{name[:40]}" def on_event(event): if not recording: return eventType = event.type if eventType.startswith("object:state-changed:") and eventType.split(":")[-1] in IGNORED_STATES: return data = event.any_data if isinstance(data, str): dataText = repr(data[:40]) elif isinstance(data, Atspi.Accessible): dataText = describe(data) else: dataText = "" events.append(f"{eventType} d1={event.detail1} d2={event.detail2} src={describe(event.source)} data={dataText}") def pump(seconds): context = GLib.MainContext.default() deadline = time.monotonic() + seconds while time.monotonic() < deadline: while context.pending(): context.iteration(False) time.sleep(0.01) def find(accessible, predicate, depth=0): if depth > 60 or accessible is None: return None if predicate(accessible): return accessible for index in range(safe(lambda: accessible.get_child_count(), 0) or 0): found = find(safe(lambda: accessible.get_child_at_index(index)), predicate, depth + 1) if found is not None: return found return None def by_role_name(role, name=None): def predicate(accessible): if safe(lambda: accessible.get_role_name()) != role: return False return name is None or (safe(lambda: accessible.get_name(), "") or "").startswith(name) return predicate def measure_reading(document): """Time what a reader does per line: line text, its range extents and the first character's position, for every text object in document order.""" objects = [] def collect(accessible, depth=0): if depth > 60 or accessible is None: return if safe(lambda: accessible.get_text_iface()) is not None: objects.append(accessible) for index in range(safe(lambda: accessible.get_child_count(), 0) or 0): collect(safe(lambda: accessible.get_child_at_index(index)), depth + 1) collect(document) timings = [] for accessible in objects: count = safe(lambda: Atspi.Text.get_character_count(accessible), 0) or 0 if count <= 0: continue started = time.monotonic() line = safe(lambda: Atspi.Text.get_string_at_offset(accessible, 0, Atspi.TextGranularity.LINE)) end = line.end_offset if line is not None and line.end_offset > 0 else count safe(lambda: Atspi.Text.get_range_extents(accessible, 0, end, Atspi.CoordType.SCREEN)) safe(lambda: Atspi.Text.get_character_extents(accessible, 0, Atspi.CoordType.SCREEN)) timings.append((time.monotonic() - started) * 1000) if not timings: return "reading: no text objects" timings.sort() return (f"reading: objects={len(timings)} total={sum(timings):.0f}ms median={timings[len(timings) // 2]:.1f}ms " f"max={timings[-1]:.1f}ms") def xdotool(title, *arguments): subprocess.run(["xdotool", "search", "--name", title, "windowactivate", "--sync"], capture_output=True) subprocess.run(["xdotool", "search", "--name", title, "windowfocus", "--sync"], capture_output=True) subprocess.run(["xdotool", *arguments], capture_output=True) def main(): global recording parser = argparse.ArgumentParser() parser.add_argument("--app-name", required=True) parser.add_argument("--log", required=True) parser.add_argument("--title", default="Wine Access Electron Test") parser.add_argument("--step-seconds", type=float, default=1.5) options = parser.parse_args() listener = Atspi.EventListener.new(on_event) for eventType in EVENT_TYPES: listener.register(eventType) deadline = time.monotonic() + 60 application = document = None while time.monotonic() < deadline and document is None: desktop = Atspi.get_desktop(0) for index in range(desktop.get_child_count()): candidate = safe(lambda: desktop.get_child_at_index(index)) if candidate is not None and options.app_name.lower() in (safe(lambda: candidate.get_name(), "") or "").lower(): application = candidate document = find(candidate, lambda a: safe(lambda: a.get_role()) == Atspi.Role.DOCUMENT_WEB and (safe(lambda: a.get_child_count(), 0) or 0) > 0) if document is not None: break pump(0.5) if document is None: print("document not found") return 3 userName = find(document, by_role_name("entry", "User name")) password = find(document, by_role_name("password text", "Password")) checkbox = find(document, by_role_name("check box", "Remember me")) addButton = find(document, by_role_name("button", "Add item")) link = find(document, by_role_name("link", "inline link")) table = find(document, by_role_name("table")) missing = [name for name, value in (("entry", userName), ("password", password), ("checkbox", checkbox), ("add button", addButton), ("link", link), ("table", table)) if value is None] if missing: print(f"fixture objects not found: {missing}") return 3 steps = [ ("focus entry", lambda: Atspi.Component.grab_focus(userName)), ("type abc", lambda: xdotool(options.title, "type", "--delay", "100", "abc")), ("caret to 1", lambda: Atspi.Text.set_caret_offset(userName, 1)), ("select 0-2", lambda: Atspi.Text.add_selection(userName, 0, 2)), ("check checkbox", lambda: Atspi.Action.do_action(checkbox, 0)), ("add item", lambda: Atspi.Action.do_action(addButton, 0)), ("follow link", lambda: Atspi.Action.do_action(link, 0)), ("scroll table", lambda: Atspi.Component.scroll_to(table, Atspi.ScrollType.TOP_EDGE)), ("focus password", lambda: Atspi.Component.grab_focus(password)), ("type password", lambda: xdotool(options.title, "type", "--delay", "100", SECRET)), ] print(measure_reading(document), flush=True) print(measure_reading(document) + " (second pass)", flush=True) log = [] pump(1.0) recording = True pump(0.5) events.clear() for label, action in steps: result = safe(action, "error") pump(options.step_seconds) log.append(f"STEP {label} result={result}") log.extend(events) events.clear() recording = False with open(options.log, "w", encoding="utf-8") as logFile: logFile.write("\n".join(log) + "\n") # Any three consecutive secret characters inside an event's text payload, # or the whole secret anywhere, is a leak. fragments = [SECRET[index:index + 3] for index in range(len(SECRET) - 2)] leaked = [line for line in log if SECRET in line or (" data='" in line and any(fragment in line.split(" data=", 1)[1] for fragment in fragments))] print(f"steps={len(steps)} events={sum(1 for line in log if not line.startswith('STEP'))} " f"passwordLeaks={len(leaked)}") return 1 if leaked else 0 if __name__ == "__main__": sys.exit(main())