mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 23:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+275
@@ -0,0 +1,275 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Networking;
|
||||
using Lumina.Infrastructure.Common.Networking;
|
||||
using Lumina.Plugins.Contracts.Common.Http;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Common.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PublicHostConnectionGuard"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PublicHostConnectionGuardTests
|
||||
{
|
||||
private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34");
|
||||
|
||||
[Fact]
|
||||
public void CreatePrimaryHandler_WhenCalled_ShouldDisableAutomaticRedirectsAndInstallTheConnectGuard()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator publicHostValidator = CreateValidator(host => [s_publicAddress]);
|
||||
|
||||
// Act
|
||||
using SocketsHttpHandler handler = PublicHostConnectionGuard.CreatePrimaryHandler(publicHostValidator, NullLogger.Instance);
|
||||
|
||||
// Assert
|
||||
Assert.False(handler.AllowAutoRedirect);
|
||||
Assert.False(handler.UseProxy);
|
||||
Assert.NotNull(handler.ConnectCallback);
|
||||
// The callback behavior itself is covered by CreatePrimaryHandler_WhenARequestConnects_ShouldUseTheAllowedPrivateHostOfTheInitialRequest.
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectAsync_WhenTheHostResolvesToOnePrivateAddress_ShouldThrowWithoutConnecting()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator publicHostValidator = CreateValidator(host => [s_publicAddress, IPAddress.Parse("10.0.0.5")]);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "mixed.example.com", 443, request: null, NullLogger.Instance, CancellationToken.None).AsTask();
|
||||
}
|
||||
|
||||
// Assert
|
||||
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, exception.RejectionReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectAsync_WhenTheRequestUriHasAUnicodeIdnHostAndTheConnectionUsesThePunycodeHost_ShouldValidateTheResolvedAddress()
|
||||
{
|
||||
// Arrange
|
||||
// Uri.Host keeps the Unicode spelling of an internationalized name, while the connection authority uses its punycode spelling. The two must never be
|
||||
// compared to decide whether a connection goes to a proxy, because an attacker controlled name could otherwise skip the address check.
|
||||
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, "https://bücher.example/cover.jpg");
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "xn--bcher-kva.example", 1, request, NullLogger.Instance, CancellationToken.None).AsTask();
|
||||
}
|
||||
|
||||
// Assert
|
||||
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, exception.RejectionReason);
|
||||
Assert.DoesNotContain("127.0.0.1", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectAsync_WhenAnotherHostResolvesToAPrivateAddress_ShouldThrowWithoutConnecting()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, "http://other.internal.example.com/cover.jpg");
|
||||
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "internal.example.com");
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "other.internal.example.com", 443, request, NullLogger.Instance, CancellationToken.None).AsTask();
|
||||
}
|
||||
|
||||
// Assert
|
||||
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, exception.RejectionReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectAsync_WhenTheAllowedPrivateHostResolvesToTheLinkLocalMetadataAddress_ShouldThrowWithoutConnecting()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Parse("169.254.169.254")]);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, "http://internal.example.com/cover.jpg");
|
||||
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "internal.example.com");
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "internal.example.com", 443, request, NullLogger.Instance, CancellationToken.None).AsTask();
|
||||
}
|
||||
|
||||
// Assert
|
||||
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
Assert.Equal(OutboundRequestRejectionReason.LinkLocalOrMetadataAddress, exception.RejectionReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectAsync_WhenTheFirstAddressIsUnreachable_ShouldConnectToTheNextAddress()
|
||||
{
|
||||
// Arrange
|
||||
using TcpListener listener = new(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
// 10.0.0.1 is a private address that no test service listens on, so the loopback address wins the staggered race.
|
||||
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Parse("10.0.0.1"), IPAddress.Loopback]);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, "http://mixed.example.com/cover.jpg");
|
||||
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "mixed.example.com");
|
||||
using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10));
|
||||
|
||||
// Act
|
||||
Task<Stream> connectTask = PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "mixed.example.com", port, request, NullLogger.Instance, CancellationToken.None).AsTask();
|
||||
(TcpClient acceptedClient, Stream stream) = await AcceptConnectionAsync(listener, connectTask, cancellationTokenSource);
|
||||
using (acceptedClient)
|
||||
using (stream)
|
||||
{
|
||||
// Assert
|
||||
Assert.True(stream.CanWrite);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreatePrimaryHandler_WhenTheConnectPolicyRejectsTheAddress_ShouldWrapThePolicyRejectionAsAConnectionError()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]);
|
||||
using SocketsHttpHandler handler = PublicHostConnectionGuard.CreatePrimaryHandler(publicHostValidator, NullLogger.Instance);
|
||||
using HttpClient client = new(handler);
|
||||
using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetAsync("http://internal.example.com/", cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
// Assert
|
||||
HttpRequestException exception = await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
Assert.Equal(HttpRequestError.ConnectionError, exception.HttpRequestError);
|
||||
PublicHostRejectedException innerException = Assert.IsType<PublicHostRejectedException>(exception.InnerException);
|
||||
Assert.Equal(HttpRequestError.ConfigurationLimitExceeded, innerException.HttpRequestError);
|
||||
Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, innerException.RejectionReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreatePrimaryHandler_WhenARequestConnects_ShouldUseTheAllowedPrivateHostOfTheInitialRequest()
|
||||
{
|
||||
// Arrange
|
||||
using TcpListener listener = new(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]);
|
||||
using SocketsHttpHandler handler = PublicHostConnectionGuard.CreatePrimaryHandler(publicHostValidator, NullLogger.Instance);
|
||||
using HttpClient client = new(handler);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, $"http://internal.example.com:{port}/");
|
||||
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "internal.example.com");
|
||||
using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10));
|
||||
|
||||
// Act
|
||||
Task<HttpResponseMessage> requestTask = client.SendAsync(request, cancellationTokenSource.Token);
|
||||
Task<TcpClient> acceptTask = listener.AcceptTcpClientAsync(cancellationTokenSource.Token).AsTask();
|
||||
try
|
||||
{
|
||||
Task firstCompletedTask = await Task.WhenAny(requestTask, acceptTask);
|
||||
// Await the request first when it completed, so a failure to connect surfaces its own exception instead of the accept timeout.
|
||||
if (firstCompletedTask == requestTask)
|
||||
await requestTask;
|
||||
|
||||
using TcpClient acceptedClient = await acceptTask;
|
||||
using NetworkStream stream = acceptedClient.GetStream();
|
||||
byte[] responseBytes = Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
|
||||
await stream.WriteAsync(responseBytes, cancellationTokenSource.Token);
|
||||
using HttpResponseMessage response = await requestTask;
|
||||
|
||||
// Assert
|
||||
// The connect callback resolved the host through the validator and read the allowed private host from the initial request message, because
|
||||
// without that option the loopback address would have been rejected and the connection would never have been accepted.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
finally
|
||||
{
|
||||
cancellationTokenSource.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectAsync_WhenTheRequestAllowsPrivateEndPoints_ShouldConnectToThePrivateAddress()
|
||||
{
|
||||
// Arrange
|
||||
using TcpListener listener = new(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, "http://internal.example.com/cover.jpg");
|
||||
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "internal.example.com");
|
||||
using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10));
|
||||
|
||||
// Act
|
||||
Task<Stream> connectTask = PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "internal.example.com", port, request, NullLogger.Instance, CancellationToken.None).AsTask();
|
||||
(TcpClient acceptedClient, Stream stream) = await AcceptConnectionAsync(listener, connectTask, cancellationTokenSource);
|
||||
using (acceptedClient)
|
||||
using (stream)
|
||||
{
|
||||
// Assert
|
||||
Assert.True(stream.CanWrite);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Accepts the connection made by <paramref name="connectTask"/>, surfacing a connection failure instead of waiting for the accept timeout.
|
||||
/// </summary>
|
||||
/// <param name="listener">The listener that accepts the connection.</param>
|
||||
/// <param name="connectTask">The task that establishes the connection.</param>
|
||||
/// <param name="cancellationTokenSource">The cancellation token source that bounds the accept.</param>
|
||||
/// <returns>The accepted client and the established stream.</returns>
|
||||
private static async Task<(TcpClient AcceptedClient, Stream Stream)> AcceptConnectionAsync(TcpListener listener, Task<Stream> connectTask, CancellationTokenSource cancellationTokenSource)
|
||||
{
|
||||
Task<TcpClient> acceptTask = listener.AcceptTcpClientAsync(cancellationTokenSource.Token).AsTask();
|
||||
try
|
||||
{
|
||||
Task firstCompletedTask = await Task.WhenAny(connectTask, acceptTask).ConfigureAwait(false);
|
||||
// Await the connect task first when it completed, so a failure to connect surfaces its own exception instead of the accept timeout.
|
||||
if (firstCompletedTask == connectTask)
|
||||
await connectTask.ConfigureAwait(false);
|
||||
|
||||
TcpClient acceptedClient = await acceptTask.ConfigureAwait(false);
|
||||
Stream stream = await connectTask.ConfigureAwait(false);
|
||||
return (acceptedClient, stream);
|
||||
}
|
||||
catch
|
||||
{
|
||||
cancellationTokenSource.Cancel();
|
||||
try
|
||||
{
|
||||
await acceptTask.ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// The accept was canceled because the connection failed; its exception must not mask the connection failure.
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PublicHostValidator"/> whose host name resolution is replaced by the provided resolver.
|
||||
/// </summary>
|
||||
/// <param name="addressResolver">The resolver that produces the addresses of a host name.</param>
|
||||
/// <returns>The created validator.</returns>
|
||||
private static PublicHostValidator CreateValidator(Func<string, IPAddress[]> addressResolver)
|
||||
{
|
||||
return new PublicHostValidator((host, cancellationToken) => Task.FromResult(addressResolver(host)));
|
||||
}
|
||||
}
|
||||
+427
@@ -0,0 +1,427 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Networking;
|
||||
using Lumina.Infrastructure.Common.Networking;
|
||||
using Lumina.Plugins.Contracts.Common.Http;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Common.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PublicHostRedirectHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PublicHostRedirectHandlerTests
|
||||
{
|
||||
private const string PRIVATE_HOST = "internal.example.com";
|
||||
|
||||
private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34");
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheResponseRedirectsToAPublicHttpsHost_ShouldFollowIt()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
{
|
||||
if (callIndex == 1)
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri("https://archive.org/download/mbid-1/index.json");
|
||||
return redirect;
|
||||
}
|
||||
return new HttpResponseMessage(HttpStatusCode.OK);
|
||||
});
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("https://coverartarchive.org/release/1");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(2, innerHandler.CallCount);
|
||||
Assert.Equal("archive.org", innerHandler.Requests[1].RequestUri!.Host);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheResponseRedirectsToAPrivateHostName_ShouldThrow()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri($"https://{PRIVATE_HOST}/index.json");
|
||||
return redirect;
|
||||
});
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetAsync("https://coverartarchive.org/release/1");
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
Assert.Equal(1, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("http://archive.org/index.json")] // A downgrade of a trusted host to plain HTTP.
|
||||
[InlineData("https://127.0.0.1/index.json")] // The IPv4 loopback address.
|
||||
[InlineData("https://localhost/index.json")] // The loopback host name.
|
||||
[InlineData("https://169.254.169.254/latest/meta-data/")] // The link local cloud metadata endpoint.
|
||||
[InlineData("https://10.0.0.5/index.json")] // A private class A address.
|
||||
[InlineData("https://192.168.1.10/index.json")] // A private class C address.
|
||||
public async Task SendAsync_WhenTheResponseRedirectsToADisallowedTarget_ShouldThrow(string location)
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri(location);
|
||||
return redirect;
|
||||
});
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetAsync("https://coverartarchive.org/release/1");
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
Assert.Equal(1, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheRequestAllowsPrivateEndPointsAndRedirectsToAPrivateHost_ShouldFollowIt()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
{
|
||||
if (callIndex == 1)
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri($"https://{PRIVATE_HOST}/index.json");
|
||||
return redirect;
|
||||
}
|
||||
return new HttpResponseMessage(HttpStatusCode.OK);
|
||||
});
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/start");
|
||||
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST);
|
||||
|
||||
// Act
|
||||
using HttpResponseMessage response = await client.SendAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(2, innerHandler.CallCount);
|
||||
Assert.Equal(PRIVATE_HOST, innerHandler.Requests[1].RequestUri!.Host);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenARequestWithABodyIsRedirected_ShouldReturnTheRedirectResponseWithoutFollowingIt()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri("https://archive.org/index.json");
|
||||
return redirect;
|
||||
});
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
using HttpRequestMessage request = new(HttpMethod.Post, "https://coverartarchive.org/release/1");
|
||||
|
||||
// Act
|
||||
using HttpResponseMessage response = await client.SendAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.TemporaryRedirect, response.StatusCode);
|
||||
Assert.Equal(1, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheRequestIsRedirectedTooManyTimes_ShouldThrow()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri("https://archive.org/loop/index.json");
|
||||
return redirect;
|
||||
});
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetAsync("https://coverartarchive.org/release/1");
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
// The initial request plus the maximum number of followed redirects are sent before the loop is detected.
|
||||
Assert.Equal(6, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheRequestDisablesRedirectFollowing_ShouldReturnTheRedirectResponseWithoutFollowingIt()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri("https://archive.org/index.json");
|
||||
return redirect;
|
||||
});
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, "https://coverartarchive.org/release/1");
|
||||
request.Options.Set(OutboundRequestOptions.FollowRedirects, false);
|
||||
|
||||
// Act
|
||||
using HttpResponseMessage response = await client.SendAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.TemporaryRedirect, response.StatusCode);
|
||||
Assert.Equal("https://archive.org/index.json", response.Headers.Location!.AbsoluteUri);
|
||||
Assert.Equal(1, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheRedirectPointsAtAnotherPrivateHostThanTheAllowedOne_ShouldThrow()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri("https://another.internal.example.com/index.json");
|
||||
return redirect;
|
||||
});
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/start");
|
||||
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.SendAsync(request);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
Assert.Equal(1, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenARedirectCrossesOrigins_ShouldNotForwardCredentialsOrHopByHopHeaders()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
{
|
||||
if (callIndex == 1)
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri("https://archive.org/index.json");
|
||||
return redirect;
|
||||
}
|
||||
return new HttpResponseMessage(HttpStatusCode.OK);
|
||||
});
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, "https://coverartarchive.org/start");
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "secret");
|
||||
request.Headers.TryAddWithoutValidation("Cookie", "session=secret");
|
||||
request.Headers.TryAddWithoutValidation("Proxy-Authorization", "Basic secret");
|
||||
request.Headers.Host = "coverartarchive.org";
|
||||
request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
|
||||
request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=5");
|
||||
request.Headers.TryAddWithoutValidation("TE", "trailers");
|
||||
request.Headers.TryAddWithoutValidation("Upgrade", "h2c");
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
using HttpResponseMessage response = await client.SendAsync(request);
|
||||
|
||||
// Assert
|
||||
HttpRequestMessage redirectedRequest = innerHandler.Requests[1];
|
||||
Assert.Null(redirectedRequest.Headers.Authorization);
|
||||
Assert.False(redirectedRequest.Headers.Contains("Cookie"));
|
||||
Assert.False(redirectedRequest.Headers.Contains("Proxy-Authorization"));
|
||||
Assert.Null(redirectedRequest.Headers.Host);
|
||||
Assert.False(redirectedRequest.Headers.Contains("Connection"));
|
||||
Assert.False(redirectedRequest.Headers.Contains("Keep-Alive"));
|
||||
Assert.False(redirectedRequest.Headers.Contains("TE"));
|
||||
Assert.False(redirectedRequest.Headers.Contains("Upgrade"));
|
||||
Assert.Contains("application/json", redirectedRequest.Headers.Accept.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenARedirectStaysOnTheSameOrigin_ShouldKeepCredentialsButDropHopByHopHeaders()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
{
|
||||
if (callIndex == 1)
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri("https://coverartarchive.org/index.json");
|
||||
return redirect;
|
||||
}
|
||||
return new HttpResponseMessage(HttpStatusCode.OK);
|
||||
});
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, "https://coverartarchive.org/start");
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "secret");
|
||||
request.Headers.TryAddWithoutValidation("Cookie", "session=secret");
|
||||
request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
|
||||
|
||||
// Act
|
||||
using HttpResponseMessage response = await client.SendAsync(request);
|
||||
|
||||
// Assert
|
||||
HttpRequestMessage redirectedRequest = innerHandler.Requests[1];
|
||||
Assert.Equal("Bearer secret", redirectedRequest.Headers.Authorization!.ToString());
|
||||
string cookieHeader = Assert.Single(redirectedRequest.Headers.GetValues("Cookie"));
|
||||
Assert.Equal("session=secret", cookieHeader);
|
||||
Assert.False(redirectedRequest.Headers.Contains("Connection"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenAHeadRequestIsRedirected_ShouldFollowIt()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
{
|
||||
if (callIndex == 1)
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri("https://archive.org/index.json");
|
||||
return redirect;
|
||||
}
|
||||
return new HttpResponseMessage(HttpStatusCode.OK);
|
||||
});
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
using HttpRequestMessage request = new(HttpMethod.Head, "https://coverartarchive.org/release/1");
|
||||
|
||||
// Act
|
||||
using HttpResponseMessage response = await client.SendAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(2, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenAnAllowedPrivateHostRedirectsToItselfAcrossMultipleHops_ShouldKeepThePermission()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
{
|
||||
if (callIndex <= 2)
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri(callIndex == 1 ? $"https://{PRIVATE_HOST}/second" : $"https://{PRIVATE_HOST}/third");
|
||||
return redirect;
|
||||
}
|
||||
return new HttpResponseMessage(HttpStatusCode.OK);
|
||||
});
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/start");
|
||||
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST);
|
||||
|
||||
// Act
|
||||
using HttpResponseMessage response = await client.SendAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(3, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheResponseRedirectsToPlainHttp_ShouldThrowAPublicHostRejectedException()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri("http://archive.org/index.json");
|
||||
return redirect;
|
||||
});
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetAsync("https://coverartarchive.org/release/1");
|
||||
}
|
||||
|
||||
// Assert
|
||||
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
Assert.Equal(OutboundRequestRejectionReason.RedirectSchemeNotHttps, exception.RejectionReason);
|
||||
Assert.Equal(1, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="HttpClient"/> whose requests are sent through the handler under test, wrapping the provided inner handler.
|
||||
/// </summary>
|
||||
/// <param name="innerHandler">The handler that answers the requests that reach the network.</param>
|
||||
/// <returns>The created client.</returns>
|
||||
private static HttpClient CreateClient(HttpMessageHandler innerHandler)
|
||||
{
|
||||
PublicHostValidator publicHostValidator = new((host, cancellationToken) =>
|
||||
Task.FromResult<IPAddress[]>(host.Contains("internal.example.com", StringComparison.OrdinalIgnoreCase) ? [IPAddress.Parse("10.0.0.5")] : [s_publicAddress]));
|
||||
PublicHostRedirectHandler handler = new(publicHostValidator, NullLogger<PublicHostRedirectHandler>.Instance) { InnerHandler = innerHandler };
|
||||
return new HttpClient(handler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
private sealed class StubHttpMessageHandler : HttpMessageHandler
|
||||
{
|
||||
private readonly Func<HttpRequestMessage, int, HttpResponseMessage> _responseFactory;
|
||||
private int _callCount;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the requests that were sent through the handler.
|
||||
/// </summary>
|
||||
public List<HttpRequestMessage> Requests { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of requests that were sent through the handler.
|
||||
/// </summary>
|
||||
public int CallCount => _callCount;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StubHttpMessageHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="responseFactory">The factory that produces the response of a request, given the request and its one based call index.</param>
|
||||
public StubHttpMessageHandler(Func<HttpRequestMessage, int, HttpResponseMessage> responseFactory)
|
||||
{
|
||||
_responseFactory = responseFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends the provided request, producing its response through the configured factory.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to send.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The response produced for the request.</returns>
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
int callIndex = Interlocked.Increment(ref _callCount);
|
||||
Requests.Add(request);
|
||||
return Task.FromResult(_responseFactory(request, callIndex));
|
||||
}
|
||||
}
|
||||
}
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Networking;
|
||||
using Lumina.Infrastructure.Common.Networking;
|
||||
using Lumina.Plugins.Contracts.Common.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Common.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PublicHostValidationHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PublicHostValidationHandlerTests
|
||||
{
|
||||
private const string PRIVATE_HOST = "internal.example.com";
|
||||
|
||||
private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34");
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheHostIsPublic_ShouldSendTheRequest()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new();
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
|
||||
// Act
|
||||
using HttpResponseMessage response = await client.GetAsync("https://example.com/cover.jpg");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(1, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("http://127.0.0.1/cover.jpg")] // The IPv4 loopback address.
|
||||
[InlineData("http://localhost/cover.jpg")] // The loopback host name.
|
||||
[InlineData("http://[::1]/cover.jpg")] // The IPv6 loopback address.
|
||||
[InlineData("http://169.254.169.254/latest/meta-data/")] // The link local cloud metadata endpoint.
|
||||
[InlineData("http://10.0.0.5/cover.jpg")] // A private class A address.
|
||||
[InlineData("http://172.16.0.1/cover.jpg")] // A private class B address.
|
||||
[InlineData("http://192.168.1.10/cover.jpg")] // A private class C address.
|
||||
public async Task SendAsync_WhenTheHostIsPrivateOrLocal_ShouldThrowAndNotSendTheRequest(string url)
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new();
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetAsync(url);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
Assert.Equal(0, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheHostNameResolvesToOnePrivateAddress_ShouldThrowAndNotSendTheRequest()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new();
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetAsync($"https://{PRIVATE_HOST}/cover.jpg");
|
||||
}
|
||||
|
||||
// Assert
|
||||
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, exception.RejectionReason);
|
||||
Assert.Contains(PRIVATE_HOST, exception.Message);
|
||||
Assert.DoesNotContain("10.0.0.5", exception.Message);
|
||||
Assert.Equal(0, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheHostCannotBeResolved_ShouldThrowAPublicHostResolutionException()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new();
|
||||
PublicHostValidator validator = new((host, cancellationToken) => throw new SocketException((int)SocketError.HostNotFound));
|
||||
PublicHostValidationHandler handler = new(validator, NullLogger<PublicHostValidationHandler>.Instance) { InnerHandler = innerHandler };
|
||||
using HttpClient client = new(handler);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetAsync("https://missing.example.com/cover.jpg");
|
||||
}
|
||||
|
||||
// Assert
|
||||
PublicHostResolutionException exception = await Assert.ThrowsAsync<PublicHostResolutionException>(Act);
|
||||
Assert.Equal(HttpRequestError.NameResolutionError, exception.HttpRequestError);
|
||||
Assert.Equal(0, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheHostIsRejected_ShouldLogAWarning()
|
||||
{
|
||||
// Arrange
|
||||
ILogger<PublicHostValidationHandler> mockLogger = Substitute.For<ILogger<PublicHostValidationHandler>>();
|
||||
mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
StubHttpMessageHandler innerHandler = new();
|
||||
PublicHostValidationHandler handler = new(CreateValidator(), mockLogger) { InnerHandler = innerHandler };
|
||||
using HttpClient client = new(handler);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetAsync($"https://{PRIVATE_HOST}/cover.jpg");
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
mockLogger.Received(1).Log(
|
||||
LogLevel.Warning,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheRequestAllowsPrivateEndPointsForTheHost_ShouldSendTheRequest()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new();
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/cover.jpg");
|
||||
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST);
|
||||
|
||||
// Act
|
||||
using HttpResponseMessage response = await client.SendAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(1, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheRequestAllowsPrivateEndPointsForAnotherHost_ShouldThrowAndNotSendTheRequest()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new();
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/cover.jpg");
|
||||
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "another.internal.example.com");
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.SendAsync(request);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
Assert.Equal(0, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheRequestHasNoAbsoluteUri_ShouldThrowAndNotSendTheRequest()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new();
|
||||
PublicHostValidationHandler handler = new(CreateValidator(), NullLogger<PublicHostValidationHandler>.Instance) { InnerHandler = innerHandler };
|
||||
using HttpMessageInvoker invoker = new(handler);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return invoker.SendAsync(new HttpRequestMessage(HttpMethod.Get, "/relative"), CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
Assert.Equal(OutboundRequestRejectionReason.RequestHasNoAbsoluteUri, exception.RejectionReason);
|
||||
Assert.Equal(0, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="HttpClient"/> whose requests are sent through the handler under test, wrapping the provided inner handler.
|
||||
/// </summary>
|
||||
/// <param name="innerHandler">The handler that answers the requests that reach the network.</param>
|
||||
/// <returns>The created client.</returns>
|
||||
private static HttpClient CreateClient(HttpMessageHandler innerHandler)
|
||||
{
|
||||
PublicHostValidationHandler handler = new(CreateValidator(), NullLogger<PublicHostValidationHandler>.Instance) { InnerHandler = innerHandler };
|
||||
return new HttpClient(handler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PublicHostValidator"/> that classifies <see cref="PRIVATE_HOST"/> as private and every other host name as public.
|
||||
/// </summary>
|
||||
/// <returns>The created validator.</returns>
|
||||
private static PublicHostValidator CreateValidator()
|
||||
{
|
||||
return new PublicHostValidator((host, cancellationToken) =>
|
||||
Task.FromResult<IPAddress[]>(string.Equals(host, PRIVATE_HOST, StringComparison.OrdinalIgnoreCase) ? [IPAddress.Parse("10.0.0.5")] : [s_publicAddress]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test HTTP message handler that answers every request with a successful response and records how many requests were sent to it.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
private sealed class StubHttpMessageHandler : HttpMessageHandler
|
||||
{
|
||||
private int _callCount;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of requests that were sent through the handler.
|
||||
/// </summary>
|
||||
public int CallCount => _callCount;
|
||||
|
||||
/// <summary>
|
||||
/// Sends the provided request, producing a successful response.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to send.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The response produced for the request.</returns>
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
Interlocked.Increment(ref _callCount);
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
|
||||
}
|
||||
}
|
||||
}
|
||||
+502
@@ -0,0 +1,502 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Networking;
|
||||
using Lumina.Infrastructure.Common.Networking;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Common.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PublicHostValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PublicHostValidatorTests
|
||||
{
|
||||
private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34");
|
||||
|
||||
[Theory]
|
||||
[InlineData("8.8.8.8")] // A public IPv4 address.
|
||||
[InlineData("1.1.1.1")] // A public IPv4 address.
|
||||
[InlineData("172.15.0.1")] // The address just below the private class B range.
|
||||
[InlineData("172.32.0.1")] // The address just above the private class B range.
|
||||
[InlineData("100.63.255.255")] // The address just below the carrier grade NAT range.
|
||||
[InlineData("100.128.0.1")] // The address just above the carrier grade NAT range.
|
||||
[InlineData("2606:4700:4700::1111")] // A public IPv6 address.
|
||||
[InlineData("[2606:4700:4700::1111]")] // A public IPv6 address, bracketed like a URI host.
|
||||
[InlineData("::ffff:93.184.216.34")] // An IPv4-mapped public IPv4 address.
|
||||
public async Task ValidateHostAsync_WhenTheHostIsAPublicAddress_ShouldReturnTrue(string host)
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved."));
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync(host, allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // An empty host.
|
||||
[InlineData(" ")] // Only white space.
|
||||
[InlineData("localhost")] // The loopback host name.
|
||||
[InlineData("LOCALHOST")] // The loopback host name, upper cased.
|
||||
[InlineData("127.0.0.1")] // The IPv4 loopback address.
|
||||
[InlineData("::1")] // The IPv6 loopback address.
|
||||
[InlineData("[::1]")] // The IPv6 loopback address, bracketed like a URI host.
|
||||
[InlineData("0.0.0.0")] // The unspecified IPv4 address.
|
||||
[InlineData("[::]")] // The unspecified IPv6 address.
|
||||
[InlineData("169.254.169.254")] // The link local cloud metadata endpoint.
|
||||
[InlineData("10.0.0.5")] // A private class A address.
|
||||
[InlineData("::ffff:10.0.0.5")] // A private class A address, in its IPv4-mapped IPv6 form.
|
||||
[InlineData("172.16.0.1")] // The lower bound of the private class B range.
|
||||
[InlineData("172.31.255.255")] // The upper bound of the private class B range.
|
||||
[InlineData("192.168.1.10")] // A private class C address.
|
||||
[InlineData("100.64.0.1")] // The lower bound of the carrier grade NAT range.
|
||||
[InlineData("100.127.255.255")] // The upper bound of the carrier grade NAT range.
|
||||
[InlineData("192.0.2.10")] // The TEST-NET-1 documentation range.
|
||||
[InlineData("198.18.0.1")] // The benchmarking range.
|
||||
[InlineData("198.51.100.10")] // The TEST-NET-2 documentation range.
|
||||
[InlineData("203.0.113.10")] // The TEST-NET-3 documentation range.
|
||||
[InlineData("224.0.0.1")] // The multicast range.
|
||||
[InlineData("240.0.0.1")] // The reserved range.
|
||||
[InlineData("255.255.255.255")] // The broadcast address.
|
||||
[InlineData("fc00::1")] // The IPv6 unique local range.
|
||||
[InlineData("fd00:ec2::254")] // The AWS IMDSv6 endpoint, which lives in a unique local range.
|
||||
[InlineData("fe80::1")] // The IPv6 link local range.
|
||||
[InlineData("2001:db8::1")] // The IPv6 documentation range.
|
||||
[InlineData("::127.0.0.1")] // An IPv4 compatible IPv6 address.
|
||||
[InlineData("64:ff9b:1::1")] // The local use NAT64 prefix.
|
||||
[InlineData("2002::1")] // The IPv6 6to4 range.
|
||||
[InlineData("64:ff9b::1")] // The IPv6 NAT64 prefix.
|
||||
[InlineData("100::1")] // The IPv6 discard only range.
|
||||
[InlineData("ff02::1")] // The IPv6 multicast range.
|
||||
public async Task ValidateHostAsync_WhenTheHostIsPrivateOrLocal_ShouldReturnFalse(string host)
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved."));
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync(host, allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostIsAnIPv4MappedPrivateAddress_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved."));
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("::ffff:10.0.0.5", allowedPrivateHost: "::ffff:10.0.0.5", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheHostNameResolvesToPublicAddresses_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [s_publicAddress, IPAddress.Parse("93.184.216.35")]);
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheHostNameResolvesToOnePrivateAddress_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheHostNameResolvesToBothPublicAndPrivateAddresses_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [s_publicAddress, IPAddress.Parse("192.168.1.10")]);
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("mixed.example.com", allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheHostNameCannotBeResolved_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(_ => throw new SocketException((int)SocketError.HostNotFound));
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("missing.example.com", allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheHostNameIsMalformed_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(_ => throw new ArgumentException("The host is malformed."));
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("malformed host", allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheHostNameResolvesToNoAddress_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(_ => []);
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("empty.example.com", allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenCancellationIsRequested_ShouldThrowOperationCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(_ => throw new OperationCanceledException());
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return sut.ValidateHostAsync("example.com", allowedPrivateHost: null, cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveEndPointsAsync_WhenThePublicHostNameResolvesToAddresses_ShouldReturnTheirEndPoints()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [s_publicAddress, s_publicAddress]);
|
||||
IPAddress expectedAddress = s_publicAddress;
|
||||
|
||||
// Act
|
||||
IReadOnlyList<IPEndPoint> result = await sut.ResolveEndPointsAsync("example.com", 443, allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
IPEndPoint endPoint = Assert.Single(result);
|
||||
Assert.Equal(expectedAddress, endPoint.Address);
|
||||
Assert.Equal(443, endPoint.Port);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveEndPointsAsync_WhenTheHostNameResolvesToOnePrivateAddress_ShouldThrow()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [s_publicAddress, IPAddress.Parse("10.0.0.5")]);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return sut.ResolveEndPointsAsync("mixed.example.com", 80, allowedPrivateHost: null, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveEndPointsAsync_WhenTheHostIsAnIPv4MappedIPv6Address_ShouldReturnItsIPv4EndPoint()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved."));
|
||||
IPAddress expectedAddress = IPAddress.Parse("93.184.216.34");
|
||||
|
||||
// Act
|
||||
IReadOnlyList<IPEndPoint> result = await sut.ResolveEndPointsAsync("::ffff:93.184.216.34", 443, allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
IPEndPoint endPoint = Assert.Single(result);
|
||||
Assert.Equal(expectedAddress, endPoint.Address);
|
||||
Assert.Equal(443, endPoint.Port);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveEndPointsAsync_WhenTheHostCannotBeResolved_ShouldThrow()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(_ => throw new SocketException((int)SocketError.HostNotFound));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return sut.ResolveEndPointsAsync("missing.example.com", 443, allowedPrivateHost: null, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<PublicHostResolutionException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveEndPointsAsync_WhenTheHostNameResolvesToNoAddress_ShouldThrow()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(_ => []);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return sut.ResolveEndPointsAsync("empty.example.com", 443, allowedPrivateHost: null, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<PublicHostResolutionException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToAPrivateAddress_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenAnotherHostResolvesToOnePrivateAddress_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("other.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostIsLocalhost_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("The loopback host name must not be resolved."));
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("localhost", allowedPrivateHost: "localhost", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostIsAnIdnNameAndTheConnectionUsesItsPunycodeSpelling_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("192.168.1.10")]);
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("xn--bcher-kva.example", allowedPrivateHost: "bücher.example", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToTheLinkLocalMetadataAddress_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("169.254.169.254")]);
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToAnIPv6UniqueLocalAddress_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("fc00::1")]);
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToTheAwsMetadataAddress_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("fd00:ec2::254")]);
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsAllowed);
|
||||
Assert.Equal(OutboundRequestRejectionReason.LinkLocalOrMetadataAddress, result.RejectionReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToTheAlibabaMetadataAddress_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("100.100.100.200")]);
|
||||
|
||||
// Act
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveEndPointsAsync_WhenTheAllowedPrivateHostResolvesToAPrivateAddress_ShouldReturnItsEndPoint()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
|
||||
IPAddress expectedAddress = IPAddress.Parse("10.0.0.5");
|
||||
|
||||
// Act
|
||||
IReadOnlyList<IPEndPoint> result = await sut.ResolveEndPointsAsync("internal.example.com", 8080, allowedPrivateHost: "internal.example.com", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
IPEndPoint endPoint = Assert.Single(result);
|
||||
Assert.Equal(expectedAddress, endPoint.Address);
|
||||
Assert.Equal(8080, endPoint.Port);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveEndPointsAsync_WhenAnotherHostResolvesToAPrivateAddress_ShouldThrow()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return sut.ResolveEndPointsAsync("other.example.com", 443, allowedPrivateHost: "internal.example.com", CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveEndPointsAsync_WhenTheAllowedPrivateHostResolvesToTheLinkLocalMetadataAddress_ShouldThrow()
|
||||
{
|
||||
// Arrange
|
||||
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("169.254.169.254")]);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return sut.ResolveEndPointsAsync("internal.example.com", 443, allowedPrivateHost: "internal.example.com", CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
|
||||
Assert.Equal(OutboundRequestRejectionReason.LinkLocalOrMetadataAddress, exception.RejectionReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheSameHostIsCheckedTwice_ShouldResolveItOnlyOnce()
|
||||
{
|
||||
// Arrange
|
||||
int resolutionCount = 0;
|
||||
PublicHostValidator sut = new((host, cancellationToken) =>
|
||||
{
|
||||
resolutionCount++;
|
||||
return Task.FromResult<IPAddress[]>([s_publicAddress]);
|
||||
});
|
||||
|
||||
// Act
|
||||
await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None);
|
||||
await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(1, resolutionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveEndPointsAsync_WhenTheHostWasAlreadyChecked_ShouldReuseTheResolution()
|
||||
{
|
||||
// Arrange
|
||||
int resolutionCount = 0;
|
||||
PublicHostValidator sut = new((host, cancellationToken) =>
|
||||
{
|
||||
resolutionCount++;
|
||||
return Task.FromResult<IPAddress[]>([s_publicAddress]);
|
||||
});
|
||||
|
||||
// Act
|
||||
await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None);
|
||||
await sut.ResolveEndPointsAsync("example.com", 443, allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(1, resolutionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateHostAsync_WhenTheHostCannotBeResolvedTwice_ShouldCacheTheFailureBriefly()
|
||||
{
|
||||
// Arrange
|
||||
int resolutionCount = 0;
|
||||
PublicHostValidator sut = new((host, cancellationToken) =>
|
||||
{
|
||||
resolutionCount++;
|
||||
throw new SocketException((int)SocketError.HostNotFound);
|
||||
});
|
||||
|
||||
// Act
|
||||
await sut.ValidateHostAsync("missing.example.com", allowedPrivateHost: null, CancellationToken.None);
|
||||
await sut.ValidateHostAsync("missing.example.com", allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(1, resolutionCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="PublicHostValidator"/> whose host name resolution is replaced by the provided resolver.
|
||||
/// </summary>
|
||||
/// <param name="addressResolver">The resolver that produces the addresses of a host name.</param>
|
||||
/// <returns>The created validator.</returns>
|
||||
private static PublicHostValidator CreateValidator(Func<string, IPAddress[]> addressResolver)
|
||||
{
|
||||
return new PublicHostValidator((host, cancellationToken) => Task.FromResult(addressResolver(host)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user