-
Notifications
You must be signed in to change notification settings - Fork 5
/
integration_test.go
711 lines (689 loc) · 21.8 KB
/
integration_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
// This files contains testing suites that test webexec as a compoennt and
// using a test client
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/pion/webrtc/v3"
"github.com/stretchr/testify/require"
"github.com/tuzig/webexec/peers"
"go.uber.org/fx/fxtest"
)
// SendRestore sends an restore message
func SendRestore(cdc *webrtc.DataChannel, ref int, marker int) error {
time.Sleep(10 * time.Millisecond)
msg := peers.CTRLMessage{
Time: time.Now().UnixNano(),
Type: "restore",
Ref: ref,
Args: peers.RestoreArgs{marker},
}
restoreMsg, err := json.Marshal(msg)
if err != nil {
return fmt.Errorf("Failed to marshal the auth args: %v", err)
}
cdc.Send(restoreMsg)
return nil
}
// waitForChild waits for a give timeout for for a process to die
func waitForChild(pid int, timeout time.Duration) error {
start := time.Now()
for time.Since(start) <= timeout {
if !isAlive(pid) {
return nil
}
time.Sleep(10 * time.Millisecond)
}
return fmt.Errorf("process %d still alive (timeout=%v)", pid, timeout)
}
// SignalPair is used to start a connection between a peer and a client
func SignalPair(client *webrtc.PeerConnection, peer *peers.Peer) error {
// Note(albrow): We need to create a data channel in order to trigger ICE
// candidate gathering in the background for the JavaScript/Wasm bindings. If
// we don't do this, the complete offer including ICE candidates will never be
// generated.
if _, err := client.CreateDataChannel("signaling", nil); err != nil {
return err
}
offer, err := client.CreateOffer(nil)
if err != nil {
return err
}
gatherComplete := webrtc.GatheringCompletePromise(client)
if err := client.SetLocalDescription(offer); err != nil {
return err
}
select {
case <-time.After(5 * time.Second):
return fmt.Errorf("timed mockedMsgs waiting to finish gathering ICE candidates")
case <-gatherComplete:
answer, err := peer.Listen(*client.LocalDescription())
if err != nil {
return err
}
err = client.SetRemoteDescription(*answer)
if err != nil {
return err
}
return nil
}
}
func getMarker(cdc *webrtc.DataChannel) int {
lastRef++
ref := lastRef
// sleep to simulate latency
time.Sleep(10 * time.Millisecond)
//TODO we need something like peer.LastMsgId++ below
msg := peers.CTRLMessage{
Time: time.Now().UnixNano(),
Type: "mark",
Ref: ref,
Args: nil,
}
markMsg, err := json.Marshal(msg)
if err != nil {
return -1
}
cdc.Send(markMsg)
return ref
}
// ParseAck parses and ack message and returns its args
func ParseAck(t *testing.T, msg webrtc.DataChannelMessage) peers.AckArgs {
var args json.RawMessage
var ackArgs peers.AckArgs
env := peers.CTRLMessage{
Args: &args,
}
err := json.Unmarshal(msg.Data, &env)
require.Nil(t, err, "failed to unmarshal cdc message: %q", err)
require.Equal(t, env.Type, "ack",
"Expected an ack message and got %q", env.Type)
err = json.Unmarshal(args, &ackArgs)
require.Nil(t, err, "failed to unmarshal ack args: %q", err)
return ackArgs
}
func TestSimpleEcho(t *testing.T) {
initTest(t)
Logger.Infof("TestSimpleEcho")
closed := make(chan bool)
client, certs, err := NewClient(true)
require.Nil(t, err, "Failed to create a new client %v", err)
defer client.Close()
peer := newPeer(t, "A", certs)
// count the incoming messages
count := 0
dc, err := client.CreateDataChannel("echo,hello world", nil)
require.Nil(t, err, "Failed to create the echo data channel: %v", err)
dc.OnOpen(func() {
Logger.Infof("Channel %q opened", dc.Label())
})
dc.OnMessage(func(msg webrtc.DataChannelMessage) {
// first get a channel Id and then "hello world" text
Logger.Infof("got message: #%d %q", count, string(msg.Data))
if count == 0 {
_, err = strconv.Atoi(string(msg.Data))
require.Nil(t, err, "Failed to cover channel it to int: %v", err)
} else if count == 1 {
require.EqualValues(t, string(msg.Data)[:11], "hello world",
"Got bad msg: %q", msg.Data)
}
count++
})
dc.OnClose(func() {
Logger.Info("Client Data channel closed")
closed <- true
})
err = SignalPair(client, peer)
require.NoError(t, err, "Signaling failed: %v", err)
// TODO: add timeout
Logger.Infof("Waiting for the channel to close")
<-closed
Logger.Infof("TestSimpleEcho done")
panes := peers.Panes.All()
lp := panes[len(panes)-1]
waitForChild(lp.C.Process.Pid, time.Second)
lp.Lock()
require.False(t, lp.IsRunning)
lp.Unlock()
// For some reason we sometimes get an empty message and count can be 3
require.GreaterOrEqual(t, count, 2, "Expected to recieve 2 messages and got %d", count)
}
func TestResizeCommand(t *testing.T) {
initTest(t)
done := make(chan bool)
client, certs, err := NewClient(true)
require.Nil(t, err, "Failed to create a new client %v", err)
defer client.Close()
peer := newPeer(t, "A", certs)
cdc, err := client.CreateDataChannel("%", nil)
require.Nil(t, err, "failed to create the control data channel: %v", err)
cdc.OnOpen(func() {
// control channel is open let's open another one, so we'll have
// what to resize
// dc, err := client.CreateDataChannel("12x34,bash", nil)
// require.Nil(t, err, "failed to create the a channel: %v", err)
addPaneArgs := peers.AddPaneArgs{Rows: 12, Cols: 34,
Command: []string{"bash"}}
m := peers.CTRLMessage{time.Now().UnixNano(), 123, "add_pane",
&addPaneArgs}
addPaneMsg, err := json.Marshal(m)
require.NoError(t, err, "failed marshilng ctrl msg: %s", err)
Logger.Info("Sending the addPane message")
cdc.Send(addPaneMsg)
})
cdc.OnMessage(func(msg webrtc.DataChannelMessage) {
ack := ParseAck(t, msg)
if ack.Ref == 123 {
// parse add_pane and send the resize command
// extract paneID from the ack body whcih is raw json
paneID, err := strconv.Atoi(string(ack.Body))
require.NoError(t, err, "failed to unmarshal ack body: %s", err)
require.NotEqual(t, -1, paneID, "Got a bad pane id: %d", paneID)
resizeArgs := peers.ResizeArgs{paneID, 80, 24}
m := peers.CTRLMessage{time.Now().UnixNano(), 456, "resize",
&resizeArgs}
resizeMsg, err := json.Marshal(m)
require.Nil(t, err, "failed marshilng ctrl msg: %v", err)
Logger.Info("Sending the resize message")
cdc.Send(resizeMsg)
} else if ack.Ref == 456 {
done <- true
}
})
// all set, let's start the signaling
SignalPair(client, peer)
select {
case <-time.After(3 * time.Second):
t.Error("Timeout waiting for dat ain reconnected pane")
case <-done:
}
}
func TestPayloadOperations(t *testing.T) {
initTest(t)
done := make(chan bool)
client, certs, err := NewClient(true)
require.Nil(t, err, "Failed to create a new client %v", err)
defer client.Close()
peer := newPeer(t, "A", certs)
cdc, err := client.CreateDataChannel("%", nil)
require.Nil(t, err, "Failed to create the control data channel: %v", err)
payload := []byte("[\"Better payload\"]")
cdc.OnOpen(func() {
time.Sleep(10 * time.Millisecond)
args := peers.SetPayloadArgs{payload}
setPayload := peers.CTRLMessage{time.Now().UnixNano(), 777,
"set_payload", &args}
setMsg, err := json.Marshal(setPayload)
require.Nil(t, err, "Failed to marshal the auth args: %v", err)
Logger.Info("Sending set_payload msg")
cdc.Send(setMsg)
})
cdc.OnMessage(func(msg webrtc.DataChannelMessage) {
// we should get an ack for the auth message and the get payload
Logger.Infof("Got a ctrl msg: %s", msg.Data)
args := ParseAck(t, msg)
if args.Ref == 777 {
require.Nil(t, err, "Failed to unmarshall the control data channel: %v", err)
require.Equal(t, payload, []byte(args.Body),
"Got the wrong payload: %q", args.Body)
done <- true
}
})
SignalPair(client, peer)
select {
case <-time.After(3 * time.Second):
t.Error("Timeout waiting for payload data")
case <-done:
}
// TODO: now get_payload and make sure it's the same
}
func TestMarkerRestore(t *testing.T) {
initTest(t)
var (
cID string
dc *webrtc.DataChannel
markerRef int
markerMutex sync.Mutex
marker int
)
gotSetMarkerAck := make(chan bool)
gotFirst := make(chan bool)
gotSecondAgain := make(chan bool)
gotAck := make(chan bool)
client, certs, err := NewClient(true)
require.Nil(t, err, "Failed to create a new client %v", err)
defer client.Close()
// start the server
peer := newPeer(t, "A", certs)
require.Nil(t, err, "Failed to start a new server %v", err)
// create the command & control data channel
cdc, err := client.CreateDataChannel("%", nil)
require.Nil(t, err, "Failed to create the control data channel: %v", err)
// count the incoming messages
count := 0
cdc.OnOpen(func() {
Logger.Info("cdc is opened")
cdc.OnMessage(func(msg webrtc.DataChannelMessage) {
// we should get an ack for the auth message
var cm peers.CTRLMessage
Logger.Infof("Got a ctrl msg: %s", msg.Data)
err := json.Unmarshal(msg.Data, &cm)
require.Nil(t, err, "Failed to marshal the server msg: %v", err)
if cm.Type == "ack" {
args := ParseAck(t, msg)
markerMutex.Lock()
defer markerMutex.Unlock()
if args.Ref == markerRef {
// convert the body to int
marker, err = strconv.Atoi(string(args.Body))
require.NoError(t, err)
Logger.Infof("Got marker: %d", marker)
gotSetMarkerAck <- true
}
}
})
dc, err = client.CreateDataChannel(
"24x80,bash,-c,echo 123456 ; sleep 1; echo 789; sleep 9", nil)
require.Nil(t, err, "Failed to create the echo data channel: %v", err)
dc.OnOpen(func() {
Logger.Infof("Channel %q opened", dc.Label())
})
dc.OnMessage(func(msg webrtc.DataChannelMessage) {
Logger.Infof("DC Got msg #%d: %s", count, msg.Data)
if len(msg.Data) > 0 {
if count == 0 {
cID = string(msg.Data)
Logger.Infof("Client got a channel id: %q", cID)
}
if count == 1 {
require.Contains(t, string(msg.Data), "123456")
gotFirst <- true
}
count++
}
})
})
SignalPair(client, peer)
select {
case <-time.After(6 * time.Second):
t.Error("Timeout waiting for first datfirst data data")
case <-gotFirst:
}
markerMutex.Lock()
markerRef = getMarker(cdc)
markerMutex.Unlock()
select {
case <-time.After(6 * time.Second):
t.Error("Timeout waiting for marker ack")
case <-gotSetMarkerAck:
}
client2, certs, err := NewClient(true)
require.Nil(t, err, "Failed to create the second client %v", err)
defer client2.Close()
peer2 := newPeer(t, "A", certs)
require.Nil(t, err, "Failed to start a new server %v", err)
// create the command & control data channel
SignalPair(client2, peer2)
cdc2, err := client2.CreateDataChannel("%", nil)
require.Nil(t, err, "Failed to create the control data channel: %v", err)
// count the incoming messages
cdc2.OnOpen(func() {
// send the restore message "marker"
go SendRestore(cdc2, 345, marker)
cdc2.OnMessage(func(msg webrtc.DataChannelMessage) {
// we should get an ack for the auth message
var cm peers.CTRLMessage
err := json.Unmarshal(msg.Data, &cm)
require.Nil(t, err, "Failed to marshal the server msg: %v", err)
Logger.Info("client2 got msg: %v", cm)
if cm.Type == "ack" {
gotAck <- true
}
})
<-gotAck
time.Sleep(time.Second)
dc, err = client2.CreateDataChannel(">"+cID, nil)
require.Nil(t, err, "Failed to create the echo data channel: %v", err)
dc.OnOpen(func() {
Logger.Infof("TS> Channel %q re-opened", dc.Label())
})
dc.OnMessage(func(msg webrtc.DataChannelMessage) {
// ignore null messages
if len(msg.Data) > 0 {
require.Contains(t, string(msg.Data), "789")
gotSecondAgain <- true
}
})
})
select {
case <-time.After(3 * time.Second):
t.Error("Timeout waiting for restored data")
case <-gotSecondAgain:
}
}
func TestAddPaneMessage(t *testing.T) {
initTest(t)
var wg sync.WaitGroup
// the trinity: a new datachannel, an ack and BADWOLF (aka command output)
wg.Add(3)
client, certs, err := NewClient(true)
require.Nil(t, err, "Failed to create a new client %v", err)
defer client.Close()
peer := newPeer(t, "A", certs)
done := make(chan bool)
client.OnDataChannel(func(d *webrtc.DataChannel) {
d.OnMessage(func(msg webrtc.DataChannelMessage) {
Logger.Infof("Got a new datachannel message: %s", string(msg.Data))
require.Equal(t, "BADWOLF", string(msg.Data[:7]))
Logger.Infof(string(msg.Data))
wg.Done()
})
l := d.Label()
Logger.Infof("Got a new datachannel: %s", l)
require.Regexp(t, regexp.MustCompile("^456:[0-9]+"), l)
wg.Done()
})
cdc, err := client.CreateDataChannel("%", nil)
require.Nil(t, err, "failed to create the control data channel: %v", err)
cdc.OnOpen(func() {
Logger.Info("cdc opened")
cdc.OnMessage(func(msg webrtc.DataChannelMessage) {
ack := ParseAck(t, msg)
if ack.Ref == 456 {
Logger.Infof("Got the ACK")
wg.Done()
}
})
addPaneArgs := peers.AddPaneArgs{Rows: 12, Cols: 34,
Command: []string{"echo", "BADWOLF"}} //, "&&", "sleep", "5"}}
m := peers.CTRLMessage{time.Now().UnixNano(), 456, "add_pane",
&addPaneArgs}
msg, err := json.Marshal(m)
require.Nil(t, err, "failed marshilng ctrl msg: %v", msg)
time.Sleep(time.Second / 10)
cdc.Send(msg)
})
go func() {
wg.Wait()
done <- true
}()
SignalPair(client, peer)
select {
case <-time.After(6 * time.Second):
t.Error("Timeout waiting for server to open channel")
case <-done:
}
}
func TestReconnectPane(t *testing.T) {
initTest(t)
var (
wg sync.WaitGroup
gotMsg sync.WaitGroup
ci int
)
client, certs, err := NewClient(true)
require.Nil(t, err, "Failed to create a new client %v", err)
defer client.Close()
peer := newPeer(t, "A", certs)
client.OnDataChannel(func(d *webrtc.DataChannel) {
l := d.Label()
//fs := strings.Split(d.Label(), ",")
d.OnMessage(func(msg webrtc.DataChannelMessage) {
if len(msg.Data) > 0 {
Logger.Infof("Got a message in %s: %s", l, string(msg.Data))
if strings.Contains(string(msg.Data), "BADWOLF") {
gotMsg.Done()
}
}
})
Logger.Infof("Got a new datachannel: %s", l)
require.Regexp(t, regexp.MustCompile("^45[67]:[0-9]+"), l)
wg.Done()
})
cdc, err := client.CreateDataChannel("%", nil)
require.Nil(t, err, "failed to create the control data channel: %v", err)
cdc.OnOpen(func() {
Logger.Info("cdc opened")
cdc.OnMessage(func(msg webrtc.DataChannelMessage) {
Logger.Infof("cdc got an ack: %v", string(msg.Data))
ack := ParseAck(t, msg)
if ack.Ref == 456 {
ci, err = strconv.Atoi(string(ack.Body))
require.Nil(t, err)
wg.Done()
}
})
time.Sleep(time.Second / 100)
addPaneArgs := peers.AddPaneArgs{Rows: 12, Cols: 34,
Command: []string{"bash", "-c", "sleep 1; echo BADWOLF"}}
m := peers.CTRLMessage{time.Now().UnixNano(), 456, "add_pane",
&addPaneArgs}
msg, err := json.Marshal(m)
require.Nil(t, err, "failed marshilng ctrl msg: %v", msg)
cdc.Send(msg)
})
wg.Add(2)
gotMsg.Add(2)
SignalPair(client, peer)
wg.Wait()
Logger.Infof("After first wait")
wg.Add(1)
a := peers.ReconnectPaneArgs{ID: ci}
m := peers.CTRLMessage{time.Now().UnixNano(), 457, "reconnect_pane",
&a}
msg, err := json.Marshal(m)
require.Nil(t, err, "failed marshilng ctrl msg: %v", msg)
cdc.Send(msg)
gotMsg.Wait()
}
func TestExecCommand(t *testing.T) {
initTest(t)
c := []string{"bash", "-c", "echo hello"}
_, tty, err := peers.ExecCommand(c, nil, nil, 0, "")
b := make([]byte, 64)
l, err := tty.Read(b)
require.Nil(t, err)
require.Less(t, 6, l, "Expected at least 5 bytes %s", string(b))
require.Equal(t, "hello", string(b[:5]))
}
func TestExecCommandWithParent(t *testing.T) {
initTest(t)
c := []string{"sh"}
cmd, tty, err := peers.ExecCommand(c, nil, nil, 0, "")
time.Sleep(time.Second / 100)
_, err = tty.Write([]byte("cd /tmp\n"))
require.Nil(t, err)
_, err = tty.Write([]byte("pwd\n"))
require.Nil(t, err)
time.Sleep(time.Second / 10)
_, tty2, err := peers.ExecCommand([]string{"pwd"}, nil, nil, cmd.Process.Pid, "")
require.Nil(t, err)
b := make([]byte, 64)
l, err := tty2.Read(b)
require.NoError(t, err)
require.Less(t, 5, l, "Expected at least 5 bytes %s", string(b))
// validate that the pwd ends with "/tmp"
cwd := string(b[:l])
require.True(t, strings.HasSuffix(cwd, "/tmp\r\n"), "Expected ouput to end with /tmp, got %s", cwd)
}
func TestPasteCommand(t *testing.T) {
done := make(chan bool)
initTest(t)
// init socket server
lifecycle := fxtest.NewLifecycle(t)
k := KeyType{}
certificate, err := k.generate()
require.NoError(t, err, "Failed to generate a certificate", err)
conf := peers.Conf{
Certificate: certificate,
AckTimeout: time.Second,
Logger: Logger,
DisconnectTimeout: time.Second,
FailedTimeout: time.Second,
KeepAliveInterval: time.Second,
GatheringTimeout: time.Second,
GetICEServers: func() ([]webrtc.ICEServer, error) {
return nil, nil
},
}
sockServer := NewSockServer(&conf)
require.NotNil(t, sockServer, "Failed to create a new server")
startParams := SocketStartParams{t.TempDir()}
server, err := StartSocketServer(lifecycle, sockServer, startParams)
require.NoError(t, err, "Failed to start a new server")
require.NotNil(t, server, "Failed to start a new server")
lifecycle.RequireStart()
defer lifecycle.RequireStop()
client, certs, err := NewClient(true)
require.Nil(t, err, "Failed to create a new client %v", err)
defer client.Close()
peer := newPeer(t, "A", certs)
peers.SetLastPeer(peer)
cdc, err := client.CreateDataChannel("%", nil)
require.Nil(t, err, "failed to create the control data channel: %v", err)
cdc.OnOpen(func() {
addPaneArgs := peers.AddPaneArgs{Rows: 12, Cols: 34,
Command: []string{"bash"}}
m := peers.CTRLMessage{time.Now().UnixNano(), 123, "add_pane",
&addPaneArgs}
addPaneMsg, err := json.Marshal(m)
require.NoError(t, err, "failed marshilng ctrl msg: %s", err)
Logger.Info("Sending the addPane message")
cdc.Send(addPaneMsg)
})
cdc.OnMessage(func(msg webrtc.DataChannelMessage) {
// parse json message
var cm peers.CTRLMessage
err := json.Unmarshal(msg.Data, &cm)
require.Nil(t, err)
switch cm.Type {
case "ack":
go func() {
fp := GetSockFP()
Logger.Infof("Got a fp: %s", fp)
httpc := http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", fp)
},
},
}
resp, err := httpc.Get("http://unix/clipboard")
require.NoError(t, err, "Failed sending a post request: %q", err)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode, "Got a bad status code: %d: %s", resp.StatusCode, body)
require.Equal(t, "echo hello", string(body))
done <- true
}()
case "get_clipboard":
// send the ack with the clipboard in the body
ack := peers.CTRLMessage{Ref: 456, Type: "ack",
Args: &peers.AckArgs{Body: "echo hello", Ref: cm.Ref}}
ackMsg, err := json.Marshal(ack)
require.Nil(t, err)
cdc.Send(ackMsg)
Logger.Info("Sent the ack")
default:
t.Errorf("Got a bad message: %s", cm.Type)
}
})
SignalPair(client, peer)
select {
case <-time.After(6 * time.Second):
t.Error("Timeout waiting for server to open channel")
case <-done:
}
}
func TestCopyCommand(t *testing.T) {
done := make(chan bool)
initTest(t) // Setup test dependencies
// Initialize socket server
lifecycle := fxtest.NewLifecycle(t)
k := KeyType{}
certificate, err := k.generate()
require.NoError(t, err, "Failed to generate a certificate")
conf := peers.Conf{
Certificate: certificate,
AckTimeout: time.Second,
// Remaining configuration similar to TestPasteCommand
}
sockServer := NewSockServer(&conf)
require.NotNil(t, sockServer, "Failed to create a new server")
startParams := SocketStartParams{t.TempDir()}
server, err := StartSocketServer(lifecycle, sockServer, startParams)
require.NoError(t, err, "Failed to start a new server")
require.NotNil(t, server, "Failed to start a new server")
lifecycle.RequireStart()
defer lifecycle.RequireStop()
client, certs, err := NewClient(true)
require.Nil(t, err, "Failed to create a new client")
defer client.Close()
peer := newPeer(t, "B", certs)
peers.SetLastPeer(peer)
cdc, err := client.CreateDataChannel("%", nil)
require.Nil(t, err, "failed to create the control data channel")
cdc.OnOpen(func() {
addPaneArgs := peers.AddPaneArgs{Rows: 12, Cols: 34,
Command: []string{"bash"}}
m := peers.CTRLMessage{time.Now().UnixNano(), 123, "add_pane",
&addPaneArgs}
addPaneMsg, err := json.Marshal(m)
require.NoError(t, err, "failed marshilng ctrl msg: %s", err)
Logger.Info("Sending the addPane message")
cdc.Send(addPaneMsg)
})
cdc.OnMessage(func(msg webrtc.DataChannelMessage) {
// Handle responses similar to TestPasteCommand, adjust based on copy command spec
var cm peers.CTRLMessage
err := json.Unmarshal(msg.Data, &cm)
require.Nil(t, err)
switch cm.Type {
case "ack":
go func() {
Logger.Infof("Got a fp: %s", startParams.fp)
httpc := http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", startParams.fp)
},
},
}
// Use POST method for /copy to simulate sending data to the server
resp, err := httpc.Post("http://unix/clipboard", "text/plain",
strings.NewReader("copy this text"))
require.NoError(t, err, "Failed sending a post request")
require.Equal(t, http.StatusOK, resp.StatusCode, "Expected no content status code, got: %d", resp.StatusCode)
}()
break
// Handle other cases or TODOs if necessary
case "set_clipboard":
// verify the clipboard content is in the body
args, ok := cm.Args.(map[string]interface{})
require.True(t, ok, "Failed to cast args")
mime := args["mimetype"].(string)
require.Equal(t, "text/plain", mime, "Expected mimetype to be 'text/plain'")
text := args["data"].(string)
require.Equal(t, "copy this text", text, "Expected clipboard content to be 'copy this text'")
done <- true
default:
t.Errorf("Got an unexpected message: %s", cm.Type)
}
})
SignalPair(client, peer)
select {
case <-time.After(time.Second * 6):
t.Error("Timeout waiting for copy action to complete")
case <-done:
}
}