File size: 41,602 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Management.Automation.Language;
using System.Management.Automation.Subsystem;
using System.Management.Automation.Subsystem.Prediction;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;

namespace PSTests.Sequential
{
    public class RemoteHyperVTests
    {
        private static ITestOutputHelper _output;

        public RemoteHyperVTests(ITestOutputHelper output)
        {
            if (!System.Management.Automation.Platform.IsWindows)
            {
                throw new SkipException("RemoteHyperVTests are only supported on Windows.");
            }

            _output = output;
        }

        // Helper method to connect with retries
        private static void ConnectWithRetry(Socket client, IPAddress address, int port, ITestOutputHelper output, int maxRetries = 10)
        {
            int retryDelayMs = 500;
            int attempt = 0;
            bool connected = false;
            while (attempt < maxRetries && !connected)
            {
                try
                {
                    client.Connect(address, port);
                    connected = true;
                }
                catch (SocketException)
                {
                    attempt++;
                    if (attempt < maxRetries)
                    {
                        output?.WriteLine($"Connect attempt {attempt} failed, retrying in {retryDelayMs}ms...");
                        Thread.Sleep(retryDelayMs);
                        retryDelayMs *= 2;
                    }
                    else
                    {
                        output?.WriteLine($"Failed to connect after {maxRetries} attempts.  This is most likely an intermittent failure due to environmental issues.");
                        throw;
                    }
                }
            }
        }

        private static void SendResponse(string name, Socket client, Queue<(byte[] bytes, int delayMs)> serverResponses)
        {
            if (serverResponses.Count > 0)
            {
                _output.WriteLine($"Mock {name} ----------------------------------------------------");
                var respTuple = serverResponses.Dequeue();
                var resp = respTuple.bytes;

                if (respTuple.delayMs > 0)
                {
                    _output.WriteLine($"Mock {name} - delaying response by {respTuple.delayMs} ms");
                    Thread.Sleep(respTuple.delayMs);
                }
                if (resp.Length > 0) {
                    client.Send(resp, resp.Length, SocketFlags.None);
                    _output.WriteLine($"Mock {name} - sent response: " + Encoding.ASCII.GetString(resp));
                }
            }
        }

        private static void StartHandshakeServer(
            string name,
            int port,
            IEnumerable<(string message, Encoding encoding)> expectedClientSends,
            IEnumerable<(string message, Encoding encoding)> serverResponses,
            bool verifyConnectionClosed,
            CancellationToken cancellationToken,
            bool sendFirst = false)
        {
            IEnumerable<(string message, Encoding encoding, int delayMs)> serverResponsesWithDelay = new List<(string message, Encoding encoding, int delayMs)>();
            foreach (var item in serverResponses)
            {
                ((List<(string message, Encoding encoding, int delayMs)>)serverResponsesWithDelay).Add((item.message, item.encoding, 1));
            }
            StartHandshakeServer(name, port, expectedClientSends, serverResponsesWithDelay, verifyConnectionClosed, cancellationToken, sendFirst);
        }

        private static void StartHandshakeServer(
            string name,
            int port,
            IEnumerable<(string message, Encoding encoding)> expectedClientSends,
            IEnumerable<(string message, Encoding encoding, int delayMs)> serverResponses,
            bool verifyConnectionClosed,
            CancellationToken cancellationToken,
            bool sendFirst = false)
        {
            var expectedMessages = new Queue<(string message, byte[] bytes, Encoding encoding)>();
            foreach (var item in expectedClientSends)
            {
                var itemBytes = item.encoding.GetBytes(item.message);
                expectedMessages.Enqueue((message: item.message, bytes: itemBytes, encoding: item.encoding));
            }

            var serverResponseBytes = new Queue<(byte[] bytes, int delayMs)>();
            foreach (var item in serverResponses)
            {
                (byte[] bytes, int delayMs) queueItem = (item.encoding.GetBytes(item.message), item.delayMs);
                serverResponseBytes.Enqueue(queueItem);
            }

            _output.WriteLine($"Mock {name} - starting listener on port {port} with {expectedMessages.Count} expected messages and {serverResponseBytes.Count} responses.");
            StartHandshakeServerImplementation(name, port, expectedMessages, serverResponseBytes, verifyConnectionClosed, cancellationToken, sendFirst);
        }

