| 1 | |
| 2 | |
| 3 | package vm |
| 4 | |
| 5 | import ( |
| 6 | "bytes" |
| 7 | "context" |
| 8 | "io" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strconv" |
| 12 | "testing" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | |
| 17 | |
| 18 | func TestImageInput(t *testing.T) { |
| 19 | for _, key := range []string{"http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "all_proxy"} { |
| 20 | t.Setenv(key, "") |
| 21 | } |
| 22 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) |
| 23 | defer cancel() |
| 24 | l := newTestLima(t) |
| 25 | state := t.TempDir() |
| 26 | t.Setenv("AGENT_VM_STATE_DIR", state) |
| 27 | if port := os.Getenv("CAGE_TEST_PROXY_PORT"); port != "" { |
| 28 | n, err := strconv.Atoi(port) |
| 29 | if err != nil || n < 1 || n > 65535 { |
| 30 | t.Fatal("invalid CAGE_TEST_PROXY_PORT") |
| 31 | } |
| 32 | if err := os.WriteFile(filepath.Join(state, "network"), []byte("allow 127.0.0.1:"+port+"\n"), 0600); err != nil { |
| 33 | t.Fatal(err) |
| 34 | } |
| 35 | for _, key := range []string{"http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY"} { |
| 36 | t.Setenv(key, "http://127.0.0.1:"+port) |
| 37 | } |
| 38 | } |
| 39 | mounts := []Mount{} |
| 40 | name := "image-input-test" |
| 41 | if err := l.Create(ctx, name, "template:debian-13", Settings{CPUs: 2, MemoryGiB: 2, DiskGiB: 10, Mounts: &mounts, NoContainerd: true}, io.Discard); err != nil { |
| 42 | t.Fatal(err) |
| 43 | } |
| 44 | t.Cleanup(func() { _ = l.Delete(context.Background(), name) }) |
| 45 | var log bytes.Buffer |
| 46 | if err := l.Start(ctx, name, &log); err != nil { |
| 47 | t.Fatalf("start: %v\n%s", err, log.String()) |
| 48 | } |
| 49 | run := func(script string, input []byte) { |
| 50 | t.Helper() |
| 51 | var output bytes.Buffer |
| 52 | code, err := l.Shell(ctx, name, ShellOpts{Workdir: "/tmp", Args: []string{"bash", "-c", script}, Stdin: bytes.NewReader(input), Stdout: &output, Stderr: &output}) |
| 53 | if err != nil || code != 0 { |
| 54 | t.Fatalf("guest: %v / %d\n%s", err, code, output.String()) |
| 55 | } |
| 56 | text := output.String() |
| 57 | if len(text) > 1600 { |
| 58 | text = text[len(text)-1600:] |
| 59 | } |
| 60 | t.Log(text) |
| 61 | } |
| 62 | run("sudo apt-get update -qq && sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libgtk-3-0 xdotool xvfb xauth python3-gi gir1.2-gtk-3.0", nil) |
| 63 | helper, err := os.ReadFile("../cage/image-input.py") |
| 64 | if err != nil { |
| 65 | t.Fatal(err) |
| 66 | } |
| 67 | run("cat > /tmp/cage-image-input.py", helper) |
| 68 | run("xvfb-run -a python3 -", []byte(imageInputAcceptance)) |
| 69 | } |
| 70 | |
| 71 | const imageInputAcceptance = ` |
| 72 | import gi |
| 73 | gi.require_version('Gtk', '3.0') |
| 74 | from gi.repository import Gtk, Gdk, GLib |
| 75 | import hashlib, json, os, pathlib, struct, subprocess, threading, zlib |
| 76 | |
| 77 | def png(seed): |
| 78 | def chunk(kind, data): |
| 79 | return struct.pack('!I',len(data))+kind+data+struct.pack('!I',zlib.crc32(kind+data)) |
| 80 | # Over 3 MB: this must traverse X11's INCR protocol. |
| 81 | raw=b''.join(b'\0'+hashlib.shake_256(bytes([seed,i%256])).digest(1024*3) for i in range(1024)) |
| 82 | return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!2I5B',1024,1024,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(raw))+chunk(b'IEND',b'') |
| 83 | images=[png(1),png(2)] |
| 84 | received=[] |
| 85 | errors=[] |
| 86 | window=Gtk.Window() |
| 87 | window.set_title('Cage image input test') |
| 88 | field=Gtk.TextView() |
| 89 | window.add(field) |
| 90 | def key(_widget,event): |
| 91 | if event.keyval==Gdk.KEY_v and event.state & Gdk.ModifierType.CONTROL_MASK: |
| 92 | def contents(_clipboard,data,_unused): |
| 93 | received.append(bytes(data.get_data() or b'')) |
| 94 | Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD).request_contents(Gdk.Atom.intern('image/png',False),contents,None) |
| 95 | return True |
| 96 | field.connect('key-press-event',key) |
| 97 | window.show_all() |
| 98 | field.grab_focus() |
| 99 | def worker(): |
| 100 | try: |
| 101 | subprocess.run(['xdotool','search','--name','Cage image input test','windowfocus','--sync'],check=True,timeout=3) |
| 102 | for image in images: |
| 103 | result=subprocess.run(['python3','/tmp/cage-image-input.py','paste'],input=image,capture_output=True,timeout=15) |
| 104 | assert result.returncode==0,(result.returncode,result.stderr) |
| 105 | result=subprocess.run(['python3','/tmp/cage-image-input.py','save'],input=images[0],capture_output=True,check=True) |
| 106 | path=pathlib.Path(json.loads(result.stdout)['path']) |
| 107 | assert path.read_bytes()==images[0] |
| 108 | assert path.stat().st_mode & 0o777 == 0o600 |
| 109 | path.unlink() |
| 110 | except BaseException as error: |
| 111 | errors.append(repr(error)) |
| 112 | GLib.timeout_add(1000, Gtk.main_quit) |
| 113 | GLib.timeout_add(300,lambda:(threading.Thread(target=worker).start(),False)[1]) |
| 114 | GLib.timeout_add(35000,Gtk.main_quit) |
| 115 | Gtk.main() |
| 116 | assert not errors,errors |
| 117 | assert received==images,[len(item) for item in received] |
| 118 | print('PASS: two real X11 image pastes, >3 MB PNG integrity, private saved attachment') |
| 119 | ` |