package guesttools import ( "bytes" "encoding/json" "os" "os/exec" "path/filepath" "reflect" "slices" "strings" "testing" ) func TestGuestAgentTextInjection(t *testing.T) { sh, err := exec.LookPath("sh") if err != nil { t.Skip("POSIX sh is unavailable") } fixture, err := filepath.Abs("testdata/pasteboard.cjs") if err != nil { t.Fatal(err) } agent := string(GuestAgentScript()) script := "set -eu\n" + scriptSection(t, agent, "read_local_clipboard() {", "\nsync_files() {") + scriptSection(t, agent, "inject_text() {", "\ntext_input_loop &") + textInjectionFixture const phrase = "远程输入 📝" original := []map[string]string{ {"public.file-url": "file:///share/first", "public.utf8-plain-text": "first", "public.png": "iVBORw0KGgo=", "public.tiff": "SUkqAA=="}, {"public.file-url": "file:///share/second", "example.custom": "opaque"}, } userCopy := []map[string]string{{"public.utf8-plain-text": phrase}} // Same text, different owner and flavors. for _, scenario := range []string{"files", "failed_ack", "user_copy", "legacy", "deferred_flavor"} { t.Run(scenario, func(t *testing.T) { lockShellFixture(t) dir := t.TempDir() write := func(name string, value []byte) { t.Helper() if err := os.WriteFile(filepath.Join(dir, name), value, 0600); err != nil { t.Fatal(err) } } read := func(name string) []byte { t.Helper() data, err := os.ReadFile(filepath.Join(dir, name)) if err != nil { t.Fatal(err) } return data } items, err := json.Marshal(original) if err != nil { t.Fatal(err) } if scenario == "deferred_flavor" { items = bytes.Replace(items, []byte("{"), []byte(`{"example.deferred":null,`), 1) } write("test-pasteboard.json", []byte(`{"changeCount":17,"items":`+string(items)+"}")) if scenario != "legacy" { write("drop-resolve.js", []byte(guestDropResolveJS)) } if scenario == "user_copy" { next, err := json.Marshal(userCopy) if err != nil { t.Fatal(err) } write("test-user-copy.json", next) } if scenario == "failed_ack" { write("test-fail-ack", nil) } write("body", []byte(phrase)) cmd := exec.Command(sh, "-s", "--", scenario) cmd.Dir = dir cmd.Env = append(os.Environ(), "PASTEBOARD_FIXTURE="+filepath.ToSlash(fixture)) cmd.Stdin = strings.NewReader(script) if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("guest injection: %v\n%s", err, out) } if scenario == "legacy" { return } var ack struct { Path string Args []string Config string Items []map[string]string } if err := json.Unmarshal(read("test-ack.json"), &ack); err != nil { t.Fatal(err) } if ack.Path != "/usr/bin/curl" || !slices.Equal(ack.Args, []string{"-fsS", "-m", "10", "-X", "POST", "-K", "-"}) || !strings.Contains(ack.Config, `url = "http://stub/v1/text-input/ack?id=7"`) || !strings.Contains(ack.Config, `header = "Authorization: Bearer fixture-token"`) { t.Fatalf("unexpected ACK request: %+v", ack) } staged := []map[string]string{{"public.utf8-plain-text": phrase, "org.nspasteboard.TransientType": "", "org.nspasteboard.AutoGeneratedType": ""}} if !reflect.DeepEqual(ack.Items, staged) { t.Fatalf("pasteboard at ACK: %v, want %v", ack.Items, staged) } var after struct { ChangeCount json.Number Items []map[string]string } if err := json.Unmarshal(read("test-pasteboard.json"), &after); err != nil { t.Fatal(err) } want := original if scenario == "user_copy" { want = userCopy } else if !bytes.Equal(read("test-pasteboard-flush"), []byte(after.ChangeCount.String())) { t.Fatal("restored pasteboard was not flushed") } if !reflect.DeepEqual(after.Items, want) { t.Fatalf("restored items: %v, want %v", after.Items, want) } }) } } const textInjectionFixture = ` TMP_DIR=. APP_DIR=. REIMS_HOST_URL=http://stub REIMS_TOKEN=fixture-token INJECT_LOCK=./injecting CLIP_LOCK=./clip.lock cur_pid=$$ scenario=$1 load_conf() { if [ -f ./txt_hdr ]; then exit 0; fi; } osascript() { if [ "$1" = -e ] && [ "$2" = 'clipboard info' ]; then if [ "$scenario" = legacy ]; then echo 'Unicode text'; else echo '«class furl», Unicode text'; fi return fi [ "$1" = -l ] && [ "$2" = JavaScript ] || return 1 if [ "$3" = -e ]; then node -p 'require("./test-pasteboard.json").changeCount'; return; fi if [ "$4" = inject-text ]; then [ -f "$INJECT_LOCK" ] && [ -d "$CLIP_LOCK" ] || return 1; fi shift 2 node "$PASTEBOARD_FIXTURE" "$@" } hash_file() { cat "$1"; } hash_files_file() { cat "$1"; } pbcopy() { echo pbcopy >> legacy-calls; cat > legacy-text; } pbpaste() { echo pbpaste >> legacy-calls; cat legacy-text; } curl() { case " $* " in *'/v1/text-input?wait=25 '*) printf 'X-Input-ID: 7\r\n' > ./txt_hdr; cp body ./txt_body; printf 200 ;; *'/v1/text-input/ack?id=7 '*) [ -d "$CLIP_LOCK" ] && cmp body legacy-text && echo ack >> legacy-calls ;; *' -X POST '*) echo POST >> calls; return 1 ;; *) echo GET >> calls; : > ./clip_hdr; printf 304 ;; esac } printf old > legacy-text (text_input_loop) 2> injection-errors [ ! -e "$INJECT_LOCK" ] [ ! -d "$CLIP_LOCK" ] [ -f "$INJECT_LOCK.completed" ] if [ "$scenario" = failed_ack ]; then grep -q 'Text injection failed' injection-errors else [ ! -s injection-errors ] || { cat injection-errors >&2; exit 1; } fi if [ "$scenario" = legacy ]; then [ "$(cat legacy-text)" = old ] && [ "$(paste -sd , legacy-calls)" = pbpaste,pbcopy,ack,pbpaste,pbcopy ] exit $? fi if [ "$scenario" != user_copy ]; then last_local_hash=$(printf 'file:///share/first\nfile:///share/second') last_server_hash=windows-cut last_server_seq=7 sync_clipboard sync_clipboard [ "$(paste -sd , calls)" = GET,GET ] [ "$last_local_hash" = "$(printf 'file:///share/first\nfile:///share/second')" ] fi [ ! -e legacy-calls ] `