forked from dotnet/yarp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSocketTests.cs
More file actions
800 lines (680 loc) · 31.6 KB
/
WebSocketTests.cs
File metadata and controls
800 lines (680 loc) · 31.6 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using Xunit;
using Xunit.Abstractions;
using Yarp.ReverseProxy.Common;
using Yarp.ReverseProxy.Forwarder;
using Yarp.ReverseProxy.Transforms;
namespace Yarp.ReverseProxy;
public class WebSocketTests
{
private readonly ITestOutputHelper _output;
public WebSocketTests(ITestOutputHelper output)
{
_output = output;
}
public static IEnumerable<object[]> WebSocketVersionNegotiation_TestData()
{
foreach (Version incomingVersion in new[] { HttpVersion.Version11, HttpVersion.Version20 })
{
foreach (HttpVersionPolicy versionPolicy in Enum.GetValues<HttpVersionPolicy>())
{
foreach (Version destinationVersion in new[] { HttpVersion.Version11, HttpVersion.Version20, HttpVersion.Version30 })
{
foreach (HttpProtocols destinationProtocols in new[] { HttpProtocols.Http1, HttpProtocols.Http2, HttpProtocols.Http1AndHttp2 })
{
foreach (bool useHttpsOnDestination in new[] { true, false })
{
(int version, bool canDowngrade) = (destinationVersion.Major, versionPolicy, useHttpsOnDestination) switch
{
(1, HttpVersionPolicy.RequestVersionOrHigher, true) => (2, true),
(1, _, _) => (1, false),
(2, HttpVersionPolicy.RequestVersionOrLower, true) => (2, true),
(2, HttpVersionPolicy.RequestVersionOrLower, false) => (1, false),
(2, _, _) => (2, false),
(3, HttpVersionPolicy.RequestVersionOrLower, true) => (2, true),
(3, HttpVersionPolicy.RequestVersionOrLower, false) => (1, false),
(3, _, _) => (-1, false), // RequestCreation error
_ => throw new Exception()
};
ForwarderError? expectedProxyError = version == -1 ? ForwarderError.RequestCreation : null;
bool e2eWillFail = expectedProxyError.HasValue;
if (version == 2 && destinationProtocols == HttpProtocols.Http1)
{
// ALPN rejects HTTP/2.
if (canDowngrade)
{
Debug.Assert(useHttpsOnDestination);
version = 1;
}
else
{
e2eWillFail = true;
expectedProxyError = ForwarderError.Request;
}
}
if (version == 1 && destinationProtocols == HttpProtocols.Http2)
{
// ALPN rejects HTTP/1.1, or the server sends back an error response when not using TLS.
e2eWillFail = true;
// An error response is just a bad status code, not a failed request from the proxy's perspective.
if (useHttpsOnDestination)
{
expectedProxyError = ForwarderError.Request;
}
}
if (version == 2 && destinationProtocols == HttpProtocols.Http1AndHttp2 && !useHttpsOnDestination)
{
// No ALPN, Kestrel doesn't know whether to use HTTP/1.1 or HTTP/2, defaulting to HTTP/1.1.
// YARP will see an 'HTTP_1_1_REQUIRED' error and return a 502.
Debug.Assert(!canDowngrade);
e2eWillFail = true;
expectedProxyError = ForwarderError.Request;
}
string expectedVersion = version == 1 ? "HTTP/1.1" : "HTTP/2";
yield return new object[] { incomingVersion, versionPolicy, destinationVersion, destinationProtocols, useHttpsOnDestination, expectedVersion, expectedProxyError, e2eWillFail };
}
}
}
}
}
}
[Theory]
[MemberData(nameof(WebSocketVersionNegotiation_TestData))]
public async Task WebSocketVersionNegotiation(Version incomingVersion, HttpVersionPolicy versionPolicy, Version requestedDestinationVersion, HttpProtocols destinationProtocols, bool useHttpsOnDestination,
string expectedVersion, ForwarderError? expectedProxyError, bool e2eWillFail)
{
using var cts = CreateTimer();
var test = CreateTestEnvironment();
test.ProxyProtocol = incomingVersion.Major == 1 ? HttpProtocols.Http1 : HttpProtocols.Http2;
test.DestinationProtocol = destinationProtocols;
test.DestinationHttpVersion = requestedDestinationVersion;
test.DestinationHttpVersionPolicy = versionPolicy;
test.UseHttpsOnDestination = useHttpsOnDestination;
int proxyRequests = 0;
ForwarderError? error = null;
test.ConfigureProxyApp = builder =>
{
builder.Use(async (context, next) =>
{
proxyRequests++;
await next(context);
error = context.Features.Get<IForwarderErrorFeature>()?.Error;
});
};
await test.Invoke(async uri =>
{
using var client = new ClientWebSocket();
client.Options.HttpVersion = incomingVersion;
client.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact;
if (e2eWillFail)
{
var ex = await Assert.ThrowsAsync<WebSocketException>(() => SendWebSocketRequestAsync(client, uri, expectedVersion, cts.Token));
Assert.IsNotType<TaskCanceledException>(ex.InnerException);
}
else
{
await SendWebSocketRequestAsync(client, uri, expectedVersion, cts.Token);
}
}, cts.Token);
Assert.Equal(1, proxyRequests);
Assert.Equal(expectedProxyError, error);
}
[Theory]
[InlineData(WebSocketMessageType.Binary)]
[InlineData(WebSocketMessageType.Text)]
public async Task WebSocketMessageTypes(WebSocketMessageType messageType)
{
using var cts = CreateTimer();
var test = CreateTestEnvironment();
await test.Invoke(async uri =>
{
using var client = new ClientWebSocket();
var webSocketsTarget = uri.Replace("https://", "wss://").Replace("http://", "ws://");
var targetUri = new Uri(new Uri(webSocketsTarget, UriKind.Absolute), "websockets");
await client.ConnectAsync(targetUri, cts.Token);
var buffer = new byte[1024];
var textToSend = $"Hello World!";
var numBytes = Encoding.UTF8.GetBytes(textToSend, buffer.AsSpan());
await client.SendAsync(new ArraySegment<byte>(buffer, 0, numBytes),
messageType,
endOfMessage: true,
cts.Token);
var message = await client.ReceiveAsync(buffer, cts.Token);
Assert.Equal(messageType, message.MessageType);
Assert.True(message.EndOfMessage);
var text = Encoding.UTF8.GetString(buffer.AsSpan(0, message.Count));
Assert.Equal(textToSend, text);
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Bye", cts.Token);
Assert.Equal(WebSocketCloseStatus.NormalClosure, client.CloseStatus);
Assert.Equal("Bye", client.CloseStatusDescription);
}, cts.Token);
}
[Fact]
public async Task RawUpgradeTest()
{
using var cts = CreateTimer();
var test = CreateTestEnvironment();
await test.Invoke(async uri =>
{
using var client = WebSocketTests.CreateInvoker();
var targetUri = new Uri(new Uri(uri, UriKind.Absolute), "rawupgrade");
using var request = new HttpRequestMessage(HttpMethod.Get, targetUri);
// TODO: https://github.com/dotnet/yarp/issues/255 Until this is fixed the "Upgrade: WebSocket" header is required.
request.Headers.TryAddWithoutValidation("Upgrade", "WebSocket");
request.Headers.TryAddWithoutValidation("Connection", "upgrade");
request.Version = new Version(1, 1);
var response = await client.SendAsync(request, cts.Token);
Assert.Equal(HttpStatusCode.SwitchingProtocols, response.StatusCode);
using var rawStream = await response.Content.ReadAsStreamAsync(cts.Token);
var buffer = new byte[5];
for (var i = 0; i <= 255; i++)
{
buffer[0] = (byte)i;
await rawStream.WriteAsync(buffer, 0, buffer.Length, cts.Token);
var read = await rawStream.ReadAsync(buffer, cts.Token);
Assert.Equal(buffer.Length, read);
Assert.Equal(i, buffer[0]);
}
await rawStream.WriteAsync(Encoding.UTF8.GetBytes("close"));
while (await rawStream.ReadAsync(buffer, cts.Token) != 0) { }
rawStream.Dispose();
}, cts.Token);
}
[Fact]
// https://github.com/dotnet/yarp/issues/255 IIS claims all requests are upgradeable.
public async Task FalseUpgradeTest()
{
using var cts = CreateTimer();
var test = CreateTestEnvironment(forceUpgradable: true);
await test.Invoke(async uri =>
{
using var client = WebSocketTests.CreateInvoker();
var targetUri = new Uri(new Uri(uri, UriKind.Absolute), "post");
using var request = new HttpRequestMessage(HttpMethod.Post, targetUri);
request.Content = new StringContent("Hello World");
request.Version = new Version(1, 1);
var response = await client.SendAsync(request, cts.Token);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("Hello World", await response.Content.ReadAsStringAsync(cts.Token));
}, cts.Token);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task WebSocket11_To_11(bool useHttps)
{
using var cts = CreateTimer();
var test = CreateTestEnvironment();
test.ProxyProtocol = HttpProtocols.Http1;
test.DestinationProtocol = HttpProtocols.Http1;
test.DestinationHttpVersion = HttpVersion.Version11;
test.UseHttpsOnProxy = useHttps;
test.UseHttpsOnDestination = useHttps;
await test.Invoke(async uri =>
{
using var client = new ClientWebSocket();
await SendWebSocketRequestAsync(client, uri, "HTTP/1.1", cts.Token);
}, cts.Token);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task WebSocket20_To_20(bool useHttps)
{
using var cts = CreateTimer();
var test = CreateTestEnvironment();
test.ProxyProtocol = HttpProtocols.Http2;
test.DestinationProtocol = HttpProtocols.Http2;
test.DestinationHttpVersionPolicy = HttpVersionPolicy.RequestVersionExact;
test.UseHttpsOnProxy = useHttps;
test.UseHttpsOnDestination = useHttps;
await test.Invoke(async uri =>
{
using var client = new ClientWebSocket();
client.Options.HttpVersion = HttpVersion.Version20;
client.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact;
await SendWebSocketRequestAsync(client, uri, "HTTP/2", cts.Token);
}, cts.Token);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task WebSocket20_To_11(bool useHttps)
{
using var cts = CreateTimer();
var test = CreateTestEnvironment();
test.ProxyProtocol = HttpProtocols.Http2;
test.DestinationProtocol = HttpProtocols.Http1;
test.DestinationHttpVersion = HttpVersion.Version11;
test.UseHttpsOnProxy = useHttps;
test.UseHttpsOnDestination = useHttps;
await test.Invoke(async uri =>
{
using var client = new ClientWebSocket();
client.Options.HttpVersion = HttpVersion.Version20;
client.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact;
await SendWebSocketRequestAsync(client, uri, "HTTP/1.1", cts.Token);
}, cts.Token);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task WebSocket11_To_20(bool useHttps)
{
using var cts = CreateTimer();
var test = CreateTestEnvironment();
test.ProxyProtocol = HttpProtocols.Http1;
test.DestinationProtocol = HttpProtocols.Http2;
test.DestinationHttpVersionPolicy = HttpVersionPolicy.RequestVersionExact;
test.UseHttpsOnProxy = useHttps;
test.UseHttpsOnDestination = useHttps;
await test.Invoke(async uri =>
{
using var client = new ClientWebSocket();
client.Options.HttpVersion = HttpVersion.Version11;
client.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact;
await SendWebSocketRequestAsync(client, uri, "HTTP/2", cts.Token);
}, cts.Token);
}
[Fact]
public async Task WebSocketFallbackFromH2()
{
using var cts = CreateTimer();
var test = CreateTestEnvironment();
test.ProxyProtocol = HttpProtocols.Http1;
// The destination doesn't support HTTP/2, as determined by ALPN
test.DestinationProtocol = HttpProtocols.Http1;
test.DestinationHttpVersion = HttpVersion.Version20;
test.UseHttpsOnDestination = true;
await test.Invoke(async uri =>
{
using var client = new ClientWebSocket();
await SendWebSocketRequestAsync(client, uri, "HTTP/1.1", cts.Token);
}, cts.Token);
}
[Fact]
public async Task WebSocketFallbackFromH2_FailureInSecondRequestTransform_TreatedAsRequestCreationFailure()
{
using var cts = CreateTimer();
ForwarderError? error = null;
var test = new TestEnvironment()
{
TestOutput = _output,
ProxyProtocol = HttpProtocols.Http1,
// The destination doesn't support HTTP/2, as determined by ALPN
DestinationProtocol = HttpProtocols.Http1,
DestinationHttpVersion = HttpVersion.Version20,
UseHttpsOnDestination = true,
ConfigureProxy = builder =>
{
builder.AddTransforms(transforms =>
{
transforms.AddRequestTransform(context =>
{
if (context.ProxyRequest.Version.Major == 1)
{
// This is the second (downgrade) request.
throw new Exception("Foo");
}
return default;
});
});
},
ConfigureProxyApp = builder =>
{
builder.Use(async (context, next) =>
{
await next(context);
error = context.Features.Get<IForwarderErrorFeature>()?.Error;
});
},
};
await test.Invoke(async uri =>
{
try
{
using var client = new ClientWebSocket();
await SendWebSocketRequestAsync(client, uri, "HTTP/1.1", cts.Token);
}
catch { }
}, cts.Token);
Assert.Equal(ForwarderError.RequestCreation, error);
}
// [Fact]
[Fact(Skip = "Manual test only, the CI doesn't always have the IIS Express test cert installed.")]
public async Task WebSocketFallbackFromH2WS()
{
if (!OperatingSystem.IsWindows())
{
// This test relies on Windows/HttpSys
return;
}
using var cts = CreateTimer();
var test = CreateTestEnvironment();
test.ProxyProtocol = HttpProtocols.Http1;
// The destination supports HTTP/2, but not H2WS
test.UseHttpSysOnDestination = true;
test.UseHttpsOnDestination = true;
await test.Invoke(async uri =>
{
using var client = new ClientWebSocket();
await SendWebSocketRequestAsync(client, uri, "HTTP/1.1", cts.Token);
}, cts.Token);
}
[Theory]
[InlineData(HttpVersionPolicy.RequestVersionExact, true)]
[InlineData(HttpVersionPolicy.RequestVersionExact, false)]
[InlineData(HttpVersionPolicy.RequestVersionOrHigher, true)]
public async Task WebSocketCantFallbackFromH2(HttpVersionPolicy policy, bool useHttps)
{
using var cts = CreateTimer();
var test = CreateTestEnvironment();
test.ProxyProtocol = HttpProtocols.Http1;
test.DestinationProtocol = HttpProtocols.Http1;
test.DestinationHttpVersion = HttpVersion.Version20;
test.DestinationHttpVersionPolicy = policy;
test.UseHttpsOnDestination = useHttps;
await test.Invoke(async uri =>
{
using var client = new ClientWebSocket();
var webSocketsTarget = uri.Replace("https://", "wss://").Replace("http://", "ws://");
var targetUri = new Uri(new Uri(webSocketsTarget, UriKind.Absolute), "websockets");
using var invoker = CreateInvoker();
var wse = await Assert.ThrowsAsync<WebSocketException>(() => client.ConnectAsync(targetUri, invoker, cts.Token));
Assert.Equal("The server returned status code '502' when status code '101' was expected.", wse.Message);
}, cts.Token);
}
[Theory]
[InlineData(HttpProtocols.Http1)] // Checked by destination
[InlineData(HttpProtocols.Http2)] // Checked by proxy
public async Task InvalidKeyHeader_400(HttpProtocols destinationProtocol)
{
using var cts = CreateTimer();
var test = CreateTestEnvironment();
test.ProxyProtocol = HttpProtocols.Http1;
test.DestinationProtocol = destinationProtocol;
test.DestinationHttpVersionPolicy = HttpVersionPolicy.RequestVersionExact;
test.DestinationHttpVersion = destinationProtocol == HttpProtocols.Http1 ? HttpVersion.Version11 : HttpVersion.Version20;
test.ConfigureProxyApp = builder =>
{
builder.Use(async (context, next) =>
{
context.Request.Headers[HeaderNames.SecWebSocketKey] = "ThisIsAnIncorrectKeyHeaderLongerThan24Bytes";
var logs = TestLogger.Collect();
await next(context);
if (destinationProtocol == HttpProtocols.Http1)
{
Assert.DoesNotContain(logs, log => log.EventId == EventIds.InvalidSecWebSocketKeyHeader);
}
else
{
Assert.Contains(logs, log => log.EventId == EventIds.InvalidSecWebSocketKeyHeader);
}
});
};
await test.Invoke(async uri =>
{
using var client = new ClientWebSocket();
client.Options.CollectHttpResponseDetails = true;
var webSocketsTarget = uri.Replace("https://", "wss://").Replace("http://", "ws://");
var targetUri = new Uri(new Uri(webSocketsTarget, UriKind.Absolute), "websockets");
client.Options.RemoteCertificateValidationCallback = (_, _, _, _) => true;
var wse = await Assert.ThrowsAsync<WebSocketException>(() => client.ConnectAsync(targetUri, cts.Token));
Assert.Equal("The server returned status code '400' when status code '101' was expected.", wse.Message);
Assert.Equal(HttpStatusCode.BadRequest, client.HttpStatusCode);
// TODO: Assert the version https://github.com/dotnet/runtime/issues/75353
}, cts.Token);
}
[Fact]
public async Task WebSocket20_To_11_WithWellFormedKeyHeader_OriginalKeyIsUsed()
{
using var cts = CreateTimer();
var clientKey = ProtocolHelper.CreateSecWebSocketKey();
var test = CreateTestEnvironment();
test.ProxyProtocol = HttpProtocols.Http2;
test.DestinationProtocol = HttpProtocols.Http1;
var originalDestinationApp = test.ConfigureDestinationApp;
test.ConfigureDestinationApp = app =>
{
app.Use((context, next) =>
{
Assert.True(context.Request.Headers.TryGetValue(HeaderNames.SecWebSocketKey, out var key));
Assert.Equal(clientKey, key);
return next(context);
});
originalDestinationApp(app);
};
await test.Invoke(async uri =>
{
using var client = new ClientWebSocket();
client.Options.HttpVersion = HttpVersion.Version20;
client.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact;
client.Options.SetRequestHeader(HeaderNames.SecWebSocketKey, clientKey);
await SendWebSocketRequestAsync(client, uri, "HTTP/1.1", cts.Token);
}, cts.Token);
}
[Fact]
public async Task WebSocket20_To_11_WithInvalidKeyHeader_RequestRejected()
{
using var cts = CreateTimer();
var test = CreateTestEnvironment();
test.ProxyProtocol = HttpProtocols.Http2;
test.DestinationProtocol = HttpProtocols.Http1;
test.ConfigureProxyApp = builder =>
{
builder.Use(async (context, next) =>
{
var logs = TestLogger.Collect();
await next(context);
Assert.Contains(logs, log => log.EventId == EventIds.InvalidSecWebSocketKeyHeader);
});
};
await test.Invoke(async uri =>
{
var webSocketsTarget = uri.Replace("http://", "ws://");
var targetUri = new Uri(new Uri(webSocketsTarget, UriKind.Absolute), "websockets");
using var client = new ClientWebSocket();
client.Options.HttpVersion = HttpVersion.Version20;
client.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact;
client.Options.CollectHttpResponseDetails = true;
client.Options.SetRequestHeader(HeaderNames.SecWebSocketKey, "Foo");
using var invoker = CreateInvoker();
var wse = await Assert.ThrowsAsync<WebSocketException>(() => client.ConnectAsync(targetUri, invoker, cts.Token));
Assert.Equal("The server returned status code '400' when status code '200' was expected.", wse.Message);
Assert.Equal(HttpStatusCode.BadRequest, client.HttpStatusCode);
}, cts.Token);
}
private async Task SendWebSocketRequestAsync(ClientWebSocket client, string uri, string destinationProtocol, CancellationToken token)
{
var webSocketsTarget = uri.Replace("https://", "wss://").Replace("http://", "ws://");
var targetUri = new Uri(new Uri(webSocketsTarget, UriKind.Absolute), "websocketversion");
using var invoker = CreateInvoker();
await client.ConnectAsync(targetUri, invoker, token);
_output.WriteLine("Client connected.");
var buffer = new byte[1024];
var textToSend = $"Hello World!";
var numBytes = Encoding.UTF8.GetBytes(textToSend, buffer);
await client.SendAsync(buffer.AsMemory(0, numBytes),
WebSocketMessageType.Text,
endOfMessage: true,
token);
_output.WriteLine($"Client sent {numBytes}.");
var message = await client.ReceiveAsync(buffer, token);
_output.WriteLine($"Client received {message.Count}.");
Assert.Equal(WebSocketMessageType.Text, message.MessageType);
Assert.True(message.EndOfMessage);
var text = Encoding.UTF8.GetString(buffer.AsSpan(0, message.Count));
Assert.Equal(destinationProtocol, text);
_output.WriteLine($"Client sending Close.");
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Bye", token);
Assert.Equal(WebSocketCloseStatus.NormalClosure, client.CloseStatus);
Assert.Equal("Bye", client.CloseStatusDescription);
_output.WriteLine($"Client Closed.");
}
private TestEnvironment CreateTestEnvironment(bool forceUpgradable = false)
{
return new TestEnvironment()
{
TestOutput = _output,
ConfigureDestinationServices = destinationServices =>
{
destinationServices.AddRouting();
},
ConfigureDestinationApp = destinationApp =>
{
destinationApp.UseWebSockets();
destinationApp.UseRouting();
destinationApp.UseEndpoints(builder =>
{
builder.Map("/websockets", WebSocket);
builder.Map("/websocketVersion", WebSocketVersion);
builder.Map("/rawupgrade", RawUpgrade);
builder.Map("/post", Post);
});
},
ConfigureProxyApp = proxyApp =>
{
// Mimic the IIS issue https://github.com/dotnet/yarp/issues/255
proxyApp.Use((context, next) =>
{
if (forceUpgradable && !(context.Features.Get<IHttpUpgradeFeature>()?.IsUpgradableRequest == true))
{
context.Features.Set<IHttpUpgradeFeature>(new AlwaysUpgradeFeature());
}
return next();
});
},
};
static async Task WebSocket(HttpContext httpContext)
{
var logger = httpContext.RequestServices.GetRequiredService<ILogger<WebSocketTests>>();
if (!httpContext.WebSockets.IsWebSocketRequest)
{
httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
logger.LogInformation("Non-WebSocket request refused.");
return;
}
using var webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();
logger.LogInformation("WebSocket accepted.");
var buffer = new byte[1024];
while (true)
{
var message = await webSocket.ReceiveAsync(buffer, httpContext.RequestAborted);
if (message.MessageType == WebSocketMessageType.Close)
{
logger.LogInformation("WebSocket Close received {status}.", message.CloseStatus);
await webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, message.CloseStatusDescription, httpContext.RequestAborted);
logger.LogInformation("WebSocket Close sent {status}.", WebSocketCloseStatus.NormalClosure);
return;
}
logger.LogInformation("WebSocket received {count} bytes.", message.Count);
await webSocket.SendAsync(buffer[0..message.Count],
message.MessageType,
message.EndOfMessage,
httpContext.RequestAborted);
logger.LogInformation("WebSocket sent {count} bytes.", message.Count);
}
}
static async Task WebSocketVersion(HttpContext httpContext)
{
var logger = httpContext.RequestServices.GetRequiredService<ILogger<WebSocketTests>>();
if (!httpContext.WebSockets.IsWebSocketRequest)
{
httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
logger.LogInformation("Non-WebSocket request refused.");
return;
}
using var webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();
logger.LogInformation("WebSocket accepted.");
var buffer = new byte[1024];
while (true)
{
var message = await webSocket.ReceiveAsync(buffer, httpContext.RequestAborted);
if (message.MessageType == WebSocketMessageType.Close)
{
logger.LogInformation("WebSocket Close received {status}.", message.CloseStatus);
await webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, message.CloseStatusDescription, httpContext.RequestAborted);
logger.LogInformation("WebSocket Close sent {status}.", WebSocketCloseStatus.NormalClosure);
return;
}
logger.LogInformation("WebSocket received {count} bytes.", message.Count);
await webSocket.SendAsync(Encoding.ASCII.GetBytes(httpContext.Request.Protocol),
WebSocketMessageType.Text,
endOfMessage: true,
httpContext.RequestAborted);
logger.LogInformation("WebSocket sent {count} bytes.", httpContext.Request.Protocol.Length);
}
}
static async Task RawUpgrade(HttpContext httpContext)
{
var upgradeFeature = httpContext.Features.Get<IHttpUpgradeFeature>();
if (upgradeFeature is null || !upgradeFeature.IsUpgradableRequest)
{
httpContext.Response.StatusCode = StatusCodes.Status426UpgradeRequired;
return;
}
await using var stream = await upgradeFeature.UpgradeAsync();
var buffer = new byte[5];
int read;
while ((read = await stream.ReadAsync(buffer, httpContext.RequestAborted)) != 0)
{
await stream.WriteAsync(buffer, 0, read, httpContext.RequestAborted);
if (string.Equals("close", Encoding.UTF8.GetString(buffer, 0, read), StringComparison.Ordinal))
{
break;
}
}
}
static async Task Post(HttpContext httpContext)
{
var body = await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
await httpContext.Response.WriteAsync(body);
}
}
private static CancellationTokenSource CreateTimer()
{
if (Debugger.IsAttached)
{
return new CancellationTokenSource();
}
return new CancellationTokenSource(TimeSpan.FromSeconds(15));
}
private static HttpMessageInvoker CreateInvoker()
{
var handler = new SocketsHttpHandler
{
AllowAutoRedirect = false,
AutomaticDecompression = DecompressionMethods.None,
UseCookies = false,
UseProxy = false
};
handler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true;
return new HttpMessageInvoker(handler);
}
private class AlwaysUpgradeFeature : IHttpUpgradeFeature
{
public bool IsUpgradableRequest => true;
public Task<Stream> UpgradeAsync()
{
throw new InvalidOperationException("This wasn't supposed to get called.");
}
}
}