interplane.Get Omega
Read in your language

hop

Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.

Brought by drakestapleton

branch main Branches Tags History

hop / Linux / tests / window_check.py

209 lines · 10332 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Independent Linux UI probe: Xvfb + real X11 keyboard and pointer events.
3
4Python is a measuring tool only. It is never installed with Hop or linked into it.
5Pass --compiler and optionally --evidence to retain source, logs and an XWD image.
6"""
7import argparse
8import json
9import os
10from pathlib import Path
11import secrets
12import socket
13import struct
14import subprocess
15import tempfile
16import time
17
18STUB = r'''
19text wt_rows "First result\nSecond result\nThird result\n"
20text wt_query "QUERY "
21text wt_action "ACT "
22text wt_nl "\n"
23global wt_byte uchar 1
24fn hop_query to void
25r = enlarge lx_rows len wt_rows
26for i ulong len wt_rows bound 256
27put lx_rows i get wt_rows i
28end
29put lx_rn 0 len wt_rows
30k = write 1 wt_query 0 len wt_query
31k = write 1 lx_query 0 get lx_qn 0
32k = write 1 wt_nl 0 1
33end
34fn hop_activate to int
35k = write 1 wt_action 0 len wt_action
36put wt_byte 0 uchar add get lx_pick 0 48
37k = write 1 wt_byte 0 1
38k = write 1 wt_nl 0 1
39ret 0
40end
41fn main to int
42ret lx_main
43end
44'''
45
46
47def authority(display, cookie, hostname=None, family=256):
48 address = socket.gethostname().encode() if hostname is None else hostname
49 fields = [address, str(display).encode(),
50 b"MIT-MAGIC-COOKIE-1", cookie]
51 return struct.pack('>H', family) + b''.join(struct.pack('>H', len(v)) + v for v in fields)
52
53
54def checked(cmd, env=None):
55 return subprocess.run(cmd, env=env, capture_output=True, check=True).stdout
56
57
58def run(compiler, evidence, source_path=None):
59 root = Path(__file__).resolve().parents[2]
60 evidence.mkdir(parents=True, exist_ok=True)
61 source = (source_path or root / 'Linux/window.om').read_bytes() + STUB.encode()
62 (evidence / 'window-test.om').write_bytes(source)
63 exe = evidence / 'window-test'
64 built = subprocess.run([str(compiler)], input=source, capture_output=True)
65 (evidence / 'compile.log').write_bytes(built.stderr)
66 assert built.returncode == 0, built.stderr.decode()
67 exe.write_bytes(built.stdout)
68 exe.chmod(0o755)
69 checks = []
70 display = 171
71 assert not Path(f'/tmp/.X11-unix/X{display}').exists(), 'test display is already occupied'
72 auth = evidence / 'Xauthority'
73 server_auth = evidence / 'server-Xauthority'
74 cookie = secrets.token_bytes(16)
75 other_host = b'hop-test-other-machine.invalid'
76 assert other_host != socket.gethostname().encode()
77 server_auth.write_bytes(authority(display, cookie))
78 server_auth.chmod(0o600)
79 # The server trusts only its actual cookie. The client also carries another machine's
80 # same-display credential, ahead of the valid one, as a shared or moved HOME can.
81 auth.write_bytes(authority(display + 1, secrets.token_bytes(16)) +
82 authority(display, secrets.token_bytes(16), other_host) +
83 authority(display, cookie))
84 auth.chmod(0o600)
85 server_log = open(evidence / 'xvfb.log', 'wb')
86 server = subprocess.Popen(['Xvfb', f':{display}', '-screen', '0', '1024x768x24',
87 '-nolisten', 'tcp', '-auth', str(server_auth)],
88 stdout=server_log, stderr=server_log)
89 proc = None
90 try:
91 for _ in range(100):
92 if server.poll() is not None:
93 raise AssertionError((evidence / 'xvfb.log').read_text())
94 if Path(f'/tmp/.X11-unix/X{display}').exists():
95 break
96 time.sleep(.02)
97 env = dict(os.environ, DISPLAY=f':{display}.0', XAUTHORITY=str(auth))
98 checked(['xdpyinfo'], env)
99 proc = subprocess.Popen([str(exe)], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
100 window = None
101 for _ in range(100):
102 found = subprocess.run(['xdotool', 'search', '--name', '^Hop$'], env=env, capture_output=True)
103 if found.returncode == 0 and found.stdout.strip():
104 window = found.stdout.splitlines()[0].decode()
105 break
106 if proc.poll() is not None:
107 break
108 time.sleep(.02)
109 assert window, 'Hop did not create its window: ' + repr(proc.communicate(timeout=1))
110 checks.append('same-display credentials for another hostname are skipped, matching xdpyinfo; screen suffix accepted')
111 checked(['xdotool', 'type', '--clearmodifiers', 'hello'], env)
112 checked(['xdotool', 'key', 'BackSpace', 'Shift_L+a'], env)
113 checked(['xdotool', 'key', 'Down', 'Return'], env)
114 checked(['xdotool', 'mousemove', '--window', window, '40', '174', 'click', '1'], env)
115 checked(['xdotool', 'key', 'ctrl+u'], env)
116 checked(['xdotool', 'type', '--clearmodifiers', 'world'], env)
117 checked(['xwd', '-silent', '-id', window, '-out', str(evidence / 'window.xwd')], env)
118 checked(['xdotool', 'key', 'Escape'], env)
119 out, err = proc.communicate(timeout=5)
120 (evidence / 'window.stdout').write_bytes(out)
121 (evidence / 'window.stderr').write_bytes(err)
122 assert proc.returncode == 0 and not err, (proc.returncode, err)
123 assert b'QUERY hello\n' in out, out
124 assert b'QUERY hellA\n' in out, out
125 checks.append('real typing, backspace and Shift reach the query')
126 assert b'ACT 1\n' in out and b'ACT 2\n' in out, out
127 checks.append('Down + Enter and a pointer click activate the selected rows')
128 assert b'QUERY world\n' in out, out
129 checks.append('Control+U clears and Escape closes cleanly')
130 wrong = evidence / 'wrong-Xauthority'
131 wrong.write_bytes(authority(display, secrets.token_bytes(16)))
132 rejected = subprocess.run([str(exe)], env=dict(env, XAUTHORITY=str(wrong)), capture_output=True, timeout=5)
133 assert rejected.returncode == 1 and b'refused' in rejected.stderr, rejected
134 standard_rejected = subprocess.run(['xdpyinfo'], env=dict(env, XAUTHORITY=str(wrong)),
135 capture_output=True, timeout=5)
136 assert standard_rejected.returncode != 0, standard_rejected
137 checks.append('wrong display cookie is refused visibly by Hop and xdpyinfo')
138 wrong.write_bytes(authority(display, cookie, other_host))
139 standard_rejected = subprocess.run(['xdpyinfo'], env=dict(env, XAUTHORITY=str(wrong)),
140 capture_output=True, timeout=5)
141 assert standard_rejected.returncode != 0, standard_rejected
142 rejected = subprocess.run([str(exe)], env=dict(env, XAUTHORITY=str(wrong)), capture_output=True, timeout=5)
143 assert rejected.returncode == 1 and b'refused' in rejected.stderr, rejected
144 checks.append('a different host record alone is refused even when its cookie is valid, matching xdpyinfo')
145 wild = evidence / 'wild-Xauthority'
146 wild.write_bytes(authority(display, cookie, other_host, family=65535))
147 wild.chmod(0o600)
148 wild_env = dict(env, XAUTHORITY=str(wild))
149 checked(['xdpyinfo'], wild_env)
150 proc = subprocess.Popen([str(exe)], env=wild_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
151 wild_window = None
152 for _ in range(100):
153 found = subprocess.run(['xdotool', 'search', '--name', '^Hop$'], env=wild_env, capture_output=True)
154 if found.returncode == 0 and found.stdout.strip():
155 wild_window = found.stdout.splitlines()[0].decode()
156 break
157 if proc.poll() is not None:
158 break
159 time.sleep(.02)
160 assert wild_window, 'Hop did not accept the explicit FamilyWild credential'
161 checked(['xdotool', 'key', 'Escape'], wild_env)
162 out, err = proc.communicate(timeout=5)
163 assert proc.returncode == 0 and not err, (proc.returncode, err)
164 checks.append('explicit FamilyWild still accepts its deliberate address wildcard, matching xdpyinfo')
165 missing = subprocess.run([str(exe)], env={k: v for k, v in env.items() if k != 'DISPLAY'}, capture_output=True, timeout=5)
166 assert missing.returncode == 1 and b'DISPLAY' in missing.stderr, missing
167 remote = subprocess.run([str(exe)], env=dict(env, DISPLAY='remote.example:0'), capture_output=True, timeout=5)
168 assert remote.returncode == 1 and b'local X11' in remote.stderr, remote
169 checks.append('missing desktop and remote display are refused visibly')
170 home = evidence / 'home'
171 home.mkdir(exist_ok=True)
172 (home / '.Xauthority').write_bytes(auth.read_bytes())
173 default_env = {k: v for k, v in dict(env, HOME=str(home)).items() if k != 'XAUTHORITY'}
174 proc = subprocess.Popen([str(exe)], env=default_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
175 time.sleep(.2)
176 assert proc.poll() is None
177 checked(['xdotool', 'key', 'Escape'], env)
178 out, err = proc.communicate(timeout=5)
179 assert proc.returncode == 0 and not err, (proc.returncode, err)
180 checks.append('default HOME/.Xauthority works')
181 result = {'status': 'PASS', 'checks': checks, 'not_run': ['native Wayland', 'XWayland', 'non-Latin rendering']}
182 (evidence / 'result.json').write_text(json.dumps(result, indent=2) + '\n')
183 print(json.dumps(result))
184 finally:
185 if proc is not None and proc.poll() is None:
186 proc.terminate()
187 proc.wait(timeout=5)
188 server.terminate()
189 server.wait(timeout=5)
190 server_log.close()
191 # Cookies grant access to a now-terminated, test-only X server, but are not retained.
192 auth.unlink(missing_ok=True)
193 server_auth.unlink(missing_ok=True)
194 (evidence / 'wild-Xauthority').unlink(missing_ok=True)
195 (evidence / 'wrong-Xauthority').unlink(missing_ok=True)
196 (evidence / 'home' / '.Xauthority').unlink(missing_ok=True)
197
198
199if __name__ == '__main__':
200 parser = argparse.ArgumentParser()
201 parser.add_argument('--compiler', required=True, type=Path)
202 parser.add_argument('--evidence', type=Path)
203 parser.add_argument('--source', type=Path, help='independent wrong-version or mutation control')
204 args = parser.parse_args()
205 if args.evidence:
206 run(args.compiler.resolve(), args.evidence.resolve(), args.source)
207 else:
208 with tempfile.TemporaryDirectory(prefix='hop-window-check-') as directory:
209 run(args.compiler.resolve(), Path(directory), args.source)