Files
Reims-Go/internal/guesttools/drop_test.go
T
ShroapandShroap 7f4cbbe911 feat(guesttools): support Windows-to-macOS window drag-and-drop (zero-copy WebDAV + stealth paste) (#82)
* fix(installer): use 8 KiB HFS+ catalog B-tree nodes for REIMSTOOLS image

* feat(guesttools): support Windows-to-macOS window drag-and-drop (Agent v13)

---------

Co-authored-by: Shroap <184123002+YinLiaoCo@users.noreply.github.com>
2026-12-02 21:35:59 +08:00

256 lines
9.5 KiB
Go

package guesttools
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
)
func TestHostDropEndpoint(t *testing.T) {
s := NewServer(nil)
port, err := s.Start(-1)
if err != nil {
t.Fatal(err)
}
defer s.Close(context.Background())
cfg := VMConfig{VMName: "mac", Token: strings.Repeat("g", 64)}
s.RegisterVM(cfg)
host := s.HostDropToken(cfg.DriverID, cfg.VMName)
if len(host) != 64 || host == cfg.Token {
t.Fatal("invalid host-only credential")
}
request := func(method, path, token, body string, status int) *http.Response {
t.Helper()
req, err := http.NewRequest(method, fmt.Sprintf("http://127.0.0.1:%d%s", port, path), strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { resp.Body.Close() })
if resp.StatusCode != status {
t.Fatalf("%s %s: got %d, want %d", method, path, resp.StatusCode, status)
}
return resp
}
const path = "/v1/host-drop"
const valid = `{"display_index":2,"norm_x":-1,"norm_y":2,"in_image":true,"paths":["demo"]}`
request("POST", path, "", valid, 401)
request("POST", path, cfg.Token, valid, 401)
request("GET", "/v1/config", host, "", 401)
request("GET", "/v1/files", host, "", 401)
request("GET", path, host, "", 405)
for _, invalid := range []string{"{", `{"paths":[]}`, `{"paths":["a"],"display_index":-1}`,
`{"paths":["a"],"norm_x":NaN}`, `{"paths":["a"],"extra":0}`, valid + "{}",
`{"paths":[` + strings.Repeat(`"a",`, MaxHostDropPaths) + `"a"]}`} {
request("POST", path, host, invalid, 400)
}
request("POST", path, host, strings.Repeat(" ", MaxHostDropBodyBytes+1), 413)
request("POST", path, host, valid, 503)
want := HostDropResult{DropID: "id", Mode: "l1_share", Delivered: []string{"demo"}}
s.SetHostDropHandler(func(key, name string, req HostDropRequest) (HostDropResult, error) {
if key != vmRegistryKey(cfg.DriverID, cfg.VMName) || name != cfg.VMName ||
req.NormX != 0 || req.NormY != 1 || req.DisplayIndex != 2 || !req.InImage || !reflect.DeepEqual(req.Paths, []string{"demo"}) {
t.Error("unexpected drop callback arguments")
}
return want, nil
})
resp := request("POST", path, host, valid, 200)
var result HostDropResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil || !reflect.DeepEqual(result, want) {
t.Fatalf("result = %+v, err = %v", result, err)
}
s.SetHostDropHandler(func(_, _ string, req HostDropRequest) (HostDropResult, error) {
if req.Text != "你好" || len(req.Paths) != 0 {
t.Errorf("unexpected text drop %+v", req)
}
return want, nil
})
request("POST", path, host, `{"text":"你好"}`, 200)
request("POST", path, host, `{"paths":["demo"],"text":"你好"}`, 400)
if s.IsConnected(cfg.VMName, time.Minute) {
t.Fatal("host drop marked the guest connected")
}
key := vmRegistryKey(cfg.DriverID, cfg.VMName)
file := filepath.Join(t.TempDir(), "demo")
if err := os.WriteFile(file, []byte("before"), 0600); err != nil {
t.Fatal(err)
}
if !s.RegisterDropShare(key, "one", []DropShareEntry{{Name: "demo", HostPath: file}}) {
t.Fatal("register failed")
}
if err := os.WriteFile(file, []byte("after"), 0600); err != nil {
t.Fatal(err)
}
other := VMConfig{VMName: "other", Token: "other-token"}
s.RegisterVM(other)
const dav = "/dav-drop/mac/one/demo"
const direct = "/v1/drop-file?drop_id=one&path=demo"
request("GET", dav, other.Token, "", 403)
request("GET", direct, other.Token, "", 404)
for _, url := range []string{dav, direct} {
request("GET", url, host, "", 401)
request("HEAD", url, cfg.Token, "", 200)
resp := request("GET", url, cfg.Token, "", 200)
if b, err := io.ReadAll(resp.Body); err != nil || string(b) != "after" {
t.Fatalf("%s returned %q, err %v", url, b, err)
}
}
request("PUT", direct, cfg.Token, "", 405)
req := httptest.NewRequest("PUT", dav, nil)
req.SetBasicAuth("guest", cfg.Token)
w := httptest.NewRecorder()
s.handleDropWebDAV(w, req)
if w.Code != 403 && w.Code != 405 {
t.Fatalf("DAV PUT returned %d", w.Code)
}
s.RevokeDropShare(key, "one")
request("GET", direct, cfg.Token, "", 404)
}
func TestDropEventsQueueAndAck(t *testing.T) {
s := NewServer(nil)
cfg := VMConfig{VMName: "mac", Token: "guest"}
s.RegisterVM(cfg)
key := vmRegistryKey(cfg.DriverID, cfg.VMName)
host := s.HostDropToken(cfg.DriverID, cfg.VMName)
const path = "/v1/drop-events"
call := func(method, url, token, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, url, strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
w := httptest.NewRecorder()
switch req.URL.Path {
case path:
s.handleDropEvents(w, req)
case path + "/paste":
s.handleDropEventsPaste(w, req)
case path + "/ack":
s.handleDropEventsAck(w, req)
}
return w
}
check := func(w *httptest.ResponseRecorder, status int) {
t.Helper()
if w.Code != status {
t.Fatalf("got %d (%s), want %d", w.Code, w.Body.String(), status)
}
}
check(call("GET", path, host, ""), 401)
check(call("POST", path+"/ack", host, ""), 401)
check(call("POST", path, cfg.Token, ""), 405)
check(call("GET", path+"/ack", cfg.Token, ""), 405)
if s.HasDropEventListener(key) {
t.Fatal("unexpected listener before first poll")
}
done := make(chan *httptest.ResponseRecorder, 1)
go func() { done <- call("GET", path+"?wait=3", cfg.Token, "") }()
deadline := time.Now().Add(2 * time.Second)
for !s.HasDropEventListener(key) {
if time.Now().After(deadline) {
t.Fatal("poll did not start")
}
time.Sleep(time.Millisecond)
}
ev := DropEvent{DropID: "one", DisplayIndex: 2, NormX: .2, NormY: .7, InImage: true, Items: []string{"demo"}}
if !s.EnqueueDropEvent(key, ev) {
t.Fatal("enqueue failed")
}
w := <-done
check(w, 200)
var got DropEvent
ev.Kind = "files"
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || !reflect.DeepEqual(got, ev) {
t.Fatalf("event %+v, error %v", got, err)
}
const paste = `{"drop_id":"one","activate_click":true}`
check(call("POST", path+"/paste", host, paste), 401)
check(call("POST", path+"/paste", "invalid", paste), 401)
check(call("POST", path+"/paste", cfg.Token, `{"drop_id":"missing"}`), 404)
check(call("POST", path+"/paste", cfg.Token, paste), 503)
s.dropPasteSettle = 5 * time.Millisecond
calls := 0
wantKey := "meta_l"
var wantFocusWait time.Duration
s.SetDropPasteHandler(func(_ context.Context, k, n, id string, display int, x, y float64, activateClick bool, commandKey string, focusWait time.Duration) error {
calls++
if k != key || n != cfg.VMName || id != ev.DropID || display != ev.DisplayIndex || x != ev.NormX || y != ev.NormY || !activateClick || commandKey != wantKey || focusWait != wantFocusWait {
t.Error("unexpected paste arguments")
}
return nil
})
start := time.Now()
check(call("POST", path+"/paste", cfg.Token, paste), 200)
if calls != 1 || time.Since(start) < s.dropPasteSettle {
t.Fatal("paste handshake returned before completion")
}
wantKey = "alt"
wantFocusWait = 220 * time.Millisecond
check(call("POST", path+"/paste", cfg.Token, `{"drop_id":"one","activate_click":true,"command_key":"alt","focus_wait_ms":220}`), 200)
check(call("POST", path+"/paste", cfg.Token, `{"drop_id":"one","command_key":"ret"}`), 400)
check(call("POST", path+"/paste", cfg.Token, `{"drop_id":"one","focus_wait_ms":-1}`), 400)
check(call("POST", path+"/paste", cfg.Token, `{"drop_id":"one","focus_wait_ms":501}`), 400)
if calls != 2 {
t.Fatalf("got %d paste calls, want 2", calls)
}
const valid = `{"drop_id":"one","status":"placed","target_kind":"desktop"}`
count := 0
s.SetDropAckHandler(func(k, n string, ack DropEventAck) {
count++
if k != key || n != cfg.VMName || ack.DropID != ev.DropID {
t.Errorf("unexpected callback %s %s %+v", k, n, ack)
}
})
for _, body := range []string{"{", "{}", valid + "{}", strings.Replace(valid, "placed", "other", 1),
strings.Replace(valid, "desktop", "other", 1), strings.Replace(valid, "{", `{"extra":0,`, 1)} {
check(call("POST", path+"/ack", cfg.Token, body), 400)
}
check(call("POST", path+"/ack", cfg.Token, strings.Repeat(" ", MaxDropAckBodyBytes+1)), 413)
for i := 0; i < 2; i++ {
check(call("POST", path+"/ack", cfg.Token, valid), 200)
}
check(call("POST", path+"/paste", cfg.Token, paste), 404)
ev.CreatedAt = time.Now().Add(-2 * DropEventTTL)
s.EnqueueDropEvent(key, ev)
check(call("GET", path+"?wait=0", cfg.Token, ""), 204)
ev.CreatedAt = time.Time{}
s.EnqueueDropEvent(key, ev)
check(call("GET", path+"?wait=0", cfg.Token, ""), 200)
s.mu.Lock()
s.vms[key].dropActive[ev.DropID].CreatedAt = time.Now().Add(-2 * DropEventTTL)
s.mu.Unlock()
check(call("POST", path+"/ack", cfg.Token, valid), 200)
if count != 1 || !s.HasDropEventListener(key) {
t.Fatalf("callbacks %d, recent listener %v", count, s.HasDropEventListener(key))
}
for _, pair := range [][2]string{{"pasted", "window"}, {"placed", "photos"}, {"cancelled", "cancelled"}} {
ev := DropEvent{DropID: "one", Kind: "text", Text: "hello", WebDAVDrop: true}
if !s.EnqueueDropEvent(key, ev) {
t.Fatal("text enqueue failed")
}
w := call("GET", path+"?wait=0", cfg.Token, "")
check(w, 200)
var got DropEvent
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || !reflect.DeepEqual(got, ev) {
t.Fatalf("text event %+v, err %v", got, err)
}
body := fmt.Sprintf(`{"drop_id":"one","status":%q,"target_kind":%q}`, pair[0], pair[1])
check(call("POST", path+"/ack", cfg.Token, body), 200)
}
if count != 4 {
t.Fatalf("got %d ack callbacks", count)
}
}