        private static void StartHandshakeServerImplementation(
            string name,
            int port,
            Queue<(string message, byte[] bytes, Encoding encoding)> expectedClientSends,
            Queue<(byte[] bytes, int delayMs)> serverResponses,
            bool verifyConnectionClosed,
            CancellationToken cancellationToken,
            bool sendFirst = false)
        {
            DateTime startTime = DateTime.UtcNow;
            var buffer = new byte[1024];
            var listener = new TcpListener(IPAddress.Loopback, port);
            listener.Start();
            try
            {
                using (var client = listener.AcceptSocket())
                {
                    if (sendFirst)
                    {
                        // Send the first message from the serverResponses queue
                        SendResponse(name, client, serverResponses);
                    }

                    while (expectedClientSends.Count > 0)
                    {
                        _output.WriteLine($"Mock {name} - time elapsed: {(DateTime.UtcNow - startTime).TotalMilliseconds} milliseconds");
                        client.ReceiveTimeout = 2 * 1000; // 2 seconds timeout for receiving data
                        cancellationToken.ThrowIfCancellationRequested();
                        var expectedMessage = expectedClientSends.Dequeue();
                        _output.WriteLine($"Mock {name} - remaining expected messages: {expectedClientSends.Count}");
                        var expected = expectedMessage.bytes;
                        Array.Clear(buffer, 0, buffer.Length);
                        int received = client.Receive(buffer);
                        // Optionally validate received data matches expected
                        string expectedString = expectedMessage.message;
                        string bufferString = expectedMessage.encoding.GetString(buffer, 0, received);
                        string alternativeEncodedString = string.Empty;
                        if (expectedMessage.encoding == Encoding.Unicode)
                        {
                            alternativeEncodedString = Encoding.UTF8.GetString(buffer, 0, received);
                        }
                        else if (expectedMessage.encoding == Encoding.UTF8)
                        {
                            alternativeEncodedString = Encoding.Unicode.GetString(buffer, 0, received);
                        }

                        if (received != expected.Length)
                        {
                            string errorMessage = $"Mock {name} - Expected {expected.Length} bytes, but received {received} bytes: `{bufferString}`(alt encoding: `{alternativeEncodedString}`); expected: {expectedString}";
                            _output.WriteLine(errorMessage);
                            throw new Exception(errorMessage);
                        }
                        if (!string.Equals(bufferString, expectedString, StringComparison.OrdinalIgnoreCase))
                        {
                            string errorMessage = $"Mock {name} - Expected `{expectedString}`; length {expected.Length}, but received; length {received}; `{bufferString}`(alt encoding: `{alternativeEncodedString}`) instead.";
                            _output.WriteLine(errorMessage);
                            throw new Exception(errorMessage);
                        }
                        _output.WriteLine($"Mock {name} - received expected message: " + expectedString);
                        SendResponse(name, client, serverResponses);
                    }

                    if (verifyConnectionClosed)
                    {
                        _output.WriteLine($"Mock {name} - verifying client connection is closed.");
                        // Wait for the client to close the connection synchronously (no timeout)
                        try
                        {
                            while (true)
                            {
                                int bytesRead = client.Receive(buffer, SocketFlags.None);
                                if (bytesRead == 0)
                                {
                                    break;
                                }

                                // If we receive any data, log and throw (assume UTF8 encoding)
                                string unexpectedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                                _output.WriteLine($"Mock {name} - received unexpected data after handshake: {unexpectedData}");
                                throw new Exception($"Mock {name} - received unexpected data after handshake: {unexpectedData}");
                            }
                            _output.WriteLine($"Mock {name} - client closed the connection.");
                        }
                        catch (SocketException ex)
                        {
                            _output.WriteLine($"Mock {name} - socket exception while waiting for client close: {ex.Message} {ex.GetType().FullName}");
                        }
                        catch (ObjectDisposedException)
                        {
                            _output.WriteLine($"Mock {name} - socket already closed.");
                            // Socket already closed
                        }
                    }
                }

                _output.WriteLine($"Mock {name} - on port {port} completed successfully.");
            }
            catch (Exception ex)
            {
                _output.WriteLine($"Mock {name} - Exception: {ex.Message} {ex.GetType().FullName}");
                _output.WriteLine(ex.StackTrace);
                throw;
            }
            finally
            {
                _output.WriteLine($"Mock {name} - remaining expected messages: {expectedClientSends.Count}");
                _output.WriteLine($"Mock {name} - stopping listener on port {port}.");
                listener.Stop();
            }
        }

