| 1 | """Isolated real-X11 clipboard check; never connects to the user's VM. |
| 2 | |
| 3 | Run with CAGE_CLIPBOARD_QA_SSH_CONFIG and CAGE_CLIPBOARD_QA_SSH_TARGET. |
| 4 | The supplied guest must have disposable :77 and :78 displays and the helper. |
| 5 | """ |
| 6 | import base64 |
| 7 | import json |
| 8 | import os |
| 9 | from pathlib import Path |
| 10 | import queue |
| 11 | import subprocess |
| 12 | import threading |
| 13 | import time |
| 14 | |
| 15 | ssh = ['ssh', '-F', os.environ['CAGE_CLIPBOARD_QA_SSH_CONFIG'], os.environ['CAGE_CLIPBOARD_QA_SSH_TARGET']] |
| 16 | directory = '/tmp/cage-clipboard-ui-qa' |
| 17 | helper = directory + '/shared-clipboard.py' |
| 18 | bridge = subprocess.Popen(ssh + ['sudo python3 ' + helper], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) |
| 19 | events = queue.Queue() |
| 20 | threading.Thread(target=lambda: [events.put(json.loads(line)) for line in bridge.stdout], daemon=True).start() |
| 21 | owners = [] |
| 22 | |
| 23 | |
| 24 | def remote(code, display=':78'): |
| 25 | return subprocess.check_output(ssh + ['env DISPLAY=' + display + ' NO_AT_BRIDGE=1 python3 -'], input=code, text=True, timeout=12) |
| 26 | |
| 27 | |
| 28 | def expect(predicate): |
| 29 | until = time.monotonic() + 8 |
| 30 | observed = [] |
| 31 | while time.monotonic() < until: |
| 32 | try: |
| 33 | value = events.get(timeout=.2) |
| 34 | except queue.Empty: |
| 35 | if bridge.poll() is not None: |
| 36 | raise RuntimeError('Clipboard bridge exited: ' + bridge.stderr.read()) |
| 37 | continue |
| 38 | observed.append({key: (len(value[key]) if key == 'png' else value[key]) for key in value}) |
| 39 | if predicate(value): |
| 40 | return value |
| 41 | raise AssertionError('Expected clipboard event not received: ' + json.dumps(observed)) |
| 42 | |
| 43 | |
| 44 | def send(value, serial): |
| 45 | bridge.stdin.write(json.dumps({**value, 'serial': serial}) + '\n') |
| 46 | bridge.stdin.flush() |
| 47 | expect(lambda event: event.get('ack') == serial) |
| 48 | |
| 49 | |
| 50 | imports = '''import gi, base64, json, ctypes as C |
| 51 | gi.require_version('Gtk', '3.0') |
| 52 | from gi.repository import Gtk, Gdk, GdkPixbuf, GLib |
| 53 | Gtk.init([]) |
| 54 | clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) |
| 55 | ''' |
| 56 | |
| 57 | |
| 58 | def owner(action, display=':78', user=None): |
| 59 | code = imports + action + "\nprint('ready',flush=True)\nGLib.timeout_add_seconds(30, lambda: (Gtk.main_quit(), False)[1])\nGtk.main()\n" |
| 60 | prefix = 'sudo -H -u ' + user + ' ' if user else '' |
| 61 | process = subprocess.Popen(ssh + [prefix + 'env DISPLAY=' + display + ' NO_AT_BRIDGE=1 python3 -'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) |
| 62 | process.stdin.write(code); process.stdin.close() |
| 63 | assert process.stdout.readline().strip() == 'ready' |
| 64 | owners.append(process) |
| 65 | return process |
| 66 | |
| 67 | |
| 68 | try: |
| 69 | send({'text': 'host 中文🙂\nsecond line'}, 1) |
| 70 | print('host text acknowledged', flush=True) |
| 71 | for display in (':77', ':78'): |
| 72 | assert json.loads(remote(imports + 'print(json.dumps(clipboard.wait_for_text()))', display)) == 'host 中文🙂\nsecond line' |
| 73 | print('both displays read text', flush=True) |
| 74 | |
| 75 | |
| 76 | owner("""window = Gtk.Window() |
| 77 | window.set_default_size(240,100) |
| 78 | window.move(40,40) |
| 79 | button = Gtk.Button(label='Copy message') |
| 80 | button.connect('clicked', lambda _button: clipboard.set_text('guest 消息🙂\\nexact text', -1)) |
| 81 | window.add(button) |
| 82 | window.show_all() |
| 83 | """) |
| 84 | subprocess.check_call(ssh + ['env DISPLAY=:78 xdotool mousemove 160 90 click 1']) |
| 85 | expect(lambda event: event.get('text') == 'guest 消息🙂\nexact text') |
| 86 | print('native button copy received', flush=True) |
| 87 | assert json.loads(remote(imports + 'print(json.dumps(clipboard.wait_for_text()))', ':77')) == 'guest 消息🙂\nexact text' |
| 88 | |
| 89 | owner("image = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, True, 8, 12, 9)\nimage.fill(0x2468acff)\nclipboard.set_image(image)", ':77') |
| 90 | image = expect(lambda event: 'png' in event) |
| 91 | print('native image copy received', flush=True) |
| 92 | assert base64.b64decode(image['png']).startswith(b'\x89PNG\r\n\x1a\n') |
| 93 | assert json.loads(remote(imports + "image=clipboard.wait_for_image(); print(json.dumps([image.get_width(),image.get_height()]))")) == [12, 9] |
| 94 | send({'png': image['png']}, 2) |
| 95 | assert json.loads(remote(imports + "image=clipboard.wait_for_image(); print(json.dumps([image.get_width(),image.get_height()]))", ':77')) == [12, 9] |
| 96 | |
| 97 | paths = [directory + '/中文.bin', directory + '/folder'] |
| 98 | remote("from pathlib import Path\np=Path('/tmp/cage-clipboard-ui-qa'); (p/'中文.bin').write_bytes(bytes([0,255,128])); (p/'folder').mkdir(exist_ok=True); (p/'folder'/'blank').write_bytes(b'')") |
| 99 | send({'files': paths}, 3) |
| 100 | print('files acknowledged', flush=True) |
| 101 | for display in (':77', ':78'): |
| 102 | actual = json.loads(remote(imports + 'print(json.dumps(clipboard.wait_for_uris()))', display)) |
| 103 | assert len(actual) == 2 and actual[0].endswith('%E4%B8%AD%E6%96%87.bin') and actual[1].endswith('/folder') |
| 104 | |
| 105 | file_owner = """ |
| 106 | gtk = C.CDLL('libgtk-3.so.0'); gdk = C.CDLL('libgdk-3.so.0') |
| 107 | gdk.gdk_atom_intern_static_string.restype=C.c_void_p |
| 108 | gdk.gdk_atom_intern_static_string.argtypes=[C.c_char_p] |
| 109 | class Target(C.Structure): |
| 110 | _fields_=[('target',C.c_char_p),('flags',C.c_uint),('info',C.c_uint)] |
| 111 | Provide=C.CFUNCTYPE(None,C.c_void_p,C.c_void_p,C.c_uint,C.c_void_p) |
| 112 | Clear=C.CFUNCTYPE(None,C.c_void_p,C.c_void_p) |
| 113 | gtk.gtk_selection_data_set.argtypes=[C.c_void_p,C.c_void_p,C.c_int,C.c_void_p,C.c_int] |
| 114 | gtk.gtk_clipboard_set_with_data.argtypes=[C.c_void_p,C.POINTER(Target),C.c_uint,Provide,Clear,C.c_void_p] |
| 115 | encoded=(uri+'\\r\\n').encode(); buffer=C.create_string_buffer(encoded) |
| 116 | @Provide |
| 117 | def provide(_clipboard,selection,_info,_data): |
| 118 | gtk.gtk_selection_data_set(selection,gdk.gdk_atom_intern_static_string(b'text/uri-list'),8,buffer,len(encoded)) |
| 119 | @Clear |
| 120 | def clear(_clipboard,_data): pass |
| 121 | targets=(Target*1)(Target(b'text/uri-list',0,0)) |
| 122 | assert gtk.gtk_clipboard_set_with_data(hash(clipboard),targets,1,provide,clear,None) |
| 123 | """ |
| 124 | owner("from pathlib import Path\np=Path.home()/'.cache/clipboard-private-qa'; p.mkdir(parents=True,exist_ok=True,mode=0o700); p.chmod(0o700); file=p/'private.bin'; file.write_bytes(bytes([0,255,128])); uri=file.as_uri()\n" + file_owner, ':77', 'cage-browser') |
| 125 | copied = expect(lambda event: 'files' in event) |
| 126 | assert copied['source'] == 'cage' and copied['files'][0].startswith('/tmp/cage-clipboard-') |
| 127 | actual = json.loads(remote(imports + 'from pathlib import Path\nfrom urllib.parse import urlsplit,unquote\nuris=clipboard.wait_for_uris(); print(json.dumps(list(Path(unquote(urlsplit(uris[0]).path)).read_bytes())))')) |
| 128 | assert actual == [0,255,128], 'private files must be materialized for the other application UID' |
| 129 | owner("uri='file:///etc/shadow'\n" + file_owner, ':77', 'cage-browser') |
| 130 | expect(lambda event: 'error' in event) |
| 131 | |
| 132 | |
| 133 | owner("Gtk.Clipboard.get(Gdk.SELECTION_PRIMARY).set_text('drag selection',-1)") |
| 134 | time.sleep(.3) |
| 135 | while not events.empty(): |
| 136 | assert events.get().get('text') != 'drag selection' |
| 137 | print(json.dumps({'text_both_displays': True, 'native_copy_button': True, 'images_both_displays': True, 'files_and_folders_both_displays': True, 'private_file_cross_uid_copy': True, 'root_only_file_denied': True, 'primary_selection_ignored': True})) |
| 138 | finally: |
| 139 | bridge.stdin.close() |
| 140 | try: |
| 141 | bridge.wait(timeout=5) |
| 142 | except subprocess.TimeoutExpired: |
| 143 | bridge.terminate() |
| 144 | for process in owners: |
| 145 | process.terminate() |