跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

shared-clipboard-guest-smoke.py

145 行 · 7.2 KB历史下载
1"""Isolated real-X11 clipboard check; never connects to the user's VM.
2
3Run with CAGE_CLIPBOARD_QA_SSH_CONFIG and CAGE_CLIPBOARD_QA_SSH_TARGET.
4The supplied guest must have disposable :77 and :78 displays and the helper.
5"""
6import base64
7import json
8import os
9from pathlib import Path
10import queue
11import subprocess
12import threading
13import time
14
15ssh = ['ssh', '-F', os.environ['CAGE_CLIPBOARD_QA_SSH_CONFIG'], os.environ['CAGE_CLIPBOARD_QA_SSH_TARGET']]
16directory = '/tmp/cage-clipboard-ui-qa'
17helper = directory + '/shared-clipboard.py'
18bridge = subprocess.Popen(ssh + ['sudo python3 ' + helper], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
19events = queue.Queue()
20threading.Thread(target=lambda: [events.put(json.loads(line)) for line in bridge.stdout], daemon=True).start()
21owners = []
22
23
24def 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
28def 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
44def 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
50imports = '''import gi, base64, json, ctypes as C
51gi.require_version('Gtk', '3.0')
52from gi.repository import Gtk, Gdk, GdkPixbuf, GLib
53Gtk.init([])
54clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
55'''
56
57
58def 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
68try:
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 # A real GTK button writes the system clipboard only after an X11 click.
76 owner("""window = Gtk.Window()
77window.set_default_size(240,100)
78window.move(40,40)
79button = Gtk.Button(label='Copy message')
80button.connect('clicked', lambda _button: clipboard.set_text('guest 消息🙂\\nexact text', -1))
81window.add(button)
82window.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 = """
106gtk = C.CDLL('libgtk-3.so.0'); gdk = C.CDLL('libgdk-3.so.0')
107gdk.gdk_atom_intern_static_string.restype=C.c_void_p
108gdk.gdk_atom_intern_static_string.argtypes=[C.c_char_p]
109class Target(C.Structure):
110 _fields_=[('target',C.c_char_p),('flags',C.c_uint),('info',C.c_uint)]
111Provide=C.CFUNCTYPE(None,C.c_void_p,C.c_void_p,C.c_uint,C.c_void_p)
112Clear=C.CFUNCTYPE(None,C.c_void_p,C.c_void_p)
113gtk.gtk_selection_data_set.argtypes=[C.c_void_p,C.c_void_p,C.c_int,C.c_void_p,C.c_int]
114gtk.gtk_clipboard_set_with_data.argtypes=[C.c_void_p,C.POINTER(Target),C.c_uint,Provide,Clear,C.c_void_p]
115encoded=(uri+'\\r\\n').encode(); buffer=C.create_string_buffer(encoded)
116@Provide
117def 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
120def clear(_clipboard,_data): pass
121targets=(Target*1)(Target(b'text/uri-list',0,0))
122assert 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 # Ordinary drag-selection PRIMARY changes must not replace the clipboard.
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}))
138finally:
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()