        // Helper function to create a random 4-character ASCII response
        private static string CreateRandomAsciiResponse()
        {
            var rand = new Random();
            // Randomly return either "PASS" or "FAIL"
            return rand.Next(0, 2) == 0 ? "PASS" : "FAIL";
        }

        // Helper method to create test data
        private static (List<(string, Encoding)> expectedClientSends, List<(string, Encoding)> serverResponses) CreateHandshakeTestData(NetworkCredential cred)
        {
            var expectedClientSends = new List<(string message, Encoding encoding)>
            {
                (message: cred.Domain, encoding: Encoding.Unicode),
                (message: cred.UserName, encoding: Encoding.Unicode),
                (message: "NONEMPTYPW", encoding: Encoding.ASCII),
                (message: cred.Password, encoding: Encoding.Unicode)
            };

            var serverResponses = new List<(string message, Encoding encoding)>
            {
                (message: CreateRandomAsciiResponse(), encoding: Encoding.ASCII), // Response to domain
                (message: CreateRandomAsciiResponse(), encoding: Encoding.ASCII), // Response to username
                (message: CreateRandomAsciiResponse(), encoding: Encoding.ASCII)  // Response to non-empty password
            };

            return (expectedClientSends, serverResponses);
        }

        private static List<(string message, Encoding encoding)> CreateVersionNegotiationClientSends()
        {
            return new List<(string message, Encoding encoding)>
            {
                (message: "VERSION", encoding: Encoding.UTF8),
                (message: "VERSION_2", encoding: Encoding.UTF8),
            };
        }

        private static List<(string, Encoding)> CreateV2Sends(NetworkCredential cred, string configurationName)
        {
            var sends = CreateVersionNegotiationClientSends();
            var password = cred.Password;
            var emptyPassword = string.IsNullOrEmpty(password);

            sends.AddRange(new List<(string message, Encoding encoding)>
            {
                (message: cred.Domain, encoding: Encoding.Unicode),
                (message: cred.UserName, encoding: Encoding.Unicode)
            });

            if (!emptyPassword)
            {
                sends.AddRange(new List<(string message, Encoding encoding)>
                {
                    (message: "NONEMPTYPW", encoding: Encoding.UTF8),
                    (message: cred.Password, encoding: Encoding.Unicode)
                });
            }
            else
            {
                sends.Add((message: "EMPTYPW", encoding: Encoding.UTF8)); // Empty password and we don't expect a response
            }

            if (!string.IsNullOrEmpty(configurationName))
            {
                sends.Add((message: "NONEMPTYCF", encoding: Encoding.UTF8));
                sends.Add((message: configurationName, encoding: Encoding.Unicode)); // Configuration string and we don't expect a response
            }
            else
            {
                sends.Add((message: "EMPTYCF", encoding: Encoding.UTF8)); // Configuration string and we don't expect a response
            }

            sends.Add((message: "PASS", encoding: Encoding.ASCII)); // Response to TOKEN

            return sends;
        }

        private static List<(string, Encoding)> CreateV2Responses(string version = "VERSION_2", bool emptyConfig = false, string token = "FakeToken0+/=", bool emptyPassword = false)
        {
            var responses = new List<(string message, Encoding encoding)>
            {
                (message: version, encoding: Encoding.ASCII), // Response to VERSION
                (message: "PASS", encoding: Encoding.ASCII), // Response to VERSION_2
                (message: "PASS", encoding: Encoding.ASCII), // Response to domain
                (message: "PASS", encoding: Encoding.ASCII), // Response to username
            };

            if (!emptyPassword)
            {
                responses.Add((message: "PASS", encoding: Encoding.ASCII));  // Response to non-empty password
            }

            responses.Add((message: "CONF", encoding: Encoding.ASCII)); // Response to configuration

            if (!emptyConfig)
            {
                responses.Add((message: "PASS", encoding: Encoding.ASCII));  // Response to non-empty configuration
            }
            responses.Add((message: "TOKEN " + token, encoding: Encoding.ASCII)); // Response to with a token than uses each class of character in base 64 encoding

            return responses;
        }

        // Helper method to create test data
        private static (List<(string, Encoding)> expectedClientSends, List<(string, Encoding)> serverResponses)
                CreateHandshakeTestDataV2(NetworkCredential cred, string version, string configurationName, string token)
        {
            bool emptyConfig = string.IsNullOrEmpty(configurationName);
            bool emptyPassword = string.IsNullOrEmpty(cred.Password);
            return (CreateV2Sends(cred, configurationName), CreateV2Responses(version, emptyConfig, token, emptyPassword));
        }

