Files
Reims-Go/internal/guesttools/clipboard_test.go
T

633 lines
24 KiB
Go

package guesttools
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"image/color"
"image/png"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
)
func TestTrimPNG(t *testing.T) {
valid := makeSamplePNG(t, 1, 2, 3)
badLength := bytes.Clone(valid)
binary.BigEndian.PutUint32(badLength[8:12], 0xffffffff)
for _, tc := range []struct {
name string
raw []byte
ok bool
}{
{"PNG", valid, true},
{"padding", append(bytes.Clone(valid), make([]byte, 16)...), true},
{"truncated", valid[:len(valid)-1], false},
{"missing IEND", valid[:len(valid)-12], false},
{"illegal chunk length", badLength, false},
{"non-PNG", []byte("not an image"), false},
} {
t.Run(tc.name, func(t *testing.T) {
got, ok := TrimPNG(tc.raw)
if ok != tc.ok || (ok && !bytes.Equal(got, valid)) || (!ok && got != nil) {
t.Fatalf("TrimPNG returned %d bytes, ok=%t", len(got), ok)
}
})
}
}
func TestDecodeDIBFormats(t *testing.T) {
le := binary.LittleEndian
for _, tc := range []struct {
name string
header int
depth uint16
masks []uint32
palette []byte
topDown bool
pixels []byte
want []color.NRGBA
}{
{"24-bit RGB bottom-up", 40, 24, nil, nil, false,
[]byte{0, 0, 255, 0, 0, 255, 0, 0},
[]color.NRGBA{{G: 255, A: 255}, {R: 255, A: 255}}},
{"32-bit RGB zero alpha and optional palette", 40, 32, nil, []byte{4, 9, 14, 0}, false,
[]byte{100, 20, 30, 0}, []color.NRGBA{{R: 30, G: 20, B: 100, A: 255}}},
{"32-bit RGB with alpha", 40, 32, nil, nil, false,
[]byte{100, 20, 30, 70}, []color.NRGBA{{R: 30, G: 20, B: 100, A: 70}}},
{"swapped red and blue with external masks", 40, 32, []uint32{0xff, 0xff00, 0xff0000}, nil, false,
[]byte{34, 56, 78, 12}, []color.NRGBA{{R: 34, G: 56, B: 78, A: 255}}},
{"V4 explicit zero alpha", 108, 32, []uint32{0xff, 0xff00, 0xff0000, 0xff000000}, nil, false,
[]byte{34, 56, 78, 0}, []color.NRGBA{{R: 34, G: 56, B: 78}}},
{"V5 explicit zero alpha", 124, 32, []uint32{0xff0000, 0xff00, 0xff, 0xff000000}, nil, false,
[]byte{34, 56, 78, 0}, []color.NRGBA{{R: 78, G: 56, B: 34}}},
{"16-bit RGB565 top-down", 40, 16, []uint32{0xf800, 0x07e0, 0x1f}, nil, true,
[]byte{0x00, 0xfc, 0, 0, 0x1f, 0, 0, 0},
[]color.NRGBA{{R: 255, G: 130, A: 255}, {B: 255, A: 255}}},
} {
t.Run(tc.name, func(t *testing.T) {
header := make([]byte, tc.header)
height := int32(len(tc.want))
if tc.topDown {
height = -height
}
le.PutUint32(header, uint32(tc.header))
le.PutUint32(header[4:], 1)
le.PutUint32(header[8:], uint32(height))
le.PutUint16(header[12:], 1)
le.PutUint16(header[14:], tc.depth)
le.PutUint32(header[32:], uint32(len(tc.palette)/4))
if len(tc.masks) > 0 {
le.PutUint32(header[16:], 3)
if tc.header == 40 {
header = append(header, make([]byte, len(tc.masks)*4)...)
}
for i, mask := range tc.masks {
le.PutUint32(header[40+4*i:], mask)
}
}
data, err := DecodeDIBToPNG(append(append(header, tc.palette...), tc.pixels...))
if err != nil {
t.Fatal(err)
}
img, err := png.Decode(bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
for y, want := range tc.want {
if got := color.NRGBAModel.Convert(img.At(0, y)); got != want {
t.Errorf("pixel y=%d: got %+v, want %+v", y, got, want)
}
}
})
}
}
func clipboardRequest(t *testing.T, srv *Server, method, query, contentType, baseSeq string, body []byte) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, "/v1/clipboard"+query, bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer clipboard-test-token")
req.Header.Set("Content-Type", contentType)
req.Header.Set("X-Clip-Base-Seq", baseSeq)
resp := httptest.NewRecorder()
srv.handleClipboard(resp, req)
return resp
}
func newClipboardTestServer(clip Clipboard) *Server {
srv := NewServer(clip)
srv.RegisterVM(VMConfig{VMName: "clipboard-test", Token: "clipboard-test-token"})
return srv
}
func TestClipboardGETSequenceWithUnchangedHash(t *testing.T) {
clip := &memClipboard{kind: ClipText, data: []byte("same text"), seq: 7}
srv := newClipboardTestServer(clip)
initial := clipboardRequest(t, srv, http.MethodGet, "", "", "", nil)
hash := initial.Header().Get("X-Clip-Hash")
if initial.Code != http.StatusOK || hash == "" || initial.Header().Get("X-Clip-Seq") != "7" {
t.Fatalf("initial GET: %d %v", initial.Code, initial.Header())
}
if err := clip.WriteText("same text"); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name, query, body string
status int
}{
{"new sequence", "&since_seq=7&wait=2", "same text", http.StatusOK},
{"same sequence", "&since_seq=8", "", http.StatusNotModified},
{"legacy guest", "", "", http.StatusNotModified},
{"invalid sequence", "&since_seq=invalid", "", http.StatusNotModified},
{"out of range sequence", "&since_seq=4294967296", "", http.StatusNotModified},
} {
t.Run(tc.name, func(t *testing.T) {
got := clipboardRequest(t, srv, http.MethodGet, "?since="+hash+tc.query, "", "", nil)
if got.Code != tc.status || got.Body.String() != tc.body || got.Header().Get("X-Clip-Seq") != "8" ||
got.Header().Get("X-Clip-Hash") != hash || got.Header().Get("X-Clip-Kind") != string(ClipText) {
t.Fatalf("GET: %d %v %q, want status %d and body %q", got.Code, got.Header(), got.Body, tc.status, tc.body)
}
})
}
}
func TestClipboardPOSTNormalizesPNG(t *testing.T) {
clip := &memClipboard{}
srv := newClipboardTestServer(clip)
pixels := makeSamplePNG(t, 1, 2, 3)
padded := append(bytes.Clone(pixels), 0, 0, 0)
post := clipboardRequest(t, srv, http.MethodPost, "", "image/png", "", padded)
hash, seq := post.Header().Get("X-Clip-Hash"), post.Header().Get("X-Clip-Seq")
if post.Code != http.StatusOK || hash != payloadHash(ClipPayload{Kind: ClipPNG, Data: pixels}) || seq == "" {
t.Fatalf("padded PNG POST: %d %v", post.Code, post.Header())
}
got, err := clip.Read()
if err != nil || got.Kind != ClipPNG || !bytes.Equal(got.Data, pixels) {
t.Fatalf("stored PNG: kind %q, %d bytes, error %v", got.Kind, len(got.Data), err)
}
get := clipboardRequest(t, srv, http.MethodGet, "?accept=image&since="+hash+"&since_seq="+seq, "", "", nil)
if get.Code != http.StatusNotModified || get.Body.Len() != 0 {
t.Fatalf("GET after padded PNG POST: %d, %d body bytes", get.Code, get.Body.Len())
}
repeated := clipboardRequest(t, srv, http.MethodPost, "", "image/png", "", padded)
if repeated.Code != http.StatusOK || repeated.Header().Get("X-Clip-Seq") != seq {
t.Fatalf("repeated padded PNG POST: %d %v", repeated.Code, repeated.Header())
}
invalid := clipboardRequest(t, srv, http.MethodPost, "", "image/png", "", pixels[:len(pixels)-1])
if invalid.Code != http.StatusBadRequest {
t.Fatalf("truncated PNG POST: %d, want %d", invalid.Code, http.StatusBadRequest)
}
}
func TestClipboardPOSTSequenceConflict(t *testing.T) {
oldPNG := makeSamplePNG(t, 255, 0, 0)
newPNG := makeSamplePNG(t, 0, 255, 0)
clip := &memClipboard{kind: ClipPNG, data: oldPNG, seq: 7}
srv := newClipboardTestServer(clip)
get := clipboardRequest(t, srv, http.MethodGet, "?accept=image", "", "", nil)
if get.Code != http.StatusOK || get.Header().Get("X-Clip-Seq") != "7" {
t.Fatalf("initial GET: %d %v", get.Code, get.Header())
}
if err := clip.WritePNG(newPNG); err != nil {
t.Fatal(err)
}
stale := clipboardRequest(t, srv, http.MethodPost, "", "image/png", "7", oldPNG)
if stale.Code != http.StatusConflict || stale.Header().Get("X-Clip-Seq") != "8" {
t.Fatalf("stale POST: %d %v", stale.Code, stale.Header())
}
got, _ := clip.Read()
if got.Kind != ClipPNG || !bytes.Equal(got.Data, newPNG) {
t.Fatal("stale POST changed the new host image")
}
for _, tc := range []struct{ base, seq string }{{"8", "9"}, {"", "10"}} {
post := clipboardRequest(t, srv, http.MethodPost, "", "text/plain", tc.base, []byte(tc.seq))
if post.Code != http.StatusOK || post.Header().Get("X-Clip-Seq") != tc.seq {
t.Fatalf("POST with base %q: %d %v", tc.base, post.Code, post.Header())
}
poll := clipboardRequest(t, srv, http.MethodGet, "?since="+post.Header().Get("X-Clip-Hash"), "", "", nil)
if poll.Code != http.StatusNotModified || poll.Header().Get("X-Clip-Seq") != tc.seq {
t.Fatalf("unchanged GET: %d %v", poll.Code, poll.Header())
}
}
}
func TestClipboardGuestToHostIgnoresStaleBase(t *testing.T) {
for _, name := range []string{"after switching from bidirectional", "guest to host from startup"} {
t.Run(name, func(t *testing.T) {
clip := &memClipboard{kind: ClipText, data: []byte("initial host"), seq: 7}
srv := newClipboardTestServer(clip)
policy := DefaultClipboardPolicy()
policy.Direction = ClipboardGuestToHost
if name == "guest to host from startup" {
srv.SetGlobalClipboardPolicy(policy)
}
initial := clipboardRequest(t, srv, http.MethodGet, "", "", "", nil)
wantBase := "7"
if name == "guest to host from startup" {
if initial.Code != http.StatusNoContent {
t.Fatalf("initial GET: %d", initial.Code)
}
initial = clipboardRequest(t, srv, http.MethodPost, "", "text/plain", "", []byte("first guest"))
wantBase = "8"
} else {
srv.SetGlobalClipboardPolicy(policy)
}
base := initial.Header().Get("X-Clip-Seq")
if initial.Code != http.StatusOK || base != wantBase {
t.Fatalf("initial sync: %d %v", initial.Code, initial.Header())
}
if err := clip.WriteText("new host"); err != nil {
t.Fatal(err)
}
post := clipboardRequest(t, srv, http.MethodPost, "", "text/plain", base, []byte("new guest"))
if post.Code != http.StatusOK || post.Header().Get("X-Clip-Seq") != strconv.FormatUint(uint64(clip.SequenceNumber()), 10) {
t.Fatalf("POST after host copied: %d %v", post.Code, post.Header())
}
if got, _ := clip.ReadText(); got != "new guest" {
t.Fatalf("host clipboard: %q", got)
}
})
}
}
type clipboardReadFailure struct {
*memClipboard
writeBase *uint32
writeErr error
}
func (c *clipboardReadFailure) readClipboard(bool, bool) (ClipPayload, uint32, error) {
return ClipPayload{}, 0, errors.New("OpenClipboard failed")
}
func (c *clipboardReadFailure) writeClipboard(payload ClipPayload, baseSeq *uint32) (uint32, error) {
c.writeBase = baseSeq
if c.writeErr != nil {
return c.SequenceNumber(), c.writeErr
}
err := c.WriteText(string(payload.Data))
return c.SequenceNumber(), err
}
func TestClipboardPOSTUsesAtomicWriteAfterReadFailure(t *testing.T) {
for _, tc := range []struct {
name string
writeErr error
wantStatus int
wantSeq string
wantErrors uint64
}{
{"write succeeds", nil, http.StatusOK, "8", 0},
{"write also fails", errors.New("OpenClipboard failed on write"), http.StatusInternalServerError, "", 1},
{"wrapped conflict", errors.Join(errClipboardConflict, errors.New("CloseClipboard failed")), http.StatusConflict, "7", 0},
} {
t.Run(tc.name, func(t *testing.T) {
clip := &clipboardReadFailure{memClipboard: &memClipboard{seq: 7}, writeErr: tc.writeErr}
srv := newClipboardTestServer(clip)
post := clipboardRequest(t, srv, http.MethodPost, "", "text/plain", "7", []byte("guest"))
if post.Code != tc.wantStatus || post.Header().Get("X-Clip-Seq") != tc.wantSeq {
t.Fatalf("POST: got %d %v %q, want status %d and seq %q", post.Code, post.Header(), post.Body, tc.wantStatus, tc.wantSeq)
}
if clip.writeBase == nil || *clip.writeBase != 7 {
t.Fatalf("atomic write did not receive base 7")
}
if got := srv.ClipboardDiagnostics().ErrorCount; got != tc.wantErrors {
t.Fatalf("clipboard errors: got %d, want %d", got, tc.wantErrors)
}
})
}
}
type clipboardReadHook struct {
*memClipboard
once sync.Once
afterRead func()
}
func (c *clipboardReadHook) Read() (ClipPayload, error) {
payload, err := c.memClipboard.Read()
c.once.Do(c.afterRead)
return payload, err
}
func TestClipboardGETDoesNotLoseWakeup(t *testing.T) {
clip := &clipboardReadHook{memClipboard: &memClipboard{kind: ClipText, data: []byte("old"), seq: 1}}
srv := newClipboardTestServer(clip)
clip.afterRead = func() {
_ = clip.WriteText("new")
srv.NotifyClipboardChanged()
}
start := time.Now()
resp := clipboardRequest(t, srv, http.MethodGet, "?wait=5&since="+textHash("old"), "", "", nil)
if resp.Code != http.StatusOK || resp.Body.String() != "new" || resp.Header().Get("X-Clip-Seq") != "2" {
t.Fatalf("GET got %d %v %q", resp.Code, resp.Header(), resp.Body)
}
if elapsed := time.Since(start); elapsed >= 4*time.Second {
t.Fatalf("GET returned only after waiting %s", elapsed)
}
}
func TestClipboardGETRechecksPolicyAfterWake(t *testing.T) {
png := makeSamplePNG(t, 1, 2, 3)
payload := ClipPayload{Kind: ClipPNG, Data: png}
clip := &clipboardReadHook{memClipboard: &memClipboard{kind: payload.Kind, data: payload.Data}}
srv := newClipboardTestServer(clip)
clip.afterRead = func() {
policy := DefaultClipboardPolicy()
policy.Direction = ClipboardGuestToHost
srv.SetGlobalClipboardPolicy(policy)
_ = clip.WritePNG(makeSamplePNG(t, 4, 5, 6))
}
resp := clipboardRequest(t, srv, http.MethodGet, "?accept=image&wait=1&since="+payloadHash(payload), "", "", nil)
if resp.Code != http.StatusNoContent {
t.Fatalf("GET after switching direction: %d, body %q", resp.Code, resp.Body)
}
}
func TestClipboardGETSkipsUnavailablePayloads(t *testing.T) {
png := makeSamplePNG(t, 1, 2, 3)
for i, tc := range []struct {
name string
kind ClipKind
query string
syncImages bool
maxBytes int
}{
{"too large", ClipPNG, "?accept=image", true, len(png) - 1},
{"images disabled", ClipPNG, "?accept=image", false, len(png)},
{"legacy text request", ClipPNG, "", true, len(png)},
{"unsupported", ClipEmpty, "?accept=image", true, len(png)},
} {
t.Run(tc.name, func(t *testing.T) {
clip := &memClipboard{kind: tc.kind, seq: uint32(i)}
if tc.kind == ClipPNG {
clip.data = png
}
srv := newClipboardTestServer(clip)
policy := DefaultClipboardPolicy()
policy.SyncImages = tc.syncImages
policy.MaxImageBytes = tc.maxBytes
srv.SetGlobalClipboardPolicy(policy)
resp := clipboardRequest(t, srv, http.MethodGet, tc.query, "", "", nil)
if resp.Code != http.StatusNotModified || resp.Body.Len() != 0 || resp.Header().Get("X-Clip-Seq") != strconv.Itoa(i) {
t.Fatalf("skipped GET: %d %v, %d bytes", resp.Code, resp.Header(), resp.Body.Len())
}
_ = clip.WriteText("next item")
resp = clipboardRequest(t, srv, http.MethodGet, tc.query, "", "", nil)
if resp.Code != http.StatusOK || resp.Body.String() != "next item" {
t.Fatalf("subsequent GET: %d %q", resp.Code, resp.Body)
}
})
}
}
func TestClipboardPOSTTextLimitAndEmptyOverwrite(t *testing.T) {
png := makeSamplePNG(t, 1, 2, 3)
clip := &memClipboard{kind: ClipPNG, data: png}
srv := newClipboardTestServer(clip)
policy := DefaultClipboardPolicy()
policy.MaxImageBytes = 16
srv.SetGlobalClipboardPolicy(policy)
img := clipboardRequest(t, srv, http.MethodPost, "", "image/png", "", png)
if img.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("oversized PNG POST: got %d", img.Code)
}
for _, value := range []string{"", strings.Repeat("文本", 100)} {
resp := clipboardRequest(t, srv, http.MethodPost, "", "text/plain", "", []byte(value))
got, _ := clip.Read()
if resp.Code != http.StatusOK || got.Kind != ClipText || string(got.Data) != value {
t.Fatalf("text POST (%d bytes): got status %d and payload %+v", len(value), resp.Code, got)
}
}
}
func TestClipboardGETFilesZeroCopyWebDAV(t *testing.T) {
first := filepath.Join(t.TempDir(), "a.txt")
second := filepath.Join(t.TempDir(), "a.txt")
folder := filepath.Join(t.TempDir(), "MyFolder")
if err := os.Mkdir(folder, 0o700); err != nil {
t.Fatal(err)
}
for path, contents := range map[string]string{
first: "first", second: "second", filepath.Join(folder, "sub.txt"): "nested",
} {
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
t.Fatal(err)
}
}
paths := []string{first, second, folder, `\\server\share\x.txt`}
link := filepath.Join(t.TempDir(), "link.txt")
if err := os.Symlink(first, link); err == nil {
paths = append(paths, link)
}
clip := &memClipboard{}
clip.WriteFiles(paths)
srv := NewServer(clip)
shared := t.TempDir()
srv.RegisterVM(VMConfig{VMName: "mac", Token: "guest", SharedDir: shared})
get := func(path string, handler http.HandlerFunc) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.SetBasicAuth("mac", "guest")
resp := httptest.NewRecorder()
handler(resp, req)
return resp
}
checkPing := func(want bool) {
t.Helper()
resp := get("/v1/ping", srv.handlePing)
var ping struct {
Capabilities []string `json:"capabilities"`
}
if err := json.Unmarshal(resp.Body.Bytes(), &ping); err != nil {
t.Fatal(err)
}
if resp.Code != http.StatusOK || slices.Contains(ping.Capabilities, "clipboard-files") != want {
t.Fatalf("ping status %d, capabilities %v, want clipboard-files=%t", resp.Code, ping.Capabilities, want)
}
}
policy := DefaultClipboardPolicy()
policy.Enabled = true
srv.SetGlobalClipboardPolicy(policy)
checkPing(true)
resp := get("/v1/clipboard?accept=image", srv.handleClipboard)
if resp.Code != http.StatusNotModified || resp.Body.Len() != 0 || resp.Header().Get("X-Clip-Kind") == "files" {
t.Fatalf("legacy GET: %d %v %q", resp.Code, resp.Header(), resp.Body.String())
}
const endpoint = "/v1/clipboard?accept=image,files"
resp = get(endpoint, srv.handleClipboard)
if resp.Code != http.StatusOK || resp.Header().Get("X-Clip-Kind") != "files" || resp.Header().Get("Content-Type") != "application/json" {
t.Fatalf("files GET: %d %v", resp.Code, resp.Header())
}
var manifest struct {
DropID string `json:"drop_id"`
Items []string `json:"items"`
}
if err := json.Unmarshal(resp.Body.Bytes(), &manifest); err != nil {
t.Fatal(err)
}
hash := resp.Header().Get("X-Clip-Hash")
if len(hash) != 64 || manifest.DropID != "clip-"+hash[:16] || !slices.Equal(manifest.Items, []string{"a.txt", "a (1).txt", "MyFolder"}) {
t.Fatalf("unexpected hash %q or manifest %+v", hash, manifest)
}
for item, want := range map[string]string{"a.txt": "first", "a (1).txt": "second", "MyFolder/sub.txt": "nested"} {
path := url.URL{Path: "/dav-drop/mac/" + manifest.DropID + "/" + item}
resp := get(path.EscapedPath(), srv.handleDropWebDAV)
if resp.Code != http.StatusOK || resp.Body.String() != want {
t.Fatalf("GET %s: %d %q, want %q", item, resp.Code, resp.Body.String(), want)
}
}
if files, err := os.ReadDir(shared); err != nil || len(files) != 0 {
t.Fatalf("SharedDir contains %v, err=%v", files, err)
}
vm := srv.vms[vmRegistryKey("", "mac")]
before := vm.dropShares.modTime
resp = get(endpoint+"&since="+hash, srv.handleClipboard)
if resp.Code != http.StatusNotModified || resp.Body.Len() != 0 || resp.Header().Get("X-Clip-Hash") != hash ||
resp.Header().Get("X-Clip-Kind") != "files" || !vm.dropShares.modTime.Equal(before) {
t.Fatalf("conditional GET: %d %v, modTime %v (was %v)", resp.Code, resp.Header(), vm.dropShares.modTime, before)
}
policy.Direction = ClipboardGuestToHost
srv.SetGlobalClipboardPolicy(policy)
checkPing(false)
if resp := get(endpoint, srv.handleClipboard); resp.Code != http.StatusNoContent || resp.Body.Len() != 0 {
t.Fatalf("guest-to-host GET: %d %q", resp.Code, resp.Body.String())
}
}
func TestClipboardFileCopyEventIdentity(t *testing.T) {
file := filepath.Join(t.TempDir(), "a.txt")
writeFile := func(contents string) {
t.Helper()
if err := os.WriteFile(file, []byte(contents), 0600); err != nil {
t.Fatal(err)
}
}
writeFile("original")
clip := &memClipboard{seq: 9}
srv := newClipboardTestServer(clip)
store := srv.vms[vmRegistryKey("", "clipboard-test")].dropShares
poll := func(since string) *httptest.ResponseRecorder {
return clipboardRequest(t, srv, http.MethodGet, "?accept=files&since="+since, "", "", nil)
}
copyAndRead := func(previousHash, wantSeq, wantContents string) (string, string) {
t.Helper()
clip.WriteFiles([]string{file})
resp := poll(previousHash)
hash := resp.Header().Get("X-Clip-Hash")
if resp.Code != http.StatusOK || hash == "" || hash == previousHash || resp.Header().Get("X-Clip-Seq") != wantSeq {
t.Fatalf("new copy: %d %v %s", resp.Code, resp.Header(), resp.Body)
}
var manifest struct {
DropID string `json:"drop_id"`
Items []string `json:"items"`
}
if err := json.Unmarshal(resp.Body.Bytes(), &manifest); err != nil || !slices.Equal(manifest.Items, []string{"a.txt"}) {
t.Fatalf("manifest %q, err=%v", resp.Body, err)
}
req := httptest.NewRequest(http.MethodGet, "/dav-drop/clipboard-test/"+manifest.DropID+"/a.txt", nil)
req.Header.Set("Authorization", "Bearer clipboard-test-token")
dav := httptest.NewRecorder()
srv.handleDropWebDAV(dav, req)
if dav.Code != http.StatusOK || dav.Body.String() != wantContents {
t.Fatalf("GET %s: %d %q, want %q", req.URL, dav.Code, dav.Body, wantContents)
}
return hash, manifest.DropID
}
hash, id := copyAndRead("", "10", "original")
// A Finder copy can replace the guest clipboard without changing the
// last host hash that the guest sends in its next conditional poll.
nextHash, nextID := copyAndRead(hash, "11", "original")
if nextID == id {
t.Fatal("copying the unchanged file again reused its WebDAV URL")
}
modTime := store.modTime
writeFile("edited on disk")
for range 3 {
resp := poll(nextHash)
if resp.Code != http.StatusNotModified || resp.Body.Len() != 0 || resp.Header().Get("X-Clip-Hash") != nextHash ||
resp.Header().Get("X-Clip-Seq") != "11" || !store.modTime.Equal(modTime) {
t.Fatalf("disk edit without copy: %d %v, root modTime %v (was %v)", resp.Code, resp.Header(), store.modTime, modTime)
}
}
_, editedID := copyAndRead(nextHash, "12", "edited on disk")
if editedID == nextID || editedID == id {
t.Fatal("copying the edited file reused a cached WebDAV URL")
}
}
type fileClipboardSnapshot struct {
*memClipboard
payload ClipPayload
reads int
}
func (c *fileClipboardSnapshot) readClipboard(bool, bool) (ClipPayload, uint32, error) {
c.reads++
return c.payload, 23, nil
}
func TestClipboardGETFilteredFileCompanion(t *testing.T) {
text := ClipPayload{Kind: ClipText, Data: []byte("copied caption")}
image := ClipPayload{Kind: ClipPNG, Data: makeSamplePNG(t, 1, 2, 3)}
blocked := []string{`\\server\share\file.txt`}
local := filepath.Join(t.TempDir(), "local.txt")
if err := os.WriteFile(local, []byte("local"), 0600); err != nil {
t.Fatal(err)
}
overflow := slices.Repeat([]string{local}, MaxClipboardFiles+1)
for _, tc := range []struct {
name string
paths []string
companion ClipPayload
accept string
maxImage int
want ClipKind
}{
{"filtered with text", blocked, text, "files", 0, ClipText},
{"overflow with text", overflow, text, "files", 0, ClipText},
{"filtered with PNG", blocked, image, "files,image", len(image.Data), ClipPNG},
{"PNG not requested", blocked, image, "files", 0, ClipEmpty},
{"PNG over policy limit", blocked, image, "files,image", len(image.Data) - 1, ClipEmpty},
{"v13 guest requests only the companion PNG", []string{local}, image, "image", len(image.Data), ClipPNG},
{"valid file takes priority", []string{local}, text, "files", 0, ClipFiles},
} {
t.Run(tc.name, func(t *testing.T) {
clip := &fileClipboardSnapshot{memClipboard: &memClipboard{}, payload: withClipboardFiles(tc.paths, tc.companion)}
srv := newClipboardTestServer(clip)
policy := DefaultClipboardPolicy()
policy.MaxImageBytes = tc.maxImage
srv.SetVMClipboardPolicy("clipboard-test", &policy)
resp := clipboardRequest(t, srv, http.MethodGet, "?accept="+tc.accept, "", "", nil)
if clip.reads != 1 || resp.Header().Get("X-Clip-Seq") != "23" {
t.Fatalf("clipboard reads=%d, headers %v", clip.reads, resp.Header())
}
if tc.want == ClipEmpty {
if resp.Code != http.StatusNotModified || resp.Body.Len() != 0 {
t.Fatalf("unavailable companion: %d %q", resp.Code, resp.Body)
}
} else if resp.Code != http.StatusOK || resp.Header().Get("X-Clip-Kind") != string(tc.want) {
t.Fatalf("GET: %d %v", resp.Code, resp.Header())
} else if tc.want != ClipFiles && (!bytes.Equal(resp.Body.Bytes(), tc.companion.Data) || resp.Header().Get("X-Clip-Hash") != payloadHash(tc.companion)) {
t.Fatalf("companion: %v %q", resp.Header(), resp.Body)
}
if tc.want == ClipPNG && resp.Header().Get("Content-Type") != "image/png" {
t.Fatalf("PNG response has content type %q", resp.Header().Get("Content-Type"))
}
if tc.want != ClipFiles && len(srv.vms[vmRegistryKey("", "clipboard-test")].dropShares.records) != 0 {
t.Fatal("filtered selection created a file share")
}
})
}
}