Skip to content

Commit 5ca9230

Browse files
authored
PR feedback from #11412 (#11474)
- Remove ExpectedMiddlewareCount since everything is middleware now - Renamed everything adapter to middleware - Added a regression test for an https scenario - Don't send client certs for tests that don't expect it
1 parent 2420d8f commit 5ca9230

17 files changed

+140
-136
lines changed

src/Servers/Kestrel/Core/test/AddressBinderTests.cs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,19 @@
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using System;
5+
using System.Collections.Generic;
56
using System.IO;
67
using System.Net;
78
using System.Net.Sockets;
89
using System.Threading.Tasks;
910
using Microsoft.AspNetCore.Connections;
11+
using Microsoft.AspNetCore.Hosting;
1012
using Microsoft.AspNetCore.Http;
1113
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal;
14+
using Microsoft.AspNetCore.Server.Kestrel.Https;
1215
using Microsoft.AspNetCore.Testing;
1316
using Microsoft.AspNetCore.Testing.xunit;
17+
using Microsoft.Extensions.DependencyInjection;
1418
using Microsoft.Extensions.Logging.Abstractions;
1519
using Xunit;
1620

@@ -149,5 +153,39 @@ await AddressBinder.BindAsync(addresses,
149153
Assert.True(ipV6Attempt, "Should have attempted to bind to IPAddress.IPv6Any");
150154
Assert.Contains(logger.Messages, f => f.Equals(CoreStrings.FormatFallbackToIPv4Any(80)));
151155
}
156+
157+
[Fact]
158+
public async Task DefaultAddressBinderWithoutDevCertButHttpsConfiguredBindsToHttpsPorts()
159+
{
160+
var x509Certificate2 = TestResources.GetTestCertificate();
161+
var logger = new MockLogger();
162+
var addresses = new ServerAddressesFeature();
163+
var services = new ServiceCollection();
164+
services.AddLogging();
165+
var options = new KestrelServerOptions()
166+
{
167+
// This stops the dev cert from being loaded
168+
IsDevCertLoaded = true,
169+
ApplicationServices = services.BuildServiceProvider()
170+
};
171+
172+
options.ConfigureEndpointDefaults(e =>
173+
{
174+
if (e.IPEndPoint.Port == 5001)
175+
{
176+
e.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = x509Certificate2 });
177+
}
178+
});
179+
180+
var endpoints = new List<ListenOptions>();
181+
await AddressBinder.BindAsync(addresses, options, logger, listenOptions =>
182+
{
183+
endpoints.Add(listenOptions);
184+
return Task.CompletedTask;
185+
});
186+
187+
Assert.Contains(endpoints, e => e.IPEndPoint.Port == 5000 && !e.IsTls);
188+
Assert.Contains(endpoints, e => e.IPEndPoint.Port == 5001 && e.IsTls);
189+
}
152190
}
153191
}

src/Servers/Kestrel/shared/test/TestServiceContext.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,6 @@ private void Initialize(ILoggerFactory loggerFactory, IKestrelTrace kestrelTrace
7676

7777
public Func<MemoryPool<byte>> MemoryPoolFactory { get; set; } = System.Buffers.SlabMemoryPoolFactory.Create;
7878

79-
public int ExpectedConnectionMiddlewareCount { get; set; }
80-
8179
public string DateHeaderValue => DateHeaderValueManager.GetDateHeaderValues().String;
8280
}
8381
}

src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,11 +89,6 @@ public TestServer(RequestDelegate app, TestServiceContext context, Action<Kestre
8989
c.Configure(context.ServerOptions);
9090
}
9191

92-
// Prevent ListenOptions reuse. This is easily done accidentally when trying to debug a test by running it
93-
// in a loop, but will cause problems because only the app func from the first loop will ever be invoked.
94-
Assert.All(context.ServerOptions.ListenOptions, lo =>
95-
Assert.Equal(context.ExpectedConnectionMiddlewareCount, lo._middleware.Count));
96-
9792
return new KestrelServer(sp.GetRequiredService<IConnectionListenerFactory>(), context);
9893
});
9994
configureServices(services);