        // Helper method to create test data
        private static (List<(string, Encoding)> expectedClientSends, List<(string, Encoding)> serverResponses) CreateHandshakeTestDataForFallback(NetworkCredential cred)
        {
            var expectedClientSends = new List<(string message, Encoding encoding)>
            {
                (message: "VERSION", encoding: Encoding.UTF8),
                (message: @"?<PSDirectVMLegacy>", encoding: Encoding.Unicode),
                (message: "EMPTYPW", encoding: Encoding.UTF8), // Response to domain
                (message: "FAIL", encoding: Encoding.UTF8), // Response to domain
            };

            List<(string message, Encoding encoding)> serverResponses = new List<(string message, Encoding encoding)>
            {
                (message: "PASS", encoding: Encoding.ASCII), // Response to VERSION but v1 server expects domain so it says "PASS"
                (message: "PASS", encoding: Encoding.ASCII), // Response to username
                (message: "FAIL", encoding: Encoding.ASCII) // Response to EMPTYPW
            };

            return (expectedClientSends, serverResponses);
        }

        // Helper to create a password with at least one non-ASCII Unicode character
        public static string CreateRandomUnicodePassword(string prefix)
        {
            var rand = new Random();
            var asciiPart = new char[6 + prefix.Length];
            // Copy prefix into asciiPart
            Array.Copy(prefix.ToCharArray(), 0, asciiPart, 0, prefix.Length);
            for (int i = prefix.Length; i < asciiPart.Length; i++)
            {
                asciiPart[i] = (char)rand.Next(33, 127); // ASCII printable
            }
            // Add a random Unicode character outside ASCII range (e.g., U+0100 to U+017F)
            char unicodeChar = (char)rand.Next(0x0100, 0x017F);
            // Insert the unicode character at a random position
            int insertPos = rand.Next(0, asciiPart.Length + 1);
            var passwordChars = new List<char>(asciiPart);
            passwordChars.Insert(insertPos, unicodeChar);
            return new string(passwordChars.ToArray());
        }

        public static NetworkCredential CreateTestCredential()
        {
            return new NetworkCredential(CreateRandomUnicodePassword("username"), CreateRandomUnicodePassword("password"), CreateRandomUnicodePassword("domain"));
        }

        [SkippableFact]
        public async Task PerformCredentialAndConfigurationHandshake_V1_Pass()
        {
            // Arrange
            int port = 50000 + (int)(DateTime.Now.Ticks % 10000);
            var cred = CreateTestCredential();
            string configurationName = CreateRandomUnicodePassword("config");

            var (expectedClientSends, serverResponses) = CreateHandshakeTestData(cred);
            expectedClientSends.Add(("PASS", Encoding.ASCII));
            serverResponses.Add(("PASS", Encoding.ASCII));

            using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
            var serverTask = Task.Run(() => StartHandshakeServer("Broker", port, expectedClientSends, serverResponses, verifyConnectionClosed: false, cts.Token), cts.Token);

            using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                ConnectWithRetry(client, IPAddress.Loopback, port, _output);
                var exchangeResult = System.Management.Automation.Remoting.RemoteSessionHyperVSocketClient.ExchangeCredentialsAndConfiguration(cred, configurationName, client, true);
                var result = exchangeResult.success;
                _output.WriteLine($"Exchange result: {result}, Token: {exchangeResult.authenticationToken}");
                System.Threading.Thread.Sleep(100); // Allow time for server to process
                Assert.True(result, $"Expected Exchange to pass");
            }

            await serverTask;
        }

        [SkippableTheory]
        [InlineData("VERSION_2", "configurationname1", "FakeTokenaaaaaaaaaAAAAAAAAAAAAAAAAAAAAAA0FakeTokenaaaaaaaaaAAAAAAAAAAAAAAAAAAAAAA0+/==")] // a fake base64 token about 512 bits long (double the size when this was spec'ed)
        [InlineData("VERSION_10", null, "FakeTokenaaaaaaaaaAAAAAAAAAAAAAAAAAAAAAA0+/=")] // a fake base64 token about 256 bits Long (the size when this was spec'ed)
        public async Task PerformCredentialAndConfigurationHandshake_V2_Pass(string versionResponse, string configurationName, string token)
        {
            // Arrange
            int port = 50000 + (int)(DateTime.Now.Ticks % 10000);
            var cred = CreateTestCredential();

            var (expectedClientSends, serverResponses) = CreateHandshakeTestDataV2(cred, versionResponse, configurationName, token);

            using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
            var serverTask = Task.Run(() => StartHandshakeServer("Broker", port, expectedClientSends, serverResponses, verifyConnectionClosed: true, cts.Token), cts.Token);

            using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                client.Connect(IPAddress.Loopback, port);
                var exchangeResult = System.Management.Automation.Remoting.RemoteSessionHyperVSocketClient.ExchangeCredentialsAndConfiguration(cred, configurationName, client, false);
                var result = exchangeResult.success;
                System.Threading.Thread.Sleep(100); // Allow time for server to process
                Assert.True(result, $"Expected Exchange to pass for version response '{versionResponse}'");
                Assert.Equal(token, exchangeResult.authenticationToken);
            }

            await serverTask;
        }

        [SkippableFact]
        public async Task PerformCredentialAndConfigurationHandshake_V1_Fallback()
        {
            // Arrange
            int port = 50000 + (int)(DateTime.Now.Ticks % 10000);
            var cred = CreateTestCredential();
            string configurationName = CreateRandomUnicodePassword("config");

            var (expectedClientSends, serverResponses) = CreateHandshakeTestDataForFallback(cred);

            using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
            var serverTask = Task.Run(() => StartHandshakeServer("Broker", port, expectedClientSends, serverResponses, verifyConnectionClosed: false, cts.Token), cts.Token);

            bool isFallback = false;
            using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                _output.WriteLine("Starting handshake with V2 protocol.");
                client.Connect(IPAddress.Loopback, port);
                var exchangeResult = System.Management.Automation.Remoting.RemoteSessionHyperVSocketClient.ExchangeCredentialsAndConfiguration(cred, configurationName, client, false);
                isFallback = !exchangeResult.success;

                System.Threading.Thread.Sleep(100); // Allow time for server to process
                _output.WriteLine("Handshake indicated fallback to V1.");
                Assert.True(isFallback, "Expected fallback to V1.");
            }
            _output.WriteLine("Handshake completed successfully with fallback to V1.");

            await serverTask;
        }

        [SkippableFact]
        public async Task PerformCredentialAndConfigurationHandshake_V2_InvalidResponse()
        {
            // Arrange
            int port = 51000 + (int)(DateTime.Now.Ticks % 10000);
            var cred = CreateTestCredential();

            var (expectedClientSends, serverResponses) = CreateHandshakeTestData(cred);
            //expectedClientSends.Add("FAI1");
            serverResponses.Add(("FAI1", Encoding.ASCII));

            using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

            //cts.Token.Register(() => throw new OperationCanceledException("Test timed out."));

            var serverTask = Task.Run(() => StartHandshakeServer("Broker", port, expectedClientSends, serverResponses, verifyConnectionClosed: false, cts.Token), cts.Token);

            using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                _output.WriteLine("connecting on port " + port);
                ConnectWithRetry(client, IPAddress.Loopback, port, _output);

                var ex = Record.Exception(() => System.Management.Automation.Remoting.RemoteSessionHyperVSocketClient.ExchangeCredentialsAndConfiguration(cred, "config", client, true));

                try
                {
                    await serverTask;
                }
                catch (AggregateException exAgg)
                {
                    Assert.Null(exAgg.Flatten().InnerExceptions[1].Message);
                }
                cts.Token.ThrowIfCancellationRequested();

                Assert.NotNull(ex);
                Assert.NotNull(ex.Message);
                Assert.Contains("Hyper-V Broker sent an invalid Credential response", ex.Message);
            }
        }

        [SkippableFact]
        public async Task PerformCredentialAndConfigurationHandshake_V1_Fail()
        {
            // Arrange
            int port = 51000 + (int)(DateTime.Now.Ticks % 10000);
            var cred = CreateTestCredential();

            var (expectedClientSends, serverResponses) = CreateHandshakeTestData(cred);
            expectedClientSends.Add(("FAIL", Encoding.ASCII));
            serverResponses.Add(("FAIL", Encoding.ASCII));

            using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15));

            // This scenario does not close the connection in a timely manner, so we set verifyConnectionClosed to false
            var serverTask = Task.Run(() => StartHandshakeServer("Broker", port, expectedClientSends, serverResponses, verifyConnectionClosed: false, cts.Token), cts.Token);

            using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                client.Connect(IPAddress.Loopback, port);

                var ex = Record.Exception(() => System.Management.Automation.Remoting.RemoteSessionHyperVSocketClient.ExchangeCredentialsAndConfiguration(cred, "config", client, true));

                try
                {
                    await serverTask;
                }
                catch (AggregateException exAgg)
                {
                    Assert.Null(exAgg.Flatten().InnerExceptions[1].Message);
                }

                cts.Token.ThrowIfCancellationRequested();

                Assert.NotNull(ex);
                Assert.NotNull(ex.Message);
                Assert.Contains("The credential is invalid.", ex.Message);
            }
        }

        [SkippableTheory]
        [InlineData("VERSION_2", "FakeTokenaaaaaaaaaAAAAAAAAAAAAAAAAAAAAAA0FakeTokenaaaaaaaaaAAAAAAAAAAAAAAAAAAAAAA0+/==")] // a fake base64 token about 512 bits long (double the size when this was spec'ed)
        [InlineData("VERSION_10", "FakeTokenaaaaaaaaaAAAAAAAAAAAAAAAAAAAAAA0+/=")] // a fake base64 token about 256 bits Long (the size when this was spec'ed)
        public async Task PerformTransportVersionAndTokenExchange_Pass(string version, string token)
        {
            // Arrange
            int port = 50000 + (int)(DateTime.Now.Ticks % 10000);
            var cred = CreateTestCredential();

            var expectedClientSends = CreateVersionNegotiationClientSends();
            expectedClientSends.Add((message: "TOKEN " + token, encoding: Encoding.ASCII));

            var serverResponses = new List<(string message, Encoding encoding)>{
                (message: version, encoding: Encoding.ASCII), // Response to VERSION
                (message: "PASS", encoding: Encoding.ASCII), // Response to VERSION_2
                (message: "PASS", encoding: Encoding.ASCII) // Response to token
            };

            using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
            var serverTask = Task.Run(() => StartHandshakeServer("Server", port, expectedClientSends, serverResponses, verifyConnectionClosed: true, cts.Token), cts.Token);

            using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                ConnectWithRetry(client, IPAddress.Loopback, port, _output);
                System.Management.Automation.Remoting.RemoteSessionHyperVSocketClient.PerformTransportVersionAndTokenExchange(client, token);
                System.Threading.Thread.Sleep(100); // Allow time for server to process
            }

            await serverTask;
        }

        [SkippableTheory]
        [InlineData(1, true)]
        [InlineData(2, true)]
        [InlineData(0, false)]
        [InlineData(null, false)]
        [System.Runtime.Versioning.SupportedOSPlatform("windows")]
        public void IsRequirePsDirectAuthenticationEnabled(int? regValue, bool expected)
        {
            const string testKeyPath = @"SOFTWARE\Microsoft\TestRequirePsDirectAuthentication";
            const string valueName = "RequirePsDirectAuthentication";
            if (!System.Management.Automation.Platform.IsWindows)
            {
                throw new SkipException("RemoteHyperVTests are only supported on Windows.");
            }

            // Clean up any previous test key
            var regHive = Microsoft.Win32.RegistryHive.CurrentUser;
            var baseKey = Microsoft.Win32.RegistryKey.OpenBaseKey(regHive, Microsoft.Win32.RegistryView.Registry64);
            baseKey.DeleteSubKeyTree(testKeyPath, false);

            bool? result = null;

            // Create the test key
            using (var key = baseKey.CreateSubKey(testKeyPath))
            {
                if (regValue.HasValue)
                {
                    key.SetValue(valueName, regValue.Value, Microsoft.Win32.RegistryValueKind.DWord);
                }
                else
                {
                    // Ensure the value does not exist
                    key.DeleteValue(valueName, false);
                }

                result = System.Management.Automation.Remoting.RemoteSessionHyperVSocketClient.IsRequirePsDirectAuthenticationEnabled(testKeyPath, regHive);
            }

            Assert.True(result.HasValue, "IsRequirePsDirectAuthenticationEnabled should return a value.");
            Assert.True(expected == result.Value,
                $"Expected IsRequirePsDirectAuthenticationEnabled to return {expected} when registry value is {(regValue.HasValue ? regValue.ToString() : "not set")}.");

            return;
        }

        [SkippableTheory]
        [InlineData("testToken", "testToken")]
        [InlineData("testToken\0", "testToken")]
        public async Task ValidatePassesWhenTokensMatch(string token, string expectedToken)
        {
            int port = 50000 + (int)(DateTime.Now.Ticks % 10000);

            var expectedClientSends = new List<(string message, Encoding encoding)>{
                (message: "VERSION", encoding: Encoding.ASCII), // Response to VERSION
                (message: "VERSION_2", encoding: Encoding.ASCII), // Response to VERSION_2
                (message: $"TOKEN {token}", encoding: Encoding.ASCII)
            };

            var serverResponses = new List<(string message, Encoding encoding)>{
                (message: "VERSION_2", encoding: Encoding.ASCII), // Response to VERSION_2
                (message: "PASS", encoding: Encoding.ASCII), // Response to VERSION_2
                (message: "PASS", encoding: Encoding.ASCII) // Response to token
            };

            using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
            var serverTask = Task.Run(() => StartHandshakeServer("Client", port, serverResponses, expectedClientSends, verifyConnectionClosed: true, cts.Token, sendFirst: true), cts.Token);

            using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                ConnectWithRetry(client, IPAddress.Loopback, port, _output);
                System.Management.Automation.Remoting.RemoteSessionHyperVSocketServer.ValidateToken(client, expectedToken, DateTimeOffset.UtcNow, 1);
                System.Threading.Thread.Sleep(100); // Allow time for server to process
            }

            await serverTask;
        }

        [SkippableTheory]
        [InlineData(5500, "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.", "SocketException")] // test the socket timeout
        [InlineData(3200, "canceled", "System.OperationCanceledException")] // test the cancellation token
        [InlineData(10, "", "")]
        public async Task ValidateTokenTimeoutFails(int timeoutMs, string expectedMessage, string expectedExceptionType = "SocketException")
        {
            string token = "testToken";
            string expectedToken = token;
            int port = 50000 + (int)(DateTime.Now.Ticks % 10000);

            var expectedClientSends = new List<(string message, Encoding encoding, int delayMs)>{
                (message: "VERSION", encoding: Encoding.ASCII, delayMs: timeoutMs), // Response to VERSION
                (message: "VERSION_2", encoding: Encoding.ASCII, delayMs: timeoutMs), // Response to VERSION_2
                (message: $"TOKEN {token}", encoding: Encoding.ASCII, delayMs: 1)
            };

            var serverResponses = new List<(string message, Encoding encoding)>{
                (message: "VERSION_2", encoding: Encoding.ASCII), // Response to VERSION_2
                (message: "PASS", encoding: Encoding.ASCII), // Response to VERSION_2
                (message: "PASS", encoding: Encoding.ASCII) // Response to token
            };

            using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
            var serverTask = Task.Run(() => StartHandshakeServer("Client", port, serverResponses, expectedClientSends, verifyConnectionClosed: true, cts.Token, sendFirst: true), cts.Token);

            using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                ConnectWithRetry(client, IPAddress.Loopback, port, _output);
                if (expectedMessage.Length > 0)
                {
                    var exception = Record.Exception(
                        () => System.Management.Automation.Remoting.RemoteSessionHyperVSocketServer.ValidateToken(client, expectedToken, DateTimeOffset.UtcNow, 5)); // set the timeout to  5 seconds or 5000 ms
                    Assert.NotNull(exception);
                    string exceptionType = exception.GetType().FullName;
                    _output.WriteLine($"Caught exception of type {exceptionType} with message: {exception.Message}");
                    Assert.Contains(expectedExceptionType, exceptionType, StringComparison.OrdinalIgnoreCase);
                    Assert.Contains(expectedMessage, exception.Message, StringComparison.OrdinalIgnoreCase);
                }
                else
                {
                    System.Management.Automation.Remoting.RemoteSessionHyperVSocketServer.ValidateToken(client, expectedToken, DateTimeOffset.UtcNow, 5);
                }
                System.Threading.Thread.Sleep(100); // Allow time for server to process
            }

            if (expectedMessage.Length == 0)
            {
                await serverTask;
            }
        }

        [SkippableFact]
        public async Task ValidateTokenTimeoutDoesAffectSession()
        {
            string token = "testToken";
            string expectedToken = token;
            int port = 50000 + (int)(DateTime.Now.Ticks % 10000);

            var expectedClientSends = new List<(string message, Encoding encoding, int delayMs)>{
                (message: "VERSION", encoding: Encoding.ASCII, delayMs: 1), // Response to VERSION
                (message: "VERSION_2", encoding: Encoding.ASCII, delayMs: 1), // Response to VERSION_2
                (message: $"TOKEN {token}", encoding: Encoding.ASCII, delayMs: 1),
                (message: string.Empty, encoding: Encoding.ASCII, delayMs: 99), // Send some data after the handshake
                (message: string.Empty, encoding: Encoding.ASCII, delayMs: 100), // Send some data after the handshake
                (message: string.Empty, encoding: Encoding.ASCII, delayMs: 101),  // Send some data after the handshake
                (message: string.Empty, encoding: Encoding.ASCII, delayMs: 102),  // Send some data after the handshake
                (message: string.Empty, encoding: Encoding.ASCII, delayMs: 103)  // Send some data after the handshake
            };

            var serverResponses = new List<(string message, Encoding encoding)>{
                (message: "VERSION_2", encoding: Encoding.ASCII), // Response to VERSION_2
                (message: "PASS", encoding: Encoding.ASCII), // Response to VERSION_2
                (message: "PASS", encoding: Encoding.ASCII), // Response to token
                (message: "PSRP-Message0", encoding: Encoding.ASCII), // Indicate server is ready to receive data
                (message: "PSRP-Message1", encoding: Encoding.ASCII), // Indicate server is ready to receive data
                (message: "PSRP-Message2", encoding: Encoding.ASCII),  // Indicate server is ready to receive data
                (message: "PSRP-Message3", encoding: Encoding.ASCII),  // Indicate server is ready to receive data
                (message: "PSRP-Message4", encoding: Encoding.ASCII)  //

            };

            using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(2));
            var serverTask = Task.Run(() => StartHandshakeServer("Client", port, serverResponses, expectedClientSends, verifyConnectionClosed: false, cts.Token, sendFirst: true), cts.Token);

            using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                ConnectWithRetry(client, IPAddress.Loopback, port, _output);
                System.Management.Automation.Remoting.RemoteSessionHyperVSocketServer.ValidateToken(client, expectedToken, DateTimeOffset.UtcNow, 5);
                for (int i = 0; i < 5; i++)
                {
                    System.Threading.Thread.Sleep(1500);
                    client.Send(Encoding.ASCII.GetBytes($"PSRP-Message{i}")); // Send some data after the handshake
                }
            }

            await serverTask;
        }

        [SkippableTheory]
        [InlineData("abc", "xyz")]
        [InlineData("abc", "abcdef")]
        [InlineData("abcdef", "abc")]
        [InlineData("abc\0def", "abc")]
        public async Task ValidateFailsWhenTokensMismatch(string token, string expectedToken)
        {
            int port = 50000 + (int)(DateTime.Now.Ticks % 10000);

            var expectedClientSends = new List<(string message, Encoding encoding)>{
                (message: "VERSION", encoding: Encoding.ASCII), // Initial request
                (message: "VERSION_2", encoding: Encoding.ASCII), // Response to VERSION_2
                (message: $"TOKEN {token}", encoding: Encoding.ASCII)
            };

            var serverResponses = new List<(string message, Encoding encoding)>{
                (message: "VERSION_2", encoding: Encoding.ASCII), // Response to VERSION
                (message: "PASS", encoding: Encoding.ASCII), // Response to VERSION_2
                (message: "FAIL", encoding: Encoding.ASCII) // Response to token
            };

            using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
            var serverTask = Task.Run(() => StartHandshakeServer("Client", port, serverResponses, expectedClientSends, verifyConnectionClosed: true, cts.Token, sendFirst: true), cts.Token);

            using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                ConnectWithRetry(client, IPAddress.Loopback, port, _output);
                DateTimeOffset tokenCreationTime = DateTimeOffset.UtcNow; // Token created 10 minutes ago
                var exception = Assert.Throws<System.Management.Automation.Remoting.PSDirectException>(
                    () => System.Management.Automation.Remoting.RemoteSessionHyperVSocketServer.ValidateToken(client, expectedToken, tokenCreationTime, 5));
                System.Threading.Thread.Sleep(100); // Allow time for server to process
                Assert.Contains("The credential is invalid.", exception.Message);
            }

            await serverTask;
        }
    }
}