mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Hardens outbound host validation against SSRF
- resolves host names and validates every address, with a connect callback that pins the checked address - applies the guard to every outbound HTTP client, with distinct rejection and resolution failures and warning logs - scopes the MusicBrainz private base URL permission to the configured host and blocks link local and cloud metadata endpoints - keeps provider redirects bounded and strips credentials and hop-by-hop headers on cross-origin redirects - adds unit, security, and end-to-end coverage, and updates the manual
This commit is contained in:
1 parent
ecdb39cc6a
commit
24af00579c
28 files changed
+2977
-162
No files matched your search
+51
@@ -18,6 +18,8 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.MediaLibrary.Artwork;
|
||||
@@ -65,6 +67,55 @@ public class BookArtworkServiceSecurityTests
|
||||
_sut = scope.ServiceProvider.GetRequiredService<IBookArtworkService>();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[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://[::1]/cover.jpg")] // The IPv6 loopback address.
|
||||
public async Task SaveBookArtworkAsync_WhenRemoteArtworkPointsAtAPrivateAddress_ShouldNotDownloadIt(string remoteUrl)
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(
|
||||
Guid.NewGuid(),
|
||||
Guid.NewGuid(),
|
||||
"Library",
|
||||
"Author",
|
||||
"Title",
|
||||
_artworkDtoFixture.Create(remoteUrl: remoteUrl),
|
||||
cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenRemoteArtworkPointsAtTheLoopbackAddress_ShouldNotConnectToIt()
|
||||
{
|
||||
// Arrange
|
||||
using TcpListener listener = new(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(
|
||||
Guid.NewGuid(),
|
||||
Guid.NewGuid(),
|
||||
"Library",
|
||||
"Author",
|
||||
"Title",
|
||||
_artworkDtoFixture.Create(remoteUrl: $"http://127.0.0.1:{port}/cover.jpg"),
|
||||
cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
// The real dependency injection container must reject the address before any connection is made, so nothing reaches the listener.
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.False(listener.Pending());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenLocalArtworkIsAReparsePoint_ShouldRejectIt()
|
||||
{
|
||||
|
||||
+72
@@ -12,6 +12,7 @@ using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
|
||||
using Lumina.Infrastructure.Common.DependencyInjection;
|
||||
using Lumina.Infrastructure.Common.Networking;
|
||||
using Lumina.Infrastructure.Core.Authorization.Policies.ConsumptionActivity;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
@@ -20,8 +21,10 @@ using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net.Http;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Common.DependencyInjection;
|
||||
@@ -73,6 +76,27 @@ public class InfrastructureLayerServicesTests
|
||||
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IValidator<Lumina.Infrastructure.Common.Models.DTO.Configuration.JwtSettingsDto>));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddInfrastructureLayerServices_WhenCalled_ShouldGuardEveryOutboundHttpClientWithThePublicHostChecks()
|
||||
{
|
||||
// Arrange
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
IConfiguration configuration = CreateConfiguration();
|
||||
services.AddInfrastructureLayerServices(configuration);
|
||||
// A plugin registers its typed client after the infrastructure layer, so the defaults must reach it too.
|
||||
services.AddHttpClient("plugin-client");
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
IHttpMessageHandlerFactory httpMessageHandlerFactory = serviceProvider.GetRequiredService<IHttpMessageHandlerFactory>();
|
||||
|
||||
// Act
|
||||
using HttpMessageHandler pluginClientHandler = httpMessageHandlerFactory.CreateHandler("plugin-client");
|
||||
using HttpMessageHandler artworkClientHandler = httpMessageHandlerFactory.CreateHandler(NamedHttpClients.ARTWORK_DOWNLOAD);
|
||||
|
||||
// Assert
|
||||
AssertUsesThePublicHostGuards(pluginClientHandler);
|
||||
AssertUsesThePublicHostGuards(artworkClientHandler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an in-memory configuration pointing the plugins directory to a non-existent folder, so no plugin assemblies are loaded.
|
||||
/// </summary>
|
||||
@@ -85,4 +109,52 @@ public class InfrastructureLayerServicesTests
|
||||
};
|
||||
return new ConfigurationBuilder().AddInMemoryCollection(configurationValues).Build();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the provided handler pipeline validates the host of every request, follows redirects only to public HTTPS hosts, and connects only to an
|
||||
/// address checked to be public.
|
||||
/// </summary>
|
||||
/// <param name="handler">The handler pipeline to check.</param>
|
||||
private static void AssertUsesThePublicHostGuards(HttpMessageHandler handler)
|
||||
{
|
||||
List<DelegatingHandler> delegatingHandlers = GetDelegatingHandlers(handler);
|
||||
int validationIndex = delegatingHandlers.FindIndex(delegatingHandler => delegatingHandler is PublicHostValidationHandler);
|
||||
int redirectIndex = delegatingHandlers.FindIndex(delegatingHandler => delegatingHandler is PublicHostRedirectHandler);
|
||||
// The validation handler must run before the redirect handler, because the redirect handler follows a redirect below the validation handler.
|
||||
Assert.True(validationIndex >= 0, "The public host validation handler must be part of the outbound pipeline.");
|
||||
Assert.True(redirectIndex > validationIndex, "The public host validation handler must run before the public host redirect handler.");
|
||||
SocketsHttpHandler primaryHandler = Assert.IsType<SocketsHttpHandler>(GetPrimaryHandler(handler));
|
||||
Assert.False(primaryHandler.AllowAutoRedirect);
|
||||
Assert.NotNull(primaryHandler.ConnectCallback);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the delegating handlers of the provided handler pipeline, from the outermost to the innermost one.
|
||||
/// </summary>
|
||||
/// <param name="handler">The handler pipeline to walk.</param>
|
||||
/// <returns>The delegating handlers of the pipeline.</returns>
|
||||
private static List<DelegatingHandler> GetDelegatingHandlers(HttpMessageHandler handler)
|
||||
{
|
||||
List<DelegatingHandler> delegatingHandlers = [];
|
||||
HttpMessageHandler currentHandler = handler;
|
||||
while (currentHandler is DelegatingHandler delegatingHandler)
|
||||
{
|
||||
delegatingHandlers.Add(delegatingHandler);
|
||||
currentHandler = delegatingHandler.InnerHandler ?? throw new InvalidOperationException("The delegating handler has no inner handler.");
|
||||
}
|
||||
return delegatingHandlers;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the primary, non delegating handler of the provided handler pipeline.
|
||||
/// </summary>
|
||||
/// <param name="handler">The handler pipeline to walk.</param>
|
||||
/// <returns>The primary handler of the pipeline.</returns>
|
||||
private static HttpMessageHandler GetPrimaryHandler(HttpMessageHandler handler)
|
||||
{
|
||||
HttpMessageHandler currentHandler = handler;
|
||||
while (currentHandler is DelegatingHandler delegatingHandler)
|
||||
currentHandler = delegatingHandler.InnerHandler ?? throw new InvalidOperationException("The delegating handler has no inner handler.");
|
||||
return currentHandler;
|
||||
}
|
||||
}
|
||||
+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)));
|
||||
}
|
||||
}
|
||||
+280
-43
@@ -1,10 +1,14 @@
|
||||
#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
|
||||
@@ -17,48 +21,12 @@ namespace Lumina.Infrastructure.UnitTests.Common.Networking;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PublicHostRedirectHandlerTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheInitialRequestHostIsPublic_ShouldSendTheRequest()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) => new HttpResponseMessage(HttpStatusCode.OK));
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
private const string PRIVATE_HOST = "internal.example.com";
|
||||
|
||||
// Act
|
||||
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_WhenTheInitialRequestHostIsPrivateOrLocal_ShouldThrowAndNotSendTheRequest(string url)
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) => new HttpResponseMessage(HttpStatusCode.OK));
|
||||
using HttpClient client = CreateClient(innerHandler);
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetAsync(url);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
Assert.Equal(0, innerHandler.CallCount);
|
||||
}
|
||||
private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34");
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenTheInitialRequestRedirectsToAPublicHttpsHost_ShouldFollowIt()
|
||||
public async Task SendAsync_WhenTheResponseRedirectsToAPublicHttpsHost_ShouldFollowIt()
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
@@ -82,6 +50,29 @@ public class PublicHostRedirectHandlerTests
|
||||
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.
|
||||
@@ -89,7 +80,7 @@ public class PublicHostRedirectHandlerTests
|
||||
[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_WhenTheInitialRequestRedirectsToADisallowedTarget_ShouldThrow(string location)
|
||||
public async Task SendAsync_WhenTheResponseRedirectsToADisallowedTarget_ShouldThrow(string location)
|
||||
{
|
||||
// Arrange
|
||||
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
|
||||
@@ -107,7 +98,55 @@ public class PublicHostRedirectHandlerTests
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -130,11 +169,207 @@ public class PublicHostRedirectHandlerTests
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
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>
|
||||
@@ -142,7 +377,9 @@ public class PublicHostRedirectHandlerTests
|
||||
/// <returns>The created client.</returns>
|
||||
private static HttpClient CreateClient(HttpMessageHandler innerHandler)
|
||||
{
|
||||
PublicHostRedirectHandler handler = new() { InnerHandler = 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);
|
||||
}
|
||||
|
||||
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
#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>>();
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
+452
-8
@@ -1,6 +1,14 @@
|
||||
#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;
|
||||
@@ -11,21 +19,28 @@ namespace Lumina.Infrastructure.UnitTests.Common.Networking;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PublicHostValidatorTests
|
||||
{
|
||||
private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34");
|
||||
|
||||
[Theory]
|
||||
[InlineData("coverartarchive.org")] // A public host name.
|
||||
[InlineData("example.com")] // A public host name.
|
||||
[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.
|
||||
public void IsPublicHost_WhenTheHostIsPublic_ShouldReturnTrue(string host)
|
||||
[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
|
||||
bool result = PublicHostValidator.IsPublicHost(host);
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync(host, allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
Assert.True(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -40,19 +55,448 @@ public class PublicHostValidatorTests
|
||||
[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.
|
||||
public void IsPublicHost_WhenTheHostIsPrivateOrLocal_ShouldReturnFalse(string host)
|
||||
[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
|
||||
bool result = PublicHostValidator.IsPublicHost(host);
|
||||
PublicHostValidationResult result = await sut.ValidateHostAsync(host, allowedPrivateHost: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
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)));
|
||||
}
|
||||
}
|
||||
+28
-8
@@ -129,22 +129,23 @@ public class CoverArtArchiveServicesTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddCoverArtArchiveArtworkProvider_WhenTheClientIsResolved_ShouldDisableAutomaticRedirectsOnItsPrimaryHandler()
|
||||
public void AddCoverArtArchiveArtworkProvider_WhenTheHostConfiguresHttpClientDefaults_ShouldKeepThePrimaryHandlerOfTheHost()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
StubPrimaryHttpMessageHandler hostPrimaryHandler = new();
|
||||
services.ConfigureHttpClientDefaults(builder => builder.ConfigurePrimaryHttpMessageHandler(() => hostPrimaryHandler));
|
||||
services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid());
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
using (IServiceScope scope = serviceProvider.CreateScope())
|
||||
{
|
||||
// Act
|
||||
CoverArtArchiveHttpClient client = scope.ServiceProvider.GetRequiredService<CoverArtArchiveHttpClient>();
|
||||
HttpClientHandler primaryHandler = GetPrimaryHandler(client);
|
||||
|
||||
// Assert
|
||||
// Automatic redirects must stay disabled on the primary handler, otherwise it would follow a server controlled redirect on its own,
|
||||
// before the client can check the target host against the Cover Art Archive and the Internet Archive, bypassing that control.
|
||||
Assert.False(primaryHandler.AllowAutoRedirect);
|
||||
// The host owns the primary handler, because it is what disables automatic redirects and connects only to addresses validated to be public.
|
||||
// The plugin must not replace it, otherwise it would follow a server controlled redirect on its own and bypass the guard of the host.
|
||||
Assert.Same(hostPrimaryHandler, GetPrimaryHandler(client));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,14 +171,14 @@ public class CoverArtArchiveServicesTests
|
||||
/// Gets the primary HTTP message handler of the provided client, unwrapping the delegating handlers built by the HTTP client factory around it.
|
||||
/// </summary>
|
||||
/// <param name="client">The client whose primary handler is retrieved.</param>
|
||||
/// <returns>The primary HTTP client handler of the client.</returns>
|
||||
private static HttpClientHandler GetPrimaryHandler(CoverArtArchiveHttpClient client)
|
||||
/// <returns>The primary HTTP message handler of the client.</returns>
|
||||
private static HttpMessageHandler GetPrimaryHandler(CoverArtArchiveHttpClient client)
|
||||
{
|
||||
HttpClient httpClient = (HttpClient)GetFieldOfType(client, typeof(HttpClient))!;
|
||||
HttpMessageHandler? handler = (HttpMessageHandler?)GetFieldOfType(httpClient, typeof(HttpMessageHandler));
|
||||
while (handler is DelegatingHandler delegatingHandler)
|
||||
handler = delegatingHandler.InnerHandler;
|
||||
return Assert.IsType<HttpClientHandler>(handler);
|
||||
return handler ?? throw new InvalidOperationException("The HTTP client has no primary handler.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -202,4 +203,23 @@ public class CoverArtArchiveServicesTests
|
||||
}
|
||||
throw new InvalidOperationException($"No field assignable to {fieldType} was found on {instance.GetType()} or its base types.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Primary HTTP message handler that identifies the handler the host configured, so a test can verify that the plugin does not replace it.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
private sealed class StubPrimaryHttpMessageHandler : HttpMessageHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// Sends the provided request. The tests never send a request through this handler.
|
||||
/// </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 of the request.</returns>
|
||||
/// <exception cref="NotSupportedException">Always thrown, because this handler only identifies the handler configured by the host.</exception>
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
+52
@@ -1,4 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Contracts.Common.Http;
|
||||
using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.CoverArtArchive.Core;
|
||||
using Lumina.Plugins.CoverArtArchive.Core.Api;
|
||||
@@ -54,6 +55,20 @@ public class CoverArtArchiveHttpClientTests
|
||||
Assert.Equal("coverartarchive.org", handler.Requests[0].RequestUri!.Host);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReleaseArtworkAsync_WhenCalled_ShouldOptOutOfTheHostRedirectHandling()
|
||||
{
|
||||
// Arrange
|
||||
(CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient();
|
||||
|
||||
// Act
|
||||
await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(handler.Requests[0].Options.TryGetValue(OutboundRequestOptions.FollowRedirects, out bool shouldFollowRedirects));
|
||||
Assert.False(shouldFollowRedirects);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReleaseGroupArtworkAsync_WhenTheReleaseGroupHasArtwork_ShouldDeserializeIt()
|
||||
{
|
||||
@@ -298,6 +313,43 @@ public class CoverArtArchiveHttpClientTests
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReleaseArtworkAsync_WhenTheHostRejectsTheRequest_ShouldNotRetry()
|
||||
{
|
||||
// Arrange
|
||||
(CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient(
|
||||
(request, callIndex) => throw new HttpRequestException(HttpRequestError.ConfigurationLimitExceeded, "Rejected."));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReleaseArtworkAsync_WhenTheConnectPolicyWrapsTheRejection_ShouldNotRetry()
|
||||
{
|
||||
// Arrange
|
||||
HttpRequestException rejection = new(HttpRequestError.ConfigurationLimitExceeded, "Rejected.");
|
||||
(CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient(
|
||||
(request, callIndex) => throw new HttpRequestException(HttpRequestError.ConnectionError, "Connection error.", rejection));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReleaseArtworkAsync_WhenEveryAttemptFails_ShouldThrowAfterExhaustingTheRetries()
|
||||
{
|
||||
|
||||
+78
-1
@@ -2,13 +2,14 @@
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Lumina.Plugins.MusicBrainz.Common.DependencyInjection;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.MusicBrainz.Core;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Api;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Settings;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -127,6 +128,26 @@ public class MusicBrainzServicesTests
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddMusicBrainzMetadataProviders_WhenTheHostConfiguresHttpClientDefaults_ShouldKeepThePrimaryHandlerOfTheHost()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
StubPrimaryHttpMessageHandler hostPrimaryHandler = new();
|
||||
services.ConfigureHttpClientDefaults(builder => builder.ConfigurePrimaryHttpMessageHandler(() => hostPrimaryHandler));
|
||||
services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid());
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
using (IServiceScope scope = serviceProvider.CreateScope())
|
||||
{
|
||||
// Act
|
||||
MusicBrainzHttpClient client = scope.ServiceProvider.GetRequiredService<MusicBrainzHttpClient>();
|
||||
|
||||
// Assert
|
||||
// The host owns the primary handler, because it is what validates and pins the address of every connection. The plugin must not replace it.
|
||||
Assert.Same(hostPrimaryHandler, GetPrimaryHandler(client));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddMusicBrainzMetadataProviders_WhenCalledTwice_ShouldNotDuplicateTheTryAddServices()
|
||||
{
|
||||
@@ -144,4 +165,60 @@ public class MusicBrainzServicesTests
|
||||
Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzResponseCache));
|
||||
Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzSettingsProvider));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the primary HTTP message handler of the provided client, unwrapping the delegating handlers built by the HTTP client factory around it.
|
||||
/// </summary>
|
||||
/// <param name="client">The client whose primary handler is retrieved.</param>
|
||||
/// <returns>The primary HTTP message handler of the client.</returns>
|
||||
private static HttpMessageHandler GetPrimaryHandler(MusicBrainzHttpClient client)
|
||||
{
|
||||
HttpClient httpClient = (HttpClient)GetFieldOfType(client, typeof(HttpClient))!;
|
||||
HttpMessageHandler? handler = (HttpMessageHandler?)GetFieldOfType(httpClient, typeof(HttpMessageHandler));
|
||||
while (handler is DelegatingHandler delegatingHandler)
|
||||
handler = delegatingHandler.InnerHandler;
|
||||
return handler ?? throw new InvalidOperationException("The HTTP client has no primary handler.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the first field, declared on the provided <paramref name="instance"/> or any of its base types, whose type is assignable to
|
||||
/// <paramref name="fieldType"/>, without relying on the field name, so the test keeps working across runtime versions.
|
||||
/// </summary>
|
||||
/// <param name="instance">The instance whose field is read.</param>
|
||||
/// <param name="fieldType">The type the field must be assignable to.</param>
|
||||
/// <returns>The value of the found field.</returns>
|
||||
/// <exception cref="InvalidOperationException">Thrown when no field assignable to <paramref name="fieldType"/> is found.</exception>
|
||||
private static object GetFieldOfType(object instance, Type fieldType)
|
||||
{
|
||||
Type? type = instance.GetType();
|
||||
while (type is not null)
|
||||
{
|
||||
FieldInfo? field = type
|
||||
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly)
|
||||
.FirstOrDefault(candidate => fieldType.IsAssignableFrom(candidate.FieldType));
|
||||
if (field is not null)
|
||||
return field.GetValue(instance)!;
|
||||
type = type.BaseType;
|
||||
}
|
||||
throw new InvalidOperationException($"No field assignable to {fieldType} was found on {instance.GetType()} or its base types.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Primary HTTP message handler that identifies the handler the host configured, so a test can verify that the plugin does not replace it.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
private sealed class StubPrimaryHttpMessageHandler : HttpMessageHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// Sends the provided request. The tests never send a request through this handler.
|
||||
/// </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 of the request.</returns>
|
||||
/// <exception cref="NotSupportedException">Always thrown, because this handler only identifies the handler configured by the host.</exception>
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
+156
-3
@@ -1,4 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Contracts.Common.Http;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.MusicBrainz.Core;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Api;
|
||||
@@ -181,6 +182,115 @@ public class MusicBrainzHttpClientTests
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheServiceRedirectsToTheSameHost_ShouldFollowIt()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero,
|
||||
(request, callIndex) => callIndex == 1 ? Redirect("http://localhost/ws/2/redirected") : Json(RECORDING_JSON));
|
||||
|
||||
// Act
|
||||
MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
Assert.True(handler.Requests[1].Options.TryGetValue(OutboundRequestOptions.FollowRedirects, out bool shouldFollowRedirects));
|
||||
Assert.False(shouldFollowRedirects);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheServiceRedirectsToAnotherHost_ShouldThrowWithoutFollowingIt()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero,
|
||||
(request, callIndex) => Redirect("http://other.example/ws/2/redirected"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheServiceDowngradesHttpsToPlainHttp_ShouldThrowWithoutFollowingIt()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("https://musicbrainz.org/ws/2/", TimeSpan.Zero,
|
||||
(request, callIndex) => Redirect("http://musicbrainz.org/ws/2/redirected"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheServiceRedirectsTooManyTimes_ShouldThrow()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero,
|
||||
(request, callIndex) => Redirect("http://localhost/ws/2/loop"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
// The initial request plus the maximum number of followed redirects are sent before the loop is detected.
|
||||
Assert.Equal(6, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheHostRejectsTheRequest_ShouldNotRetry()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero,
|
||||
(request, callIndex) => throw new HttpRequestException(HttpRequestError.ConfigurationLimitExceeded, "Rejected."));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenTheConnectPolicyWrapsTheRejection_ShouldNotRetry()
|
||||
{
|
||||
// Arrange
|
||||
HttpRequestException rejection = new(HttpRequestError.ConfigurationLimitExceeded, "Rejected.");
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero,
|
||||
(request, callIndex) => throw new HttpRequestException(HttpRequestError.ConnectionError, "Connection error.", rejection));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenEveryAttemptFails_ShouldThrowAfterExhaustingTheRetries()
|
||||
{
|
||||
@@ -243,6 +353,33 @@ public class MusicBrainzHttpClientTests
|
||||
Assert.Equal("Custom/9.9", handler.Requests[0].Headers.UserAgent.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenAPrivateBaseUrlIsAllowed_ShouldScopeThePermissionToTheBaseHost()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, doesAllowPrivateBaseUrl: true);
|
||||
|
||||
// Act
|
||||
await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(handler.Requests[0].Options.TryGetValue(OutboundRequestOptions.AllowedPrivateHost, out string? allowedPrivateHost));
|
||||
Assert.Equal("localhost", allowedPrivateHost);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecordingAsync_WhenAPrivateBaseUrlIsNotAllowed_ShouldNotAllowTheRequestToReachPrivateEndPoints()
|
||||
{
|
||||
// Arrange
|
||||
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, doesAllowPrivateBaseUrl: false);
|
||||
|
||||
// Act
|
||||
await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(handler.Requests[0].Options.TryGetValue(OutboundRequestOptions.AllowedPrivateHost, out string? _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAsync_WhenTheArtistExists_ShouldDeserializeIt()
|
||||
{
|
||||
@@ -532,16 +669,18 @@ public class MusicBrainzHttpClientTests
|
||||
/// <param name="minimumRequestInterval">The minimum request interval configured for the client.</param>
|
||||
/// <param name="responseFactory">Optional. The factory that produces the response of a request.</param>
|
||||
/// <param name="contactEmail">Optional. The contact email configured for the client.</param>
|
||||
/// <param name="doesAllowPrivateBaseUrl">Optional. Whether the base URL may point at a private or local host.</param>
|
||||
/// <returns>The created client, its stub handler and the underlying HTTP client.</returns>
|
||||
private (MusicBrainzHttpClient Client, StubHttpMessageHandler Handler, HttpClient HttpClient) CreateClient(
|
||||
string baseUrl,
|
||||
TimeSpan minimumRequestInterval,
|
||||
Func<HttpRequestMessage, int, HttpResponseMessage>? responseFactory = null,
|
||||
string? contactEmail = null)
|
||||
string? contactEmail = null,
|
||||
bool? doesAllowPrivateBaseUrl = null)
|
||||
{
|
||||
StubHttpMessageHandler handler = new(responseFactory ?? ((request, callIndex) => Json(RECORDING_JSON)));
|
||||
HttpClient httpClient = new(handler);
|
||||
MusicBrainzHttpClient client = CreateMusicBrainzHttpClient(httpClient, baseUrl, minimumRequestInterval, contactEmail);
|
||||
MusicBrainzHttpClient client = CreateMusicBrainzHttpClient(httpClient, baseUrl, minimumRequestInterval, contactEmail, doesAllowPrivateBaseUrl);
|
||||
return (client, handler, httpClient);
|
||||
}
|
||||
|
||||
@@ -552,11 +691,13 @@ public class MusicBrainzHttpClientTests
|
||||
/// <param name="baseUrl">The base URL of the MusicBrainz web service the client points to.</param>
|
||||
/// <param name="minimumRequestInterval">The minimum request interval configured for the client.</param>
|
||||
/// <param name="contactEmail">Optional. The contact email configured for the client.</param>
|
||||
/// <param name="doesAllowPrivateBaseUrl">Optional. Whether the base URL may point at a private or local host.</param>
|
||||
/// <returns>The created client.</returns>
|
||||
private MusicBrainzHttpClient CreateMusicBrainzHttpClient(HttpClient httpClient, string baseUrl, TimeSpan minimumRequestInterval, string? contactEmail)
|
||||
private MusicBrainzHttpClient CreateMusicBrainzHttpClient(HttpClient httpClient, string baseUrl, TimeSpan minimumRequestInterval, string? contactEmail, bool? doesAllowPrivateBaseUrl = null)
|
||||
{
|
||||
MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create(
|
||||
baseUrl: baseUrl,
|
||||
doesAllowPrivateBaseUrl: doesAllowPrivateBaseUrl,
|
||||
userAgent: "Lumina-Test/1.0",
|
||||
contactEmail: contactEmail,
|
||||
includeContactEmail: contactEmail is not null,
|
||||
@@ -575,4 +716,16 @@ public class MusicBrainzHttpClientTests
|
||||
{
|
||||
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a temporary redirect response to the provided location.
|
||||
/// </summary>
|
||||
/// <param name="location">The absolute location of the redirect target.</param>
|
||||
/// <returns>The created response.</returns>
|
||||
private static HttpResponseMessage Redirect(string location)
|
||||
{
|
||||
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
|
||||
redirect.Headers.Location = new Uri(location);
|
||||
return redirect;
|
||||
}
|
||||
}
|
||||
+31
@@ -111,13 +111,27 @@ public class MusicBrainzSettingsProviderTests
|
||||
[Theory]
|
||||
[InlineData("http://127.0.0.1/ws/2/")] // IPv4 loopback.
|
||||
[InlineData("http://localhost/ws/2/")] // Loopback host name.
|
||||
[InlineData("http://localhost./ws/2/")] // Loopback host name with a trailing dot.
|
||||
[InlineData("http://[::1]/ws/2/")] // IPv6 loopback.
|
||||
[InlineData("http://169.254.169.254/latest/meta-data/")] // Link local cloud metadata endpoint.
|
||||
[InlineData("http://10.0.0.5/ws/2/")] // Private class A range.
|
||||
[InlineData("http://172.16.0.1/ws/2/")] // Private class B range.
|
||||
[InlineData("http://[::ffff:10.0.0.5]/ws/2/")] // An IPv4-mapped private address.
|
||||
[InlineData("http://192.168.1.10/ws/2/")] // Private class C range.
|
||||
[InlineData("http://0.0.0.0/ws/2/")] // Unspecified address.
|
||||
[InlineData("http://[fc00::1]/ws/2/")] // IPv6 unique local range.
|
||||
[InlineData("http://[fd00:ec2::254]/ws/2/")] // The AWS IMDSv6 endpoint, which lives in a unique local range.
|
||||
[InlineData("http://198.18.0.1/ws/2/")] // IPv4 benchmarking range.
|
||||
[InlineData("http://198.51.100.10/ws/2/")] // TEST-NET-2 documentation range.
|
||||
[InlineData("http://203.0.113.10/ws/2/")] // TEST-NET-3 documentation range.
|
||||
[InlineData("http://224.0.0.1/ws/2/")] // IPv4 multicast range.
|
||||
[InlineData("http://[ff02::1]/ws/2/")] // IPv6 multicast range.
|
||||
[InlineData("http://[2001:db8::1]/ws/2/")] // IPv6 documentation range.
|
||||
[InlineData("http://[::127.0.0.1]/ws/2/")] // IPv4 compatible IPv6 address.
|
||||
[InlineData("http://[64:ff9b:1::1]/ws/2/")] // Local use NAT64 prefix.
|
||||
[InlineData("http://[2002::1]/ws/2/")] // IPv6 6to4 range.
|
||||
[InlineData("http://[64:ff9b::1]/ws/2/")] // IPv6 NAT64 prefix.
|
||||
[InlineData("http://[100::1]/ws/2/")] // IPv6 discard only range.
|
||||
public async Task GetAsync_WhenThePersistedBaseUrlPointsAtALocalOrPrivateHost_ShouldKeepTheDefaultBaseUrl(string baseUrl)
|
||||
{
|
||||
// Arrange
|
||||
@@ -137,6 +151,7 @@ public class MusicBrainzSettingsProviderTests
|
||||
[InlineData("http://192.168.1.10/ws/2/")] // Private class C range, a typical self hosted mirror.
|
||||
[InlineData("http://localhost/ws/2/")] // Loopback host name.
|
||||
[InlineData("http://[fc00::1]/ws/2/")] // IPv6 unique local range.
|
||||
[InlineData("http://[::ffff:10.0.0.5]/ws/2/")] // An IPv4-mapped private address.
|
||||
public async Task GetAsync_WhenPrivateBaseUrlsAreExplicitlyAllowed_ShouldApplyThem(string baseUrl)
|
||||
{
|
||||
// Arrange
|
||||
@@ -193,6 +208,22 @@ public class MusicBrainzSettingsProviderTests
|
||||
Assert.Equal("http://mirror.example/ws/2/", result.BaseUrl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenThePersistedBaseUrlIsAnIPv4MappedPublicAddress_ShouldApplyIt()
|
||||
{
|
||||
// Arrange
|
||||
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
|
||||
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
|
||||
new Dictionary<string, string> { [MusicBrainzSettingsKeys.BASE_URL] = "http://[::ffff:93.184.216.34]/ws/2/" });
|
||||
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
|
||||
|
||||
// Act
|
||||
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("http://[::ffff:93.184.216.34]/ws/2/", result.BaseUrl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenThePersistedBaseUrlIsNull_ShouldKeepTheDefaultBaseUrl()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user