src/Servers/Kestrel/test/FunctionalTests/ConnectionAdapterTests.cs renamed to src/Servers/Kestrel/test/FunctionalTests/ConnectionMiddlewareTests.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,15 @@
1212

1313
namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
1414
{
15-
public class ConnectionAdapterTests : LoggedTest
15+
public class ConnectionMiddlewareTests : LoggedTest
1616
{
1717
[Fact]
18-
public async Task ThrowingSynchronousConnectionAdapterDoesNotCrashServer()
18+
public async Task ThrowingSynchronousConnectionMiddlewareDoesNotCrashServer()
1919
{
2020
var listenOptions = new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0));
2121
listenOptions.Use(next => context => throw new Exception());
2222

23-
var serviceContext = new TestServiceContext(LoggerFactory) { ExpectedConnectionMiddlewareCount = 1 };
23+
var serviceContext = new TestServiceContext(LoggerFactory);
2424

2525
using (var server = new TestServer(TestApp.EchoApp, serviceContext, listenOptions))
2626
{

src/Servers/Kestrel/test/FunctionalTests/Http2/HandshakeTests.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public void TlsAndHttp2NotSupportedOnMac()
4444
var ex = Assert.Throws<NotSupportedException>(() => new TestServer(context =>
4545
{
4646
throw new NotImplementedException();
47-
}, new TestServiceContext(LoggerFactory) { ExpectedConnectionMiddlewareCount = 1 },
47+
}, new TestServiceContext(LoggerFactory),
4848
kestrelOptions =>
4949
{
5050
kestrelOptions.Listen(IPAddress.Loopback, 0, listenOptions =>
@@ -71,7 +71,7 @@ public async Task TlsAlpnHandshakeSelectsHttp2From1and2()
7171
"ALPN: " + tlsFeature.ApplicationProtocol.Length);
7272

7373
return context.Response.WriteAsync("hello world " + context.Request.Protocol);
74-
}, new TestServiceContext(LoggerFactory) { ExpectedConnectionMiddlewareCount = 1 },
74+
}, new TestServiceContext(LoggerFactory),
7575
kestrelOptions =>
7676
{
7777
kestrelOptions.Listen(IPAddress.Loopback, 0, listenOptions =>
@@ -102,7 +102,7 @@ public async Task TlsAlpnHandshakeSelectsHttp2()
102102
"ALPN: " + tlsFeature.ApplicationProtocol.Length);
103103

104104
return context.Response.WriteAsync("hello world " + context.Request.Protocol);
105-
}, new TestServiceContext(LoggerFactory) { ExpectedConnectionMiddlewareCount = 1 },
105+
}, new TestServiceContext(LoggerFactory),
106106
kestrelOptions =>
107107
{
108108
kestrelOptions.Listen(IPAddress.Loopback, 0, listenOptions =>

src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public async Task GracefulShutdownWaitsForRequestsToFinish()
6060
.Setup(m => m.Http2ConnectionClosing(It.IsAny<string>()))
6161
.Callback(() => requestStopping.SetResult(null));
6262

63-
var testContext = new TestServiceContext(LoggerFactory, mockKestrelTrace.Object) { ExpectedConnectionMiddlewareCount = 1 };
63+
var testContext = new TestServiceContext(LoggerFactory, mockKestrelTrace.Object);
6464

6565
testContext.InitializeHeartbeat();
6666

@@ -112,8 +112,7 @@ public async Task GracefulTurnsAbortiveIfRequestsDoNotFinish()
112112

113113
var testContext = new TestServiceContext(LoggerFactory)
114114
{
115-
MemoryPoolFactory = memoryPoolFactory.Create,
116-
ExpectedConnectionMiddlewareCount = 1
115+
MemoryPoolFactory = memoryPoolFactory.Create
117116
};
118117

119118
TestApplicationErrorLogger.ThrowOnUngracefulShutdown = false;

src/Servers/Kestrel/test/FunctionalTests/RequestTests.cs

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public class RequestTests : LoggedTest
3737
private const int _connectionResetEventId = 19;
3838
private static readonly int _semaphoreWaitTimeout = Debugger.IsAttached ? 10000 : 2500;
3939

40-
public static TheoryData<ListenOptions> ConnectionAdapterData => new TheoryData<ListenOptions>
40+
public static TheoryData<ListenOptions> ConnectionMiddlewareData => new TheoryData<ListenOptions>
4141
{
4242
new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0)),
4343
new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0)).UsePassThrough()
@@ -503,10 +503,10 @@ public async Task AbortingTheConnectionSendsFIN()
503503
}
504504

505505
[Theory]
506-
[MemberData(nameof(ConnectionAdapterData))]
506+
[MemberData(nameof(ConnectionMiddlewareData))]
507507
public async Task ConnectionClosedTokenFiresOnClientFIN(ListenOptions listenOptions)
508508
{
509-
var testContext = new TestServiceContext(LoggerFactory) { ExpectedConnectionMiddlewareCount = listenOptions._middleware.Count };
509+
var testContext = new TestServiceContext(LoggerFactory);
510510
var appStartedTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
511511
var connectionClosedTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
512512

@@ -540,10 +540,10 @@ await connection.Send(
540540

541541
[Theory]
542542
[Flaky("https://github.com/aspnet/AspNetCore-Internal/issues/2181", FlakyOn.Helix.All)]
543-
[MemberData(nameof(ConnectionAdapterData))]
543+
[MemberData(nameof(ConnectionMiddlewareData))]
544544
public async Task ConnectionClosedTokenFiresOnServerFIN(ListenOptions listenOptions)
545545
{
546-
var testContext = new TestServiceContext(LoggerFactory) { ExpectedConnectionMiddlewareCount = listenOptions._middleware.Count };
546+
var testContext = new TestServiceContext(LoggerFactory);
547547
var connectionClosedTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
548548

549549
using (var server = new TestServer(context =>
@@ -577,10 +577,10 @@ await connection.ReceiveEnd($"HTTP/1.1 200 OK",
577577
}
578578

579579
[Theory]
580-
[MemberData(nameof(ConnectionAdapterData))]
580+
[MemberData(nameof(ConnectionMiddlewareData))]
581581
public async Task ConnectionClosedTokenFiresOnServerAbort(ListenOptions listenOptions)
582582
{
583-
var testContext = new TestServiceContext(LoggerFactory) { ExpectedConnectionMiddlewareCount = listenOptions._middleware.Count };
583+
var testContext = new TestServiceContext(LoggerFactory);
584584
var connectionClosedTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
585585

586586
using (var server = new TestServer(context =>
@@ -619,13 +619,13 @@ await connection.Send(
619619
}
620620

621621
[Theory]
622-
[MemberData(nameof(ConnectionAdapterData))]
622+
[MemberData(nameof(ConnectionMiddlewareData))]
623623
public async Task RequestsCanBeAbortedMidRead(ListenOptions listenOptions)
624624
{
625625
// This needs a timeout.
626626
const int applicationAbortedConnectionId = 34;
627627

628-
var testContext = new TestServiceContext(LoggerFactory) { ExpectedConnectionMiddlewareCount = listenOptions._middleware.Count };
628+
var testContext = new TestServiceContext(LoggerFactory);
629629

630630
var readTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
631631
var registrationTcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
@@ -710,7 +710,7 @@ await connection.Send("POST / HTTP/1.1",
710710
}
711711

712712
[Theory]
713-
[MemberData(nameof(ConnectionAdapterData))]
713+
[MemberData(nameof(ConnectionMiddlewareData))]
714714
public async Task ServerCanAbortConnectionAfterUnobservedClose(ListenOptions listenOptions)
715715
{
716716
const int connectionPausedEventId = 4;
@@ -743,7 +743,6 @@ public async Task ServerCanAbortConnectionAfterUnobservedClose(ListenOptions lis
743743
var mockKestrelTrace = new Mock<IKestrelTrace>();
744744
var testContext = new TestServiceContext(LoggerFactory, mockKestrelTrace.Object)
745745
{
746-
ExpectedConnectionMiddlewareCount = listenOptions._middleware.Count,
747746
ServerOptions =
748747
{
749748
Limits =
@@ -796,14 +795,14 @@ await connection.Send(
796795
#if LIBUV
797796
[Flaky("https://github.com/aspnet/AspNetCore-Internal/issues/1971", FlakyOn.Helix.All)]
798797
#endif
799-
[MemberData(nameof(ConnectionAdapterData))]
798+
[MemberData(nameof(ConnectionMiddlewareData))]
800799
public async Task AppCanHandleClientAbortingConnectionMidRequest(ListenOptions listenOptions)
801800
{
802801
var readTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
803802
var appStartedTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
804803

805804
var mockKestrelTrace = new Mock<IKestrelTrace>();
806-
var testContext = new TestServiceContext(LoggerFactory, mockKestrelTrace.Object) { ExpectedConnectionMiddlewareCount = listenOptions._middleware.Count };
805+
var testContext = new TestServiceContext(LoggerFactory, mockKestrelTrace.Object);
807806

808807
var scratchBuffer = new byte[4096];
809808

src/Servers/Kestrel/test/FunctionalTests/ResponseTests.cs

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
3333
{
3434
public class ResponseTests : TestApplicationErrorLoggerLoggedTest
3535
{
36-
public static TheoryData<ListenOptions> ConnectionAdapterData => new TheoryData<ListenOptions>
36+
public static TheoryData<ListenOptions> ConnectionMiddlewareData => new TheoryData<ListenOptions>
3737
{
3838
new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0)),
3939
new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0)).UsePassThrough()
@@ -136,7 +136,7 @@ public async Task IgnoreNullHeaderValues(string headerName, StringValues headerV
136136
}
137137

138138
[Theory]
139-
[MemberData(nameof(ConnectionAdapterData))]
139+
[MemberData(nameof(ConnectionMiddlewareData))]
140140
public async Task WriteAfterConnectionCloseNoops(ListenOptions listenOptions)
141141
{
142142
var connectionClosed = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
@@ -157,7 +157,7 @@ public async Task WriteAfterConnectionCloseNoops(ListenOptions listenOptions)
157157
{
158158
appCompleted.TrySetException(ex);
159159
}
160-
}, new TestServiceContext(LoggerFactory) { ExpectedConnectionMiddlewareCount = listenOptions._middleware.Count }, listenOptions))
160+
}, new TestServiceContext(LoggerFactory), listenOptions))
161161
{
162162
using (var connection = server.CreateConnection())
163163
{
@@ -180,7 +180,7 @@ await connection.Send(
180180
}
181181

182182
[Theory]
183-
[MemberData(nameof(ConnectionAdapterData))]
183+
[MemberData(nameof(ConnectionMiddlewareData))]
184184
public async Task ThrowsOnWriteWithRequestAbortedTokenAfterRequestIsAborted(ListenOptions listenOptions)
185185
{
186186
// This should match _maxBytesPreCompleted in SocketOutput
@@ -219,7 +219,7 @@ public async Task ThrowsOnWriteWithRequestAbortedTokenAfterRequestIsAborted(List
219219
}
220220

221221
writeTcs.SetException(new Exception("This shouldn't be reached."));
222-
}, new TestServiceContext(LoggerFactory) { ExpectedConnectionMiddlewareCount = listenOptions._middleware.Count }, listenOptions))
222+
}, new TestServiceContext(LoggerFactory), listenOptions))
223223
{
224224
using (var connection = server.CreateConnection())
225225
{
@@ -244,7 +244,7 @@ await connection.Send(
244244
}
245245

246246
[Theory]
247-
[MemberData(nameof(ConnectionAdapterData))]
247+
[MemberData(nameof(ConnectionMiddlewareData))]
248248
public async Task WritingToConnectionAfterUnobservedCloseTriggersRequestAbortedToken(ListenOptions listenOptions)
249249
{
250250
const int connectionPausedEventId = 4;
@@ -273,7 +273,6 @@ public async Task WritingToConnectionAfterUnobservedCloseTriggersRequestAbortedT
273273

274274
var testContext = new TestServiceContext(LoggerFactory, mockKestrelTrace.Object)
275275
{
276-
ExpectedConnectionMiddlewareCount = listenOptions._middleware.Count,
277276
ServerOptions =
278277
{
279278
Limits =
@@ -341,7 +340,7 @@ await connection.Send(
341340

342341
[Theory]
343342
[Flaky("https://github.com/aspnet/AspNetCore-Internal/issues/1972", FlakyOn.All)]
344-
[MemberData(nameof(ConnectionAdapterData))]
343+
[MemberData(nameof(ConnectionMiddlewareData))]
345344
public async Task AppCanHandleClientAbortingConnectionMidResponse(ListenOptions listenOptions)
346345
{
347346
const int connectionResetEventId = 19;
@@ -368,7 +367,7 @@ public async Task AppCanHandleClientAbortingConnectionMidResponse(ListenOptions
368367

369368
await requestAborted.Task.DefaultTimeout();
370369
appCompletedTcs.SetResult(null);
371-
}, new TestServiceContext(LoggerFactory) { ExpectedConnectionMiddlewareCount = listenOptions._middleware.Count }, listenOptions))
370+
}, new TestServiceContext(LoggerFactory), listenOptions))
372371
{
373372
using (var connection = server.CreateConnection())
374373
{
@@ -414,15 +413,15 @@ await connection.Send(
414413
}
415414

416415
[Theory]
417-
[MemberData(nameof(ConnectionAdapterData))]
416+
[MemberData(nameof(ConnectionMiddlewareData))]
418417
public async Task ClientAbortingConnectionImmediatelyIsNotLoggedHigherThanDebug(ListenOptions listenOptions)
419418
{
420419
// Attempt multiple connections to be extra sure the resets are consistently logged appropriately.
421420
const int numConnections = 10;
422421

423422
// There's not guarantee that the app even gets invoked in this test. The connection reset can be observed
424423
// as early as accept.
425-
var testServiceContext = new TestServiceContext(LoggerFactory) { ExpectedConnectionMiddlewareCount = listenOptions._middleware.Count };
424+
var testServiceContext = new TestServiceContext(LoggerFactory);
426425
using (var server = new TestServer(context => Task.CompletedTask, testServiceContext, listenOptions))
427426
{
428427
for (var i = 0; i < numConnections; i++)
@@ -582,8 +581,7 @@ public async Task HttpsConnectionClosedWhenResponseDoesNotSatisfyMinimumDataRate
582581
{
583582
MinResponseDataRate = new MinDataRate(bytesPerSecond: 1024 * 1024, gracePeriod: TimeSpan.FromSeconds(2))
584583
}
585-
},
586-
ExpectedConnectionMiddlewareCount = 1
584+
}
587585
};
588586

589587
testContext.InitializeHeartbeat();

src/Servers/Kestrel/test/InMemory.FunctionalTests/ConnectionLimitTests.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -207,10 +207,7 @@ private TestServer CreateServerWithMaxConnections(RequestDelegate app, long max)
207207

208208
private TestServer CreateServerWithMaxConnections(RequestDelegate app, ResourceCounter concurrentConnectionCounter)
209209
{
210-
var serviceContext = new TestServiceContext(LoggerFactory)
211-
{
212-
ExpectedConnectionMiddlewareCount = 1
213-
};
210+
var serviceContext = new TestServiceContext(LoggerFactory);
214211

215212
var listenOptions = new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0));
216213
listenOptions.Use(next =>

0 commit comments

Comments
 (0)