Renames project paths from Lumina to Nemera

This commit is contained in:
BinaryAlley committed 2026-11-27 15:34:43 +02:00
1 parent ce6fddb4c9
commit 0f659a4877
6450 files changed

No files matched your search

@@ -0,0 +1,160 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
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;
using Lumina.Infrastructure.Core.Time;
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;
/// <summary>
/// Contains unit tests for the <see cref="InfrastructureLayerServices"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class InfrastructureLayerServicesTests
{
[Fact]
public void AddInfrastructureLayerServices_WhenCalled_ShouldRegisterCoreInfrastructureServices()
{
// Arrange
IServiceCollection services = new ServiceCollection();
IConfiguration configuration = CreateConfiguration();
// Act
services.AddInfrastructureLayerServices(configuration);
// Assert
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IFileHashService) && descriptor.ImplementationType == typeof(FileHashService));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDateTimeProvider) && descriptor.ImplementationType == typeof(DateTimeProvider));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPlaybackFormatService) && descriptor.ImplementationType == typeof(PlaybackFormatService));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPluginManager));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPluginSettingsStore));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDomainEventsQueue));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDomainEventPublisher));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IMediaLibrariesScanQueue));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IMediaLibrariesScanCancellationTracker));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IMediaLibraryScanProgressNotifier));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IHostedService));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IConsumptionActivityAccessPolicy) && descriptor.ImplementationType == typeof(ConsumptionActivityAccessPolicy));
}
[Fact]
public void AddInfrastructureLayerServices_WhenCalled_ShouldRegisterAllValidatorsFromTheAssembly()
{
// Arrange
IServiceCollection services = new ServiceCollection();
IConfiguration configuration = CreateConfiguration();
// Act
services.AddInfrastructureLayerServices(configuration);
// Assert
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IValidator<PluginsSettingsDto>));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IValidator<Lumina.Infrastructure.Common.Models.DTO.Configuration.CorsSettingsDto>));
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>
/// <returns>The created configuration.</returns>
private static IConfiguration CreateConfiguration()
{
Dictionary<string, string?> configurationValues = new()
{
[$"{PluginsSettingsDto.SECTION_NAME}:Directory"] = "non-existent-plugins-directory"
};
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;
}
}
@@ -0,0 +1,194 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Infrastructure.Common.DomainEvents;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.DomainEvents;
/// <summary>
/// Contains unit tests for the <see cref="DomainEventPublisher"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DomainEventPublisherTests
{
public sealed record TestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent;
public sealed record NestedTestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent;
private sealed class RecordingDomainEventHandler : IDomainEventHandler<TestDomainEvent>
{
private readonly List<string> _callLog;
private readonly string _handlerName;
public RecordingDomainEventHandler(List<string> callLog, string handlerName)
{
_callLog = callLog;
_handlerName = handlerName;
}
public ValueTask HandleAsync(TestDomainEvent domainEvent, CancellationToken cancellationToken)
{
_callLog.Add(_handlerName);
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Creates a publisher wired to a fresh service provider, optionally registering additional services.
/// </summary>
/// <param name="configureServices">Optional action used to register additional services into the provider.</param>
/// <returns>A domain event publisher resolved from the created provider.</returns>
private static IDomainEventPublisher CreatePublisher(Action<IServiceCollection>? configureServices = null)
{
IServiceCollection services = new ServiceCollection();
services.AddScoped<IDomainEventPublisher, DomainEventPublisher>();
configureServices?.Invoke(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
return serviceProvider.GetRequiredService<IDomainEventPublisher>();
}
/// <summary>
/// Creates a valid instance of <see cref="TestDomainEvent"/>.
/// </summary>
/// <returns>The created domain event.</returns>
private static TestDomainEvent CreateTestDomainEvent()
{
return new TestDomainEvent(Guid.NewGuid(), DateTime.UtcNow);
}
/// <summary>
/// Creates a valid instance of <see cref="NestedTestDomainEvent"/>.
/// </summary>
/// <returns>The created domain event.</returns>
private static NestedTestDomainEvent CreateNestedTestDomainEvent()
{
return new NestedTestDomainEvent(Guid.NewGuid(), DateTime.UtcNow);
}
[Fact]
public async Task Publish_WhenHandlersAreRegistered_ShouldInvokeAllHandlersInOrder()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
List<string> callLog = [];
IDomainEventPublisher publisher = CreatePublisher(services =>
{
services.AddScoped<IDomainEventHandler<TestDomainEvent>>(_ => new RecordingDomainEventHandler(callLog, "first"));
services.AddScoped<IDomainEventHandler<TestDomainEvent>>(_ => new RecordingDomainEventHandler(callLog, "second"));
});
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
Assert.Equal(["first", "second"], callLog);
}
[Fact]
public async Task Publish_WhenNoHandlersAreRegisteredForTheEventType_ShouldNotThrow()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
IDomainEventPublisher publisher = CreatePublisher();
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
// Reaching this point without an exception means the publish was a no-op, as expected.
}
[Fact]
public async Task Publish_WhenOnlyAnotherEventTypeHasHandlers_ShouldNotInvokeThem()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
IDomainEventHandler<NestedTestDomainEvent> nestedHandler = Substitute.For<IDomainEventHandler<NestedTestDomainEvent>>();
IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped(_ => nestedHandler));
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
await nestedHandler.DidNotReceive().HandleAsync(Arg.Any<NestedTestDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Publish_WhenHandlerThrows_ShouldPropagateTheException()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
InvalidOperationException expectedException = new("Test exception");
IDomainEventHandler<TestDomainEvent> handler = Substitute.For<IDomainEventHandler<TestDomainEvent>>();
handler.HandleAsync(Arg.Any<TestDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(callInfo => throw expectedException);
IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped<IDomainEventHandler<TestDomainEvent>>(_ => handler));
// Act
InvalidOperationException result = await Assert.ThrowsAsync<InvalidOperationException>(
() => publisher.PublishAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Same(expectedException, result);
}
[Fact]
public async Task Publish_WhenHandlerPublishesAnotherEvent_ShouldInvokeNestedHandlers()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
NestedTestDomainEvent nestedDomainEvent = CreateNestedTestDomainEvent();
IDomainEventHandler<TestDomainEvent> handler = Substitute.For<IDomainEventHandler<TestDomainEvent>>();
IDomainEventHandler<NestedTestDomainEvent> nestedHandler = Substitute.For<IDomainEventHandler<NestedTestDomainEvent>>();
IDomainEventPublisher publisher = CreatePublisher(services =>
{
services.AddScoped(_ => handler);
services.AddScoped(_ => nestedHandler);
});
handler.HandleAsync(domainEvent, Arg.Any<CancellationToken>())
.Returns(callInfo => publisher.PublishAsync(nestedDomainEvent, callInfo.Arg<CancellationToken>()));
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
await nestedHandler.Received(1).HandleAsync(nestedDomainEvent, Arg.Any<CancellationToken>());
}
[Fact]
public async Task Publish_WhenCancellationRequested_ShouldPassTokenToHandlers()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
using CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;
IDomainEventHandler<TestDomainEvent> handler = Substitute.For<IDomainEventHandler<TestDomainEvent>>();
IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped(_ => handler));
// Act
await publisher.PublishAsync(domainEvent, cancellationToken);
// Assert
await handler.Received(1).HandleAsync(domainEvent, Arg.Is(cancellationToken));
}
[Fact]
public async Task Publish_WhenDomainEventIsNull_ShouldThrowArgumentNullException()
{
// Arrange
IDomainEventPublisher publisher = CreatePublisher();
// Act
ArgumentNullException result = await Assert.ThrowsAsync<ArgumentNullException>(() => publisher.PublishAsync(null!, CancellationToken.None).AsTask());
// Assert
Assert.Equal("domainEvent", result.ParamName);
}
}
@@ -0,0 +1,109 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Infrastructure.Common.DomainEvents;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.DomainEvents;
/// <summary>
/// Contains unit tests for the <see cref="DomainEventsQueue"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DomainEventsQueueTests
{
private readonly DomainEventsQueue _sut = new();
[Fact]
public void TryDequeue_WhenQueueIsEmpty_ShouldReturnFalse()
{
// Act
bool result = _sut.TryDequeue(out IDomainEvent domainEvent);
// Assert
Assert.False(result);
Assert.Null(domainEvent);
}
[Fact]
public void Enqueue_WhenCalled_ShouldDequeueTheSameDomainEvent()
{
// Arrange
TestDomainEvent domainEvent = new(Guid.NewGuid(), DateTime.UtcNow);
// Act
_sut.Enqueue(domainEvent);
bool result = _sut.TryDequeue(out IDomainEvent dequeuedEvent);
// Assert
Assert.True(result);
Assert.Same(domainEvent, dequeuedEvent);
}
[Fact]
public void Enqueue_WhenCalledMultipleTimes_ShouldDequeueInFifoOrder()
{
// Arrange
TestDomainEvent firstEvent = new(Guid.NewGuid(), DateTime.UtcNow);
TestDomainEvent secondEvent = new(Guid.NewGuid(), DateTime.UtcNow);
TestDomainEvent thirdEvent = new(Guid.NewGuid(), DateTime.UtcNow);
// Act
_sut.Enqueue(firstEvent);
_sut.Enqueue(secondEvent);
_sut.Enqueue(thirdEvent);
_sut.TryDequeue(out IDomainEvent firstDequeued);
_sut.TryDequeue(out IDomainEvent secondDequeued);
_sut.TryDequeue(out IDomainEvent thirdDequeued);
// Assert
Assert.Same(firstEvent, firstDequeued);
Assert.Same(secondEvent, secondDequeued);
Assert.Same(thirdEvent, thirdDequeued);
}
[Fact]
public void Enqueue_WhenCalledWithMultipleEventTypes_ShouldDequeueAllTypes()
{
// Arrange
TestDomainEvent testEvent = new(Guid.NewGuid(), DateTime.UtcNow);
NestedTestDomainEvent nestedEvent = new(Guid.NewGuid(), DateTime.UtcNow);
// Act
_sut.Enqueue(testEvent);
_sut.Enqueue(nestedEvent);
_sut.TryDequeue(out IDomainEvent firstDequeued);
_sut.TryDequeue(out IDomainEvent secondDequeued);
// Assert
Assert.Same(testEvent, firstDequeued);
Assert.Same(nestedEvent, secondDequeued);
}
[Fact]
public void TryDequeue_WhenAllEventsWereDequeued_ShouldReturnFalseOnNextCall()
{
// Arrange
TestDomainEvent domainEvent = new(Guid.NewGuid(), DateTime.UtcNow);
_sut.Enqueue(domainEvent);
// Act
_sut.TryDequeue(out _);
bool result = _sut.TryDequeue(out IDomainEvent dequeuedEvent);
// Assert
Assert.False(result);
Assert.Null(dequeuedEvent);
}
/// <summary>
/// Test domain event used by the queue tests.
/// </summary>
private sealed record TestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent;
/// <summary>
/// A second test domain event used by the queue tests.
/// </summary>
private sealed record NestedTestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent;
}
@@ -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)));
}
}
@@ -0,0 +1,427 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Networking;
using Lumina.Infrastructure.Common.Networking;
using Lumina.Plugins.Contracts.Common.Http;
using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Networking;
/// <summary>
/// Contains unit tests for the <see cref="PublicHostRedirectHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PublicHostRedirectHandlerTests
{
private const string PRIVATE_HOST = "internal.example.com";
private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34");
[Fact]
public async Task SendAsync_WhenTheResponseRedirectsToAPublicHttpsHost_ShouldFollowIt()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
if (callIndex == 1)
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://archive.org/download/mbid-1/index.json");
return redirect;
}
return new HttpResponseMessage(HttpStatusCode.OK);
});
using HttpClient client = CreateClient(innerHandler);
// Act
HttpResponseMessage response = await client.GetAsync("https://coverartarchive.org/release/1");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(2, innerHandler.CallCount);
Assert.Equal("archive.org", innerHandler.Requests[1].RequestUri!.Host);
}
[Fact]
public async Task SendAsync_WhenTheResponseRedirectsToAPrivateHostName_ShouldThrow()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri($"https://{PRIVATE_HOST}/index.json");
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
// Act
Task Act()
{
return client.GetAsync("https://coverartarchive.org/release/1");
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(1, innerHandler.CallCount);
}
[Theory]
[InlineData("http://archive.org/index.json")] // A downgrade of a trusted host to plain HTTP.
[InlineData("https://127.0.0.1/index.json")] // The IPv4 loopback address.
[InlineData("https://localhost/index.json")] // The loopback host name.
[InlineData("https://169.254.169.254/latest/meta-data/")] // The link local cloud metadata endpoint.
[InlineData("https://10.0.0.5/index.json")] // A private class A address.
[InlineData("https://192.168.1.10/index.json")] // A private class C address.
public async Task SendAsync_WhenTheResponseRedirectsToADisallowedTarget_ShouldThrow(string location)
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri(location);
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
// Act
Task Act()
{
return client.GetAsync("https://coverartarchive.org/release/1");
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(1, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheRequestAllowsPrivateEndPointsAndRedirectsToAPrivateHost_ShouldFollowIt()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
if (callIndex == 1)
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri($"https://{PRIVATE_HOST}/index.json");
return redirect;
}
return new HttpResponseMessage(HttpStatusCode.OK);
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/start");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST);
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(2, innerHandler.CallCount);
Assert.Equal(PRIVATE_HOST, innerHandler.Requests[1].RequestUri!.Host);
}
[Fact]
public async Task SendAsync_WhenARequestWithABodyIsRedirected_ShouldReturnTheRedirectResponseWithoutFollowingIt()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://archive.org/index.json");
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Post, "https://coverartarchive.org/release/1");
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.TemporaryRedirect, response.StatusCode);
Assert.Equal(1, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheRequestIsRedirectedTooManyTimes_ShouldThrow()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://archive.org/loop/index.json");
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
// Act
Task Act()
{
return client.GetAsync("https://coverartarchive.org/release/1");
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
// The initial request plus the maximum number of followed redirects are sent before the loop is detected.
Assert.Equal(6, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheRequestDisablesRedirectFollowing_ShouldReturnTheRedirectResponseWithoutFollowingIt()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://archive.org/index.json");
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, "https://coverartarchive.org/release/1");
request.Options.Set(OutboundRequestOptions.FollowRedirects, false);
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.TemporaryRedirect, response.StatusCode);
Assert.Equal("https://archive.org/index.json", response.Headers.Location!.AbsoluteUri);
Assert.Equal(1, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheRedirectPointsAtAnotherPrivateHostThanTheAllowedOne_ShouldThrow()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://another.internal.example.com/index.json");
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/start");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST);
// Act
Task Act()
{
return client.SendAsync(request);
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(1, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenARedirectCrossesOrigins_ShouldNotForwardCredentialsOrHopByHopHeaders()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
if (callIndex == 1)
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://archive.org/index.json");
return redirect;
}
return new HttpResponseMessage(HttpStatusCode.OK);
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, "https://coverartarchive.org/start");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "secret");
request.Headers.TryAddWithoutValidation("Cookie", "session=secret");
request.Headers.TryAddWithoutValidation("Proxy-Authorization", "Basic secret");
request.Headers.Host = "coverartarchive.org";
request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=5");
request.Headers.TryAddWithoutValidation("TE", "trailers");
request.Headers.TryAddWithoutValidation("Upgrade", "h2c");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
HttpRequestMessage redirectedRequest = innerHandler.Requests[1];
Assert.Null(redirectedRequest.Headers.Authorization);
Assert.False(redirectedRequest.Headers.Contains("Cookie"));
Assert.False(redirectedRequest.Headers.Contains("Proxy-Authorization"));
Assert.Null(redirectedRequest.Headers.Host);
Assert.False(redirectedRequest.Headers.Contains("Connection"));
Assert.False(redirectedRequest.Headers.Contains("Keep-Alive"));
Assert.False(redirectedRequest.Headers.Contains("TE"));
Assert.False(redirectedRequest.Headers.Contains("Upgrade"));
Assert.Contains("application/json", redirectedRequest.Headers.Accept.ToString());
}
[Fact]
public async Task SendAsync_WhenARedirectStaysOnTheSameOrigin_ShouldKeepCredentialsButDropHopByHopHeaders()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
if (callIndex == 1)
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://coverartarchive.org/index.json");
return redirect;
}
return new HttpResponseMessage(HttpStatusCode.OK);
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, "https://coverartarchive.org/start");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "secret");
request.Headers.TryAddWithoutValidation("Cookie", "session=secret");
request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
HttpRequestMessage redirectedRequest = innerHandler.Requests[1];
Assert.Equal("Bearer secret", redirectedRequest.Headers.Authorization!.ToString());
string cookieHeader = Assert.Single(redirectedRequest.Headers.GetValues("Cookie"));
Assert.Equal("session=secret", cookieHeader);
Assert.False(redirectedRequest.Headers.Contains("Connection"));
}
[Fact]
public async Task SendAsync_WhenAHeadRequestIsRedirected_ShouldFollowIt()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
if (callIndex == 1)
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://archive.org/index.json");
return redirect;
}
return new HttpResponseMessage(HttpStatusCode.OK);
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Head, "https://coverartarchive.org/release/1");
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(2, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenAnAllowedPrivateHostRedirectsToItselfAcrossMultipleHops_ShouldKeepThePermission()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
if (callIndex <= 2)
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri(callIndex == 1 ? $"https://{PRIVATE_HOST}/second" : $"https://{PRIVATE_HOST}/third");
return redirect;
}
return new HttpResponseMessage(HttpStatusCode.OK);
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/start");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST);
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(3, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheResponseRedirectsToPlainHttp_ShouldThrowAPublicHostRejectedException()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("http://archive.org/index.json");
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
// Act
Task Act()
{
return client.GetAsync("https://coverartarchive.org/release/1");
}
// Assert
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(OutboundRequestRejectionReason.RedirectSchemeNotHttps, exception.RejectionReason);
Assert.Equal(1, innerHandler.CallCount);
}
/// <summary>
/// Creates an <see cref="HttpClient"/> whose requests are sent through the handler under test, wrapping the provided inner handler.
/// </summary>
/// <param name="innerHandler">The handler that answers the requests that reach the network.</param>
/// <returns>The created client.</returns>
private static HttpClient CreateClient(HttpMessageHandler innerHandler)
{
PublicHostValidator publicHostValidator = new((host, cancellationToken) =>
Task.FromResult<IPAddress[]>(host.Contains("internal.example.com", StringComparison.OrdinalIgnoreCase) ? [IPAddress.Parse("10.0.0.5")] : [s_publicAddress]));
PublicHostRedirectHandler handler = new(publicHostValidator, NullLogger<PublicHostRedirectHandler>.Instance) { InnerHandler = innerHandler };
return new HttpClient(handler);
}
/// <summary>
/// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed class StubHttpMessageHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, int, HttpResponseMessage> _responseFactory;
private int _callCount;
/// <summary>
/// Gets the requests that were sent through the handler.
/// </summary>
public List<HttpRequestMessage> Requests { get; } = [];
/// <summary>
/// Gets the number of requests that were sent through the handler.
/// </summary>
public int CallCount => _callCount;
/// <summary>
/// Initializes a new instance of the <see cref="StubHttpMessageHandler"/> class.
/// </summary>
/// <param name="responseFactory">The factory that produces the response of a request, given the request and its one based call index.</param>
public StubHttpMessageHandler(Func<HttpRequestMessage, int, HttpResponseMessage> responseFactory)
{
_responseFactory = responseFactory;
}
/// <summary>
/// Sends the provided request, producing its response through the configured factory.
/// </summary>
/// <param name="request">The request to send.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The response produced for the request.</returns>
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
int callIndex = Interlocked.Increment(ref _callCount);
Requests.Add(request);
return Task.FromResult(_responseFactory(request, callIndex));
}
}
}
@@ -0,0 +1,240 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Networking;
using Lumina.Infrastructure.Common.Networking;
using Lumina.Plugins.Contracts.Common.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Networking;
/// <summary>
/// Contains unit tests for the <see cref="PublicHostValidationHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PublicHostValidationHandlerTests
{
private const string PRIVATE_HOST = "internal.example.com";
private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34");
[Fact]
public async Task SendAsync_WhenTheHostIsPublic_ShouldSendTheRequest()
{
// Arrange
StubHttpMessageHandler innerHandler = new();
using HttpClient client = CreateClient(innerHandler);
// Act
using HttpResponseMessage response = await client.GetAsync("https://example.com/cover.jpg");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(1, innerHandler.CallCount);
}
[Theory]
[InlineData("http://127.0.0.1/cover.jpg")] // The IPv4 loopback address.
[InlineData("http://localhost/cover.jpg")] // The loopback host name.
[InlineData("http://[::1]/cover.jpg")] // The IPv6 loopback address.
[InlineData("http://169.254.169.254/latest/meta-data/")] // The link local cloud metadata endpoint.
[InlineData("http://10.0.0.5/cover.jpg")] // A private class A address.
[InlineData("http://172.16.0.1/cover.jpg")] // A private class B address.
[InlineData("http://192.168.1.10/cover.jpg")] // A private class C address.
public async Task SendAsync_WhenTheHostIsPrivateOrLocal_ShouldThrowAndNotSendTheRequest(string url)
{
// Arrange
StubHttpMessageHandler innerHandler = new();
using HttpClient client = CreateClient(innerHandler);
// Act
Task Act()
{
return client.GetAsync(url);
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(0, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheHostNameResolvesToOnePrivateAddress_ShouldThrowAndNotSendTheRequest()
{
// Arrange
StubHttpMessageHandler innerHandler = new();
using HttpClient client = CreateClient(innerHandler);
// Act
Task Act()
{
return client.GetAsync($"https://{PRIVATE_HOST}/cover.jpg");
}
// Assert
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, exception.RejectionReason);
Assert.Contains(PRIVATE_HOST, exception.Message);
Assert.DoesNotContain("10.0.0.5", exception.Message);
Assert.Equal(0, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheHostCannotBeResolved_ShouldThrowAPublicHostResolutionException()
{
// Arrange
StubHttpMessageHandler innerHandler = new();
PublicHostValidator validator = new((host, cancellationToken) => throw new SocketException((int)SocketError.HostNotFound));
PublicHostValidationHandler handler = new(validator, NullLogger<PublicHostValidationHandler>.Instance) { InnerHandler = innerHandler };
using HttpClient client = new(handler);
// Act
Task Act()
{
return client.GetAsync("https://missing.example.com/cover.jpg");
}
// Assert
PublicHostResolutionException exception = await Assert.ThrowsAsync<PublicHostResolutionException>(Act);
Assert.Equal(HttpRequestError.NameResolutionError, exception.HttpRequestError);
Assert.Equal(0, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheHostIsRejected_ShouldLogAWarning()
{
// Arrange
ILogger<PublicHostValidationHandler> mockLogger = Substitute.For<ILogger<PublicHostValidationHandler>>();
mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
StubHttpMessageHandler innerHandler = new();
PublicHostValidationHandler handler = new(CreateValidator(), mockLogger) { InnerHandler = innerHandler };
using HttpClient client = new(handler);
// Act
Task Act()
{
return client.GetAsync($"https://{PRIVATE_HOST}/cover.jpg");
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task SendAsync_WhenTheRequestAllowsPrivateEndPointsForTheHost_ShouldSendTheRequest()
{
// Arrange
StubHttpMessageHandler innerHandler = new();
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/cover.jpg");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST);
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(1, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheRequestAllowsPrivateEndPointsForAnotherHost_ShouldThrowAndNotSendTheRequest()
{
// Arrange
StubHttpMessageHandler innerHandler = new();
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/cover.jpg");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "another.internal.example.com");
// Act
Task Act()
{
return client.SendAsync(request);
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(0, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheRequestHasNoAbsoluteUri_ShouldThrowAndNotSendTheRequest()
{
// Arrange
StubHttpMessageHandler innerHandler = new();
PublicHostValidationHandler handler = new(CreateValidator(), NullLogger<PublicHostValidationHandler>.Instance) { InnerHandler = innerHandler };
using HttpMessageInvoker invoker = new(handler);
// Act
Task Act()
{
return invoker.SendAsync(new HttpRequestMessage(HttpMethod.Get, "/relative"), CancellationToken.None);
}
// Assert
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(OutboundRequestRejectionReason.RequestHasNoAbsoluteUri, exception.RejectionReason);
Assert.Equal(0, innerHandler.CallCount);
}
/// <summary>
/// Creates an <see cref="HttpClient"/> whose requests are sent through the handler under test, wrapping the provided inner handler.
/// </summary>
/// <param name="innerHandler">The handler that answers the requests that reach the network.</param>
/// <returns>The created client.</returns>
private static HttpClient CreateClient(HttpMessageHandler innerHandler)
{
PublicHostValidationHandler handler = new(CreateValidator(), NullLogger<PublicHostValidationHandler>.Instance) { InnerHandler = innerHandler };
return new HttpClient(handler);
}
/// <summary>
/// Creates a <see cref="PublicHostValidator"/> that classifies <see cref="PRIVATE_HOST"/> as private and every other host name as public.
/// </summary>
/// <returns>The created validator.</returns>
private static PublicHostValidator CreateValidator()
{
return new PublicHostValidator((host, cancellationToken) =>
Task.FromResult<IPAddress[]>(string.Equals(host, PRIVATE_HOST, StringComparison.OrdinalIgnoreCase) ? [IPAddress.Parse("10.0.0.5")] : [s_publicAddress]));
}
/// <summary>
/// Test HTTP message handler that answers every request with a successful response and records how many requests were sent to it.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed class StubHttpMessageHandler : HttpMessageHandler
{
private int _callCount;
/// <summary>
/// Gets the number of requests that were sent through the handler.
/// </summary>
public int CallCount => _callCount;
/// <summary>
/// Sends the provided request, producing a successful response.
/// </summary>
/// <param name="request">The request to send.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The response produced for the request.</returns>
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _callCount);
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
}
}
}
@@ -0,0 +1,502 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Networking;
using Lumina.Infrastructure.Common.Networking;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Networking;
/// <summary>
/// Contains unit tests for the <see cref="PublicHostValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PublicHostValidatorTests
{
private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34");
[Theory]
[InlineData("8.8.8.8")] // A public IPv4 address.
[InlineData("1.1.1.1")] // A public IPv4 address.
[InlineData("172.15.0.1")] // The address just below the private class B range.
[InlineData("172.32.0.1")] // The address just above the private class B range.
[InlineData("100.63.255.255")] // The address just below the carrier grade NAT range.
[InlineData("100.128.0.1")] // The address just above the carrier grade NAT range.
[InlineData("2606:4700:4700::1111")] // A public IPv6 address.
[InlineData("[2606:4700:4700::1111]")] // A public IPv6 address, bracketed like a URI host.
[InlineData("::ffff:93.184.216.34")] // An IPv4-mapped public IPv4 address.
public async Task ValidateHostAsync_WhenTheHostIsAPublicAddress_ShouldReturnTrue(string host)
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved."));
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync(host, allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Theory]
[InlineData("")] // An empty host.
[InlineData(" ")] // Only white space.
[InlineData("localhost")] // The loopback host name.
[InlineData("LOCALHOST")] // The loopback host name, upper cased.
[InlineData("127.0.0.1")] // The IPv4 loopback address.
[InlineData("::1")] // The IPv6 loopback address.
[InlineData("[::1]")] // The IPv6 loopback address, bracketed like a URI host.
[InlineData("0.0.0.0")] // The unspecified IPv4 address.
[InlineData("[::]")] // The unspecified IPv6 address.
[InlineData("169.254.169.254")] // The link local cloud metadata endpoint.
[InlineData("10.0.0.5")] // A private class A address.
[InlineData("::ffff:10.0.0.5")] // A private class A address, in its IPv4-mapped IPv6 form.
[InlineData("172.16.0.1")] // The lower bound of the private class B range.
[InlineData("172.31.255.255")] // The upper bound of the private class B range.
[InlineData("192.168.1.10")] // A private class C address.
[InlineData("100.64.0.1")] // The lower bound of the carrier grade NAT range.
[InlineData("100.127.255.255")] // The upper bound of the carrier grade NAT range.
[InlineData("192.0.2.10")] // The TEST-NET-1 documentation range.
[InlineData("198.18.0.1")] // The benchmarking range.
[InlineData("198.51.100.10")] // The TEST-NET-2 documentation range.
[InlineData("203.0.113.10")] // The TEST-NET-3 documentation range.
[InlineData("224.0.0.1")] // The multicast range.
[InlineData("240.0.0.1")] // The reserved range.
[InlineData("255.255.255.255")] // The broadcast address.
[InlineData("fc00::1")] // The IPv6 unique local range.
[InlineData("fd00:ec2::254")] // The AWS IMDSv6 endpoint, which lives in a unique local range.
[InlineData("fe80::1")] // The IPv6 link local range.
[InlineData("2001:db8::1")] // The IPv6 documentation range.
[InlineData("::127.0.0.1")] // An IPv4 compatible IPv6 address.
[InlineData("64:ff9b:1::1")] // The local use NAT64 prefix.
[InlineData("2002::1")] // The IPv6 6to4 range.
[InlineData("64:ff9b::1")] // The IPv6 NAT64 prefix.
[InlineData("100::1")] // The IPv6 discard only range.
[InlineData("ff02::1")] // The IPv6 multicast range.
public async Task ValidateHostAsync_WhenTheHostIsPrivateOrLocal_ShouldReturnFalse(string host)
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved."));
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync(host, allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostIsAnIPv4MappedPrivateAddress_ShouldReturnTrue()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved."));
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("::ffff:10.0.0.5", allowedPrivateHost: "::ffff:10.0.0.5", CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostNameResolvesToPublicAddresses_ShouldReturnTrue()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [s_publicAddress, IPAddress.Parse("93.184.216.35")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostNameResolvesToOnePrivateAddress_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostNameResolvesToBothPublicAndPrivateAddresses_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [s_publicAddress, IPAddress.Parse("192.168.1.10")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("mixed.example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostNameCannotBeResolved_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new SocketException((int)SocketError.HostNotFound));
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("missing.example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostNameIsMalformed_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new ArgumentException("The host is malformed."));
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("malformed host", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostNameResolvesToNoAddress_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => []);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("empty.example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenCancellationIsRequested_ShouldThrowOperationCanceledException()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new OperationCanceledException());
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task Act()
{
return sut.ValidateHostAsync("example.com", allowedPrivateHost: null, cancellationTokenSource.Token);
}
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenThePublicHostNameResolvesToAddresses_ShouldReturnTheirEndPoints()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [s_publicAddress, s_publicAddress]);
IPAddress expectedAddress = s_publicAddress;
// Act
IReadOnlyList<IPEndPoint> result = await sut.ResolveEndPointsAsync("example.com", 443, allowedPrivateHost: null, CancellationToken.None);
// Assert
IPEndPoint endPoint = Assert.Single(result);
Assert.Equal(expectedAddress, endPoint.Address);
Assert.Equal(443, endPoint.Port);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheHostNameResolvesToOnePrivateAddress_ShouldThrow()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [s_publicAddress, IPAddress.Parse("10.0.0.5")]);
// Act
Task Act()
{
return sut.ResolveEndPointsAsync("mixed.example.com", 80, allowedPrivateHost: null, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheHostIsAnIPv4MappedIPv6Address_ShouldReturnItsIPv4EndPoint()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved."));
IPAddress expectedAddress = IPAddress.Parse("93.184.216.34");
// Act
IReadOnlyList<IPEndPoint> result = await sut.ResolveEndPointsAsync("::ffff:93.184.216.34", 443, allowedPrivateHost: null, CancellationToken.None);
// Assert
IPEndPoint endPoint = Assert.Single(result);
Assert.Equal(expectedAddress, endPoint.Address);
Assert.Equal(443, endPoint.Port);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheHostCannotBeResolved_ShouldThrow()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new SocketException((int)SocketError.HostNotFound));
// Act
Task Act()
{
return sut.ResolveEndPointsAsync("missing.example.com", 443, allowedPrivateHost: null, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<PublicHostResolutionException>(Act);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheHostNameResolvesToNoAddress_ShouldThrow()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => []);
// Act
Task Act()
{
return sut.ResolveEndPointsAsync("empty.example.com", 443, allowedPrivateHost: null, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<PublicHostResolutionException>(Act);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToAPrivateAddress_ShouldReturnTrue()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenAnotherHostResolvesToOnePrivateAddress_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("other.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostIsLocalhost_ShouldReturnTrue()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("The loopback host name must not be resolved."));
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("localhost", allowedPrivateHost: "localhost", CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostIsAnIdnNameAndTheConnectionUsesItsPunycodeSpelling_ShouldReturnTrue()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("192.168.1.10")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("xn--bcher-kva.example", allowedPrivateHost: "bücher.example", CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToTheLinkLocalMetadataAddress_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("169.254.169.254")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToAnIPv6UniqueLocalAddress_ShouldReturnTrue()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("fc00::1")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToTheAwsMetadataAddress_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("fd00:ec2::254")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
Assert.Equal(OutboundRequestRejectionReason.LinkLocalOrMetadataAddress, result.RejectionReason);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToTheAlibabaMetadataAddress_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("100.100.100.200")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheAllowedPrivateHostResolvesToAPrivateAddress_ShouldReturnItsEndPoint()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
IPAddress expectedAddress = IPAddress.Parse("10.0.0.5");
// Act
IReadOnlyList<IPEndPoint> result = await sut.ResolveEndPointsAsync("internal.example.com", 8080, allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
IPEndPoint endPoint = Assert.Single(result);
Assert.Equal(expectedAddress, endPoint.Address);
Assert.Equal(8080, endPoint.Port);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenAnotherHostResolvesToAPrivateAddress_ShouldThrow()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
// Act
Task Act()
{
return sut.ResolveEndPointsAsync("other.example.com", 443, allowedPrivateHost: "internal.example.com", CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheAllowedPrivateHostResolvesToTheLinkLocalMetadataAddress_ShouldThrow()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("169.254.169.254")]);
// Act
Task Act()
{
return sut.ResolveEndPointsAsync("internal.example.com", 443, allowedPrivateHost: "internal.example.com", CancellationToken.None);
}
// Assert
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(OutboundRequestRejectionReason.LinkLocalOrMetadataAddress, exception.RejectionReason);
}
[Fact]
public async Task ValidateHostAsync_WhenTheSameHostIsCheckedTwice_ShouldResolveItOnlyOnce()
{
// Arrange
int resolutionCount = 0;
PublicHostValidator sut = new((host, cancellationToken) =>
{
resolutionCount++;
return Task.FromResult<IPAddress[]>([s_publicAddress]);
});
// Act
await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None);
await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.Equal(1, resolutionCount);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheHostWasAlreadyChecked_ShouldReuseTheResolution()
{
// Arrange
int resolutionCount = 0;
PublicHostValidator sut = new((host, cancellationToken) =>
{
resolutionCount++;
return Task.FromResult<IPAddress[]>([s_publicAddress]);
});
// Act
await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None);
await sut.ResolveEndPointsAsync("example.com", 443, allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.Equal(1, resolutionCount);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostCannotBeResolvedTwice_ShouldCacheTheFailureBriefly()
{
// Arrange
int resolutionCount = 0;
PublicHostValidator sut = new((host, cancellationToken) =>
{
resolutionCount++;
throw new SocketException((int)SocketError.HostNotFound);
});
// Act
await sut.ValidateHostAsync("missing.example.com", allowedPrivateHost: null, CancellationToken.None);
await sut.ValidateHostAsync("missing.example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.Equal(1, resolutionCount);
}
/// <summary>
/// Creates a <see cref="PublicHostValidator"/> whose host name resolution is replaced by the provided resolver.
/// </summary>
/// <param name="addressResolver">The resolver that produces the addresses of a host name.</param>
/// <returns>The created validator.</returns>
private static PublicHostValidator CreateValidator(Func<string, IPAddress[]> addressResolver)
{
return new PublicHostValidator((host, cancellationToken) => Task.FromResult(addressResolver(host)));
}
}
@@ -0,0 +1,121 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Utilities;
/// <summary>
/// Contains unit tests for the <see cref="ExceptionUtilities"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ExceptionUtilitiesTests
{
[Fact]
public void AggregateMessages_WhenCalledWithNestedException_ShouldConcatenateAllMessages()
{
// Arrange
Exception exception = new("outer", new InvalidOperationException("inner", new ArgumentException("deepest")));
// Act
string result = exception.AggregateMessages();
// Assert
Assert.Contains("outer", result);
Assert.Contains("inner", result);
Assert.Contains("deepest", result);
Assert.Contains(" -> ", result);
}
[Fact]
public void AggregateMessages_WhenCalledWithSingleException_ShouldReturnItsMessageWithArrow()
{
// Arrange
Exception exception = new("only-message");
// Act
string result = exception.AggregateMessages();
// Assert
Assert.Contains("only-message", result);
Assert.Contains(" -> ", result);
}
[Fact]
public void GetInnerExceptions_WhenExceptionIsNull_ShouldReturnEmptySequence()
{
// Act
IEnumerable<Exception> result = ((Exception)null!).GetInnerExceptions();
// Assert
Assert.Empty(result);
}
[Fact]
public void GetInnerExceptions_WhenExceptionHasNestedInners_ShouldReturnAllLevels()
{
// Arrange
Exception exception = new("first", new InvalidOperationException("second", new ArgumentException("third")));
// Act
List<Exception> result = [.. exception.GetInnerExceptions()];
// Assert
Assert.Equal(3, result.Count);
Assert.Equal("first", result[0].Message);
Assert.Equal("second", result[1].Message);
Assert.Equal("third", result[2].Message);
}
[Fact]
public void GetInnerExceptions_WhenChainExceedsMaximumDepth_ShouldStopAtMaximumDepth()
{
// Arrange
Exception exception = new("level-1", new Exception("level-2", new Exception("level-3", new Exception("level-4", new Exception("level-5", new Exception("level-6"))))));
// Act
List<Exception> result = [.. exception.GetInnerExceptions(maximumDepth: 3)];
// Assert
Assert.Equal(3, result.Count);
Assert.Equal(["level-1", "level-2", "level-3"], result.Select(inner => inner.Message));
}
[Fact]
public void GetInnerExceptions_WhenExceptionIsAggregate_ShouldReturnItsInnerExceptions()
{
// Arrange
AggregateException exception = new(
"aggregate",
[new InvalidOperationException("first-inner", new Exception("first-deep")), new ArgumentException("second-inner")]);
// Act
List<Exception> result = [.. exception.GetInnerExceptions()];
// Assert
// The aggregate exception itself, its inner exceptions and their inners are traversed, and the first inner exception
// is also reachable through the regular InnerException chain, so it is yielded twice.
Assert.Equal(6, result.Count);
Assert.Contains(result, inner => inner is AggregateException);
Assert.Equal(2, result.Count(inner => inner.Message == "first-inner"));
Assert.Equal(2, result.Count(inner => inner.Message == "first-deep"));
Assert.Single(result, inner => inner.Message == "second-inner");
}
[Fact]
public void AggregateMessage_WhenCalled_ShouldContainMessageAndCallStack()
{
// Arrange
Exception exception = new("some-message");
// Act
string result = exception.AggregateMessage();
// Assert
Assert.Contains("Message: some-message", result);
Assert.Contains("CallStack:", result);
}
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Infrastructure.Common.Utilities;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Utilities;
/// <summary>
/// Contains unit tests for the <see cref="ImageTypeUtilities"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ImageTypeUtilitiesTests
{
[Theory]
[InlineData(ImageType.BMP, "bmp")] // Bitmap image.
[InlineData(ImageType.GIF, "gif")] // Graphics interchange format.
[InlineData(ImageType.PNG, "png")] // Portable network graphics.
[InlineData(ImageType.TIFF, "tiff")] // Tagged image file format.
[InlineData(ImageType.PICT, "pct")] // Macintosh picture.
[InlineData(ImageType.ICO, "ico")] // Icon format.
[InlineData(ImageType.PSD, "psd")] // Photoshop document.
[InlineData(ImageType.JPEG2000, "jp2")] // JPEG 2000.
[InlineData(ImageType.AVIF, "avif")] // AV1 image file format.
[InlineData(ImageType.WEBP, "webp")] // Web picture format.
[InlineData(ImageType.TGA, "tga")] // Truevision TGA.
[InlineData(ImageType.SVG, "svg")] // Scalable vector graphics.
public void ToFileExtension_WhenTypeIsRecognized_ShouldReturnConventionalExtension(ImageType imageType, string expectedExtension)
{
// Act
string result = imageType.ToFileExtension();
// Assert
Assert.Equal(expectedExtension, result);
}
[Theory]
[InlineData(ImageType.JPEG)] // Joint photographic experts group.
[InlineData(ImageType.JPEG_CANON)] // Canon-specific JPEG.
[InlineData(ImageType.JPEG_UNKNOWN)] // Unknown JPEG.
public void ToFileExtension_WhenTypeIsAnyJpeg_ShouldReturnJpg(ImageType imageType)
{
// Act
string result = imageType.ToFileExtension();
// Assert
Assert.Equal("jpg", result);
}
[Fact]
public void ToFileExtension_WhenTypeIsNotARecognizedImage_ShouldReturnBin()
{
// Act
string result = ImageType.None.ToFileExtension();
// Assert
Assert.Equal("bin", result);
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Infrastructure.Common.Utilities;
using Lumina.Infrastructure.Common.Validation;
using Lumina.Infrastructure.Fixtures.Common.Utilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Utilities;
/// <summary>
/// Contains unit tests for the <see cref="OptionsBuilderValidationUtilities"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class OptionsBuilderValidationUtilitiesTests
{
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="OptionsBuilderValidationUtilitiesTests"/> class.
/// </summary>
public OptionsBuilderValidationUtilitiesTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void ValidateFluently_WhenCalled_ShouldRegisterFluentValidationOptions()
{
// Arrange
IServiceCollection services = Substitute.For<IServiceCollection>();
string name = _fixture.Create<string>();
OptionsBuilder<OptionsBuilderValidationUtilitiesFixture> optionsBuilder = new(services, name);
// Act
OptionsBuilder<OptionsBuilderValidationUtilitiesFixture> result = optionsBuilder.ValidateFluently();
// Assert
Assert.Same(optionsBuilder, result);
services.Received(1).Add(Arg.Is<ServiceDescriptor>(sd =>
sd.ServiceType == typeof(IValidateOptions<OptionsBuilderValidationUtilitiesFixture>) &&
sd.Lifetime == ServiceLifetime.Singleton &&
sd.ImplementationFactory != null));
}
[Fact]
public void ValidateFluently_WhenCalled_ShouldUseCorrectName()
{
// Arrange
ServiceCollection services = new();
string name = _fixture.Create<string>();
OptionsBuilder<OptionsBuilderValidationUtilitiesFixture> optionsBuilder = new(services, name);
// Act
optionsBuilder.ValidateFluently();
// Assert
ServiceDescriptor? serviceDescriptor = services.FirstOrDefault(sd =>
sd.ServiceType == typeof(IValidateOptions<OptionsBuilderValidationUtilitiesFixture>) &&
sd.Lifetime == ServiceLifetime.Singleton &&
sd.ImplementationFactory != null);
Assert.NotNull(serviceDescriptor);
Func<IServiceProvider, object>? implementationFactory = serviceDescriptor!.ImplementationFactory;
Assert.NotNull(implementationFactory);
IServiceProvider serviceProvider = Substitute.For<IServiceProvider>();
IValidator<OptionsBuilderValidationUtilitiesFixture> mockValidator = Substitute.For<IValidator<OptionsBuilderValidationUtilitiesFixture>>();
serviceProvider.GetService(typeof(IValidator<OptionsBuilderValidationUtilitiesFixture>))
.Returns(mockValidator);
ValidationOptions<OptionsBuilderValidationUtilitiesFixture>? validationOptions = implementationFactory!(serviceProvider) as ValidationOptions<OptionsBuilderValidationUtilitiesFixture>;
Assert.NotNull(validationOptions);
Assert.Equal(name, validationOptions.Name);
}
}
@@ -0,0 +1,127 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Validation;
using Lumina.Infrastructure.Fixtures.Common.Validation;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validation;
/// <summary>
/// Contains unit tests for the <see cref="ValidationOptions"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidationOptionsTests
{
private readonly IFixture _fixture;
private readonly ValidationOptionsFixture _validationOptionsFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ValidationOptionsTests"/> class.
/// </summary>
public ValidationOptionsTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void Validate_WhenMatchingName_ShouldValidateOptions()
{
// Arrange
string name = _fixture.Create<string>();
ValidationOptionsFixture options = _validationOptionsFixture.Create();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
validator.Validate(options).Returns([]);
ValidationOptions<ValidationOptionsFixture> sut = new(name, validator);
// Act
ValidateOptionsResult result = sut.Validate(name, options);
// Assert
Assert.IsType<ValidateOptionsResult>(result);
Assert.False(result.Failed);
validator.Received(1).Validate(options);
}
[Fact]
public void Validate_WhenNonMatchingName_ShouldSkipValidation()
{
// Arrange
string name = _fixture.Create<string>();
string differentName = _fixture.Create<string>();
ValidationOptionsFixture options = _validationOptionsFixture.Create();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
ValidationOptions<ValidationOptionsFixture> sut = new(name, validator);
// Act
ValidateOptionsResult result = sut.Validate(differentName, options);
// Assert
Assert.Equal(ValidateOptionsResult.Skip, result);
validator.DidNotReceive().Validate(options);
}
[Fact]
public void Validate_WhenNullName_ShouldValidateOptions()
{
// Arrange
ValidationOptionsFixture options = _validationOptionsFixture.Create();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
validator.Validate(options).Returns([]);
ValidationOptions<ValidationOptionsFixture> sut = new(null, validator);
// Act
ValidateOptionsResult result = sut.Validate(_fixture.Create<string>(), options);
// Assert
Assert.IsType<ValidateOptionsResult>(result);
Assert.False(result.Failed);
validator.Received(1).Validate(options);
}
[Fact]
public void Validate_WhenNullOptions_ShouldThrowArgumentNullException()
{
// Arrange
string name = _fixture.Create<string>();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
ValidationOptions<ValidationOptionsFixture> sut = new(name, validator);
// Act
Action act = () => sut.Validate(name, null!);
// Assert
Assert.Throws<ArgumentNullException>(() => sut.Validate(name, null!));
}
[Fact]
public void Validate_WhenInvalidOptions_ShouldReturnFailureResult()
{
// Arrange
string name = _fixture.Create<string>();
ValidationOptionsFixture options = _validationOptionsFixture.Create();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
List<Error> validationFailures =
[
Error.Validation("PropertyName", "Error Message")
];
validator.Validate(options).Returns(validationFailures);
ValidationOptions<ValidationOptionsFixture> sut = new(name, validator);
// Act
ValidateOptionsResult result = sut.Validate(name, options);
// Assert
Assert.IsType<ValidateOptionsResult>(result);
Assert.True(result.Failed);
Assert.Single(result.Failures);
Assert.Contains("Options validation failed for 'PropertyName' with error: 'Error Message'", result.Failures);
}
}
@@ -0,0 +1,132 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="CorsSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CorsSettingsDtoValidatorTests
{
private readonly CorsSettingsDtoValidator _validator = new();
private readonly CorsSettingsDtoFixture _corsSettingsDtoFixture = new();
[Fact]
public void Validate_WhenOriginsAreValidAbsoluteUrls_ShouldNotHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create(["https://app.example.com", "http://localhost:4200"]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenOriginIsWildcard_ShouldNotHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create(["*"]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenAllowedOriginsIsEmpty_ShouldHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create([]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.CorsOriginsCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenOriginHasTrailingSlash_ShouldHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create(["https://app.example.com/"]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.CorsOriginIsInvalid.Description, result[0].Description);
}
[Fact]
public void Validate_WhenOriginHasNoScheme_ShouldHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create(["app.example.com"]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.CorsOriginIsInvalid.Description, result[0].Description);
}
[Fact]
public void Validate_WhenOriginHasUnsupportedScheme_ShouldHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create(["ftp://app.example.com"]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.CorsOriginIsInvalid.Description, result[0].Description);
}
[Fact]
public void Validate_WhenOneOriginIsInvalid_ShouldHaveValidationErrorForThatOrigin()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create(["https://valid.example.com", "invalid-origin"]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.CorsOriginIsInvalid.Description, result[0].Description);
}
[Fact]
public void Validate_WhenOriginIsEmptyString_ShouldHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create([""]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Equal(2, result.Count);
Assert.Contains(result, error => error.Description == Errors.Configuration.CorsOriginsCannotBeEmpty.Description);
Assert.Contains(result, error => error.Description == Errors.Configuration.CorsOriginIsInvalid.Description);
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="DatabaseSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DatabaseSettingsDtoValidatorTests
{
private readonly DatabaseSettingsDtoValidator _validator = new();
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseSettingsDtoValidatorTests"/> class.
/// </summary>
public DatabaseSettingsDtoValidatorTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void Validate_WhenDefaultConnectionProvided_ShouldNotHaveValidationError()
{
// Arrange
DatabaseSettingsDto model = _fixture.Build<DatabaseSettingsDto>()
.With(x => x.DefaultConnection, "dummy-connection-string")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenDefaultConnectionNotProvided_ShouldHaveValidationError()
{
// Arrange
DatabaseSettingsDto model = _fixture.Build<DatabaseSettingsDto>()
.With(x => x.DefaultConnection, string.Empty)
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Description, result[0].Description);
}
}
@@ -0,0 +1,80 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="EncryptionSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EncryptionSettingsDtoValidatorTests
{
private readonly EncryptionSettingsDtoValidator _validator = new();
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="EncryptionSettingsDtoValidatorTests"/> class.
/// </summary>
public EncryptionSettingsDtoValidatorTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void Validate_WhenValidBase64SecretKeyProvided_ShouldNotHaveValidationError()
{
// Arrange
EncryptionSettingsDto model = _fixture.Build<EncryptionSettingsDto>()
.With(x => x.SecretKey, "dGhpcyBpcyBhIHZhbGlkIGJhc2U2NCBzdHJpbmc=") // "this is a valid base64 string" in base64.
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationError()
{
// Arrange
EncryptionSettingsDto model = _fixture.Build<EncryptionSettingsDto>()
.With(x => x.SecretKey, string.Empty)
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.EncryptionSecretKeyCannotBeEmpty.Description, result[0].Description);
}
[Theory]
[InlineData("not-a-base64-string")]
[InlineData("invalid!base64")]
[InlineData("123")]
public void Validate_WhenSecretKeyIsNotBase64_ShouldHaveValidationError(string invalidBase64)
{
// Arrange
EncryptionSettingsDto model = _fixture.Build<EncryptionSettingsDto>()
.With(x => x.SecretKey, invalidBase64)
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.EncryptionSecretKeyMustBeABase64String.Description, result[0].Description);
}
}
@@ -0,0 +1,147 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="JwtSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class JwtSettingsDtoValidatorTests
{
private readonly JwtSettingsDtoValidator _validator = new();
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="JwtSettingsDtoValidatorTests"/> class.
/// </summary>
public JwtSettingsDtoValidatorTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void Validate_WhenAllPropertiesValid_ShouldNotHaveValidationError()
{
// Arrange
JwtSettingsDto model = _fixture.Build<JwtSettingsDto>()
.With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing")
.With(x => x.ExpiryMinutes, 30)
.With(x => x.Issuer, "test-issuer")
.With(x => x.Audience, "test-audience")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationErrors()
{
// Arrange
JwtSettingsDto model = _fixture.Build<JwtSettingsDto>()
.With(x => x.SecretKey, string.Empty)
.With(x => x.ExpiryMinutes, 30)
.With(x => x.Issuer, "test-issuer")
.With(x => x.Audience, "test-audience")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Equal(2, result.Count);
Assert.Contains(result, error => error.Description == Errors.Configuration.JwtSecretKeyCannotBeEmpty.Description);
Assert.Contains(result, error => error.Description == Errors.Configuration.JwtSecretKeyTooShort.Description);
}
[Fact]
public void Validate_WhenSecretKeyTooShort_ShouldHaveValidationError()
{
// Arrange
JwtSettingsDto model = _fixture.Build<JwtSettingsDto>()
.With(x => x.SecretKey, "short-key")
.With(x => x.ExpiryMinutes, 30)
.With(x => x.Issuer, "test-issuer")
.With(x => x.Audience, "test-audience")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.JwtSecretKeyTooShort.Description, result[0].Description);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(-60)]
public void Validate_WhenExpiryMinutesNotPositive_ShouldHaveValidationError(int minutes)
{
// Arrange
JwtSettingsDto model = _fixture.Build<JwtSettingsDto>()
.With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing")
.With(x => x.ExpiryMinutes, minutes)
.With(x => x.Issuer, "test-issuer")
.With(x => x.Audience, "test-audience")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.JwtExpiryMinutesMustBePositive.Description, result[0].Description);
}
[Fact]
public void Validate_WhenIssuerIsEmpty_ShouldHaveValidationError()
{
// Arrange
JwtSettingsDto model = _fixture.Build<JwtSettingsDto>()
.With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing")
.With(x => x.ExpiryMinutes, 30)
.With(x => x.Issuer, string.Empty)
.With(x => x.Audience, "test-audience")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.JwtIssuerCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenAudienceIsEmpty_ShouldHaveValidationError()
{
// Arrange
JwtSettingsDto model = _fixture.Build<JwtSettingsDto>()
.With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing")
.With(x => x.ExpiryMinutes, 30)
.With(x => x.Issuer, "test-issuer")
.With(x => x.Audience, string.Empty)
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.JwtAudienceCannotBeEmpty.Description, result[0].Description);
}
}
@@ -0,0 +1,124 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Validators;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="MediaSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaSettingsDtoValidatorTests
{
private readonly MediaSettingsDtoValidator _validator = new();
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="MediaSettingsDtoValidatorTests"/> class.
/// </summary>
public MediaSettingsDtoValidatorTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void Validate_WhenRootDirectoryProvided_ShouldNotHaveValidationError()
{
// Arrange
MediaSettingsDto model = _fixture.Build<MediaSettingsDto>()
.With(x => x.RootDirectory, "/path/to/media")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenRootDirectoryIsEmpty_ShouldHaveValidationError()
{
// Arrange
MediaSettingsDto model = _fixture.Build<MediaSettingsDto>()
.With(x => x.RootDirectory, string.Empty)
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenRootDirectoryIsWhitespace_ShouldHaveValidationError()
{
// Arrange
MediaSettingsDto model = _fixture.Build<MediaSettingsDto>()
.With(x => x.RootDirectory, " ")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenMediaLibrariesDirectoryIsEmpty_ShouldHaveValidationError()
{
// Arrange
MediaSettingsDto model = _fixture.Build<MediaSettingsDto>()
.With(x => x.LibrariesDirectory, string.Empty)
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenMediaLibrariesDirectoryProvided_ShouldNotHaveValidationError()
{
// Arrange
MediaSettingsDto model = _fixture.Build<MediaSettingsDto>()
.With(x => x.LibrariesDirectory, "/path/to/media")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenMediaLibrariesDirectoryIsWhitespace_ShouldHaveValidationError()
{
// Arrange
MediaSettingsDto model = _fixture.Build<MediaSettingsDto>()
.With(x => x.LibrariesDirectory, " ")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty.Description, result[0].Description);
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Validators;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="PluginsSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PluginsSettingsDtoValidatorTests
{
private readonly PluginsSettingsDtoValidator _validator = new();
private readonly PluginsSettingsDtoFixture _pluginsSettingsDtoFixture = new();
[Fact]
public void Validate_WhenDirectoryProvided_ShouldNotHaveValidationError()
{
// Arrange
PluginsSettingsDto model = _pluginsSettingsDtoFixture.Create(directory: "/path/to/plugins");
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenDirectoryIsEmpty_ShouldHaveValidationError()
{
// Arrange
PluginsSettingsDto model = _pluginsSettingsDtoFixture.Create(directory: string.Empty);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.PluginsDirectoryCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenDirectoryIsWhitespace_ShouldHaveValidationError()
{
// Arrange
PluginsSettingsDto model = _pluginsSettingsDtoFixture.Create(directory: " ");
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.PluginsDirectoryCannotBeEmpty.Description, result[0].Description);
}
}
@@ -0,0 +1,140 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="ThemeEngineOptionsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeEngineOptionsDtoValidatorTests
{
private readonly ThemeEngineOptionsDtoValidator _validator = new();
private readonly ThemeEngineOptionsDtoFixture _themeEngineOptionsDtoFixture = new();
[Fact]
public void Validate_WhenAllPropertiesValid_ShouldNotHaveValidationError()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create();
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenStoragePathIsEmpty_ShouldHaveValidationError()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(storagePath: string.Empty);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeStoragePathCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenBundledThemesPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(bundledThemesPath: string.Empty);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeBundledThemesPathCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenDefaultThemeIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(defaultThemeId: string.Empty);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeDefaultThemeIdCannotBeEmpty.Description, result[0].Description);
}
[Theory]
[InlineData(0L)] // Zero, not positive.
[InlineData(-1L)] // Negative.
public void Validate_WhenMaxArchiveBytesIsNotPositive_ShouldHaveValidationError(long maxArchiveBytes)
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxArchiveBytes: maxArchiveBytes);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeMaxArchiveBytesMustBePositive.Description, result[0].Description);
}
[Theory]
[InlineData(0L)] // Zero, not positive.
[InlineData(-1L)] // Negative.
public void Validate_WhenMaxExpandedBytesIsNotPositive_ShouldHaveValidationError(long maxExpandedBytes)
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxExpandedBytes: maxExpandedBytes);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeMaxExpandedBytesMustBePositive.Description, result[0].Description);
}
[Theory]
[InlineData(0L)] // Zero, not positive.
[InlineData(-1L)] // Negative.
public void Validate_WhenMaxSingleFileBytesIsNotPositive_ShouldHaveValidationError(long maxSingleFileBytes)
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxSingleFileBytes: maxSingleFileBytes);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeMaxSingleFileBytesMustBePositive.Description, result[0].Description);
}
[Theory]
[InlineData(0)] // Zero, not positive.
[InlineData(-1)] // Negative.
public void Validate_WhenMaxEntriesIsNotPositive_ShouldHaveValidationError(int maxEntries)
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxEntries: maxEntries);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeMaxEntriesMustBePositive.Description, result[0].Description);
}
}
@@ -0,0 +1,454 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Abstractions;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="TranscodingSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingSettingsDtoValidatorTests : IDisposable
{
private readonly TranscodingSettingsDtoValidator _validator;
private readonly TranscodingSettingsDtoFixture _transcodingSettingsDtoFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
private readonly PluginsSettingsDtoFixture _pluginsSettingsDtoFixture = new();
private readonly string _sandboxRoot;
private readonly string _mediaRoot;
private readonly string _validCacheDirectory;
private readonly string _pluginsDirectory;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingSettingsDtoValidatorTests"/> class.
/// </summary>
public TranscodingSettingsDtoValidatorTests()
{
_sandboxRoot = Path.Combine(Path.GetTempPath(), "lumina-transcoding-validator-tests-" + Guid.NewGuid().ToString("N"));
_mediaRoot = Path.Combine(_sandboxRoot, "media");
_validCacheDirectory = Path.Combine(_sandboxRoot, "cache");
_pluginsDirectory = Path.Combine(_sandboxRoot, "plugins");
Directory.CreateDirectory(_mediaRoot);
Directory.CreateDirectory(_validCacheDirectory);
Directory.CreateDirectory(_pluginsDirectory);
// The real path service is used, with the real path strategy of the current platform, so containment follows the file system rules of the host.
IPlatformContext platformContext = Substitute.For<IPlatformContext>();
IPathStrategy pathStrategy = OperatingSystem.IsWindows()
? new WindowsPathStrategy(new FileSystem())
: new UnixPathStrategy(new FileSystem());
platformContext.PathStrategy.Returns(pathStrategy);
IPlatformContextManager platformContextManager = Substitute.For<IPlatformContextManager>();
platformContextManager.GetCurrentContext().Returns(platformContext);
IPathService pathService = new PathService(platformContextManager);
// An absolute root directory pins the media root that is served by the media route, because Path.Combine returns its second argument when it is rooted.
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: _mediaRoot);
PluginsSettingsDto pluginsSettings = _pluginsSettingsDtoFixture.Create(directory: _pluginsDirectory);
_validator = new TranscodingSettingsDtoValidator(Options.Create(mediaSettings), Options.Create(pluginsSettings), pathService);
}
[Fact]
public void Validate_WhenSettingsAreValid_ShouldNotHaveAnyValidationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Theory]
[InlineData(null)] // A missing ffmpeg path.
[InlineData("")] // An empty ffmpeg path.
[InlineData(" ")] // A whitespace ffmpeg path.
public void Validate_WhenFfmpegPathIsEmpty_ShouldHaveFfmpegPathCannotBeEmptyError(string? ffmpegPath)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(ffmpegPath: ffmpegPath, includeFfmpegPath: ffmpegPath is not null);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingFfmpegPathCannotBeEmpty.Description);
}
[Theory]
[InlineData(0)] // A job count of zero disables normalization.
[InlineData(-1)] // A negative job count disables normalization.
public void Validate_WhenMaxConcurrentJobsIsNotPositive_ShouldHaveMaxConcurrentJobsMustBePositiveError(int maxConcurrentJobs)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: maxConcurrentJobs, maxConcurrentJobsPerUser: 1);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsMustBePositive.Description);
}
[Fact]
public void Validate_WhenMaxConcurrentJobsIsTooLarge_ShouldHaveMaxConcurrentJobsIsTooLargeError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 65, maxConcurrentJobsPerUser: 1);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge.Description);
}
[Fact]
public void Validate_WhenMaxConcurrentJobsIsTheMaximum_ShouldNotHaveMaxConcurrentJobsErrors()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 64, maxConcurrentJobsPerUser: 64);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsMustBePositive.Description);
}
[Theory]
[InlineData(0)] // A per-user job count of zero never admits a normalization.
[InlineData(-1)] // A negative per-user job count never admits a normalization.
public void Validate_WhenMaxConcurrentJobsPerUserIsNotPositive_ShouldHaveMaxConcurrentJobsPerUserMustBePositiveError(int maxConcurrentJobsPerUser)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 8, maxConcurrentJobsPerUser: maxConcurrentJobsPerUser);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserMustBePositive.Description);
}
[Fact]
public void Validate_WhenMaxConcurrentJobsPerUserIsTooLarge_ShouldHaveMaxConcurrentJobsPerUserIsTooLargeError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 64, maxConcurrentJobsPerUser: 65);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserIsTooLarge.Description);
}
[Fact]
public void Validate_WhenMaxConcurrentJobsPerUserExceedsTheGlobalLimit_ShouldHaveMaxConcurrentJobsPerUserExceedsGlobalError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 8, maxConcurrentJobsPerUser: 16);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserExceedsGlobal.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserIsTooLarge.Description);
}
[Theory]
[InlineData(0)] // A cache with no capacity cannot hold a normalized track.
[InlineData(-1)] // A negative cache size is not a capacity.
public void Validate_WhenMaxCacheBytesIsNotPositive_ShouldHaveMaxCacheBytesMustBePositiveError(long maxCacheBytes)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxCacheBytes: maxCacheBytes);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxCacheBytesMustBePositive.Description);
}
[Theory]
[InlineData(0)] // A job timeout of zero stops every job immediately.
[InlineData(-1)] // A negative job timeout stops every job immediately.
public void Validate_WhenJobTimeoutSecondsIsNotPositive_ShouldHaveJobTimeoutMustBePositiveError(int jobTimeoutSeconds)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(jobTimeoutSeconds: jobTimeoutSeconds);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutMustBePositive.Description);
}
[Fact]
public void Validate_WhenJobTimeoutSecondsIsTooLong_ShouldHaveJobTimeoutIsTooLongError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(jobTimeoutSeconds: 86_401);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutIsTooLong.Description);
}
[Fact]
public void Validate_WhenJobTimeoutSecondsIsTheMaximum_ShouldNotHaveJobTimeoutErrors()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(jobTimeoutSeconds: 86_400);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutIsTooLong.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutMustBePositive.Description);
}
[Theory]
[InlineData(0)] // An eviction grace of zero protects nothing.
[InlineData(-1)] // A negative eviction grace protects nothing.
public void Validate_WhenEvictionGraceSecondsIsNotPositive_ShouldHaveEvictionGraceSecondsMustBePositiveError(int evictionGraceSeconds)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(evictionGraceSeconds: evictionGraceSeconds);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsMustBePositive.Description);
}
[Fact]
public void Validate_WhenEvictionGraceSecondsIsTooLong_ShouldHaveEvictionGraceSecondsIsTooLongError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(evictionGraceSeconds: 86_401);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsIsTooLong.Description);
}
[Fact]
public void Validate_WhenEvictionGraceSecondsIsTheMaximum_ShouldNotHaveEvictionGraceSecondsErrors()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(evictionGraceSeconds: 86_400);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsIsTooLong.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsMustBePositive.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsMalformed_ShouldHaveCacheDirectoryIsInvalidError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: "bad\0path");
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInvalid.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsInsideTheMediaRoot_ShouldHaveCacheDirectoryIsInsideMediaRootError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: Path.Combine(_mediaRoot, "cache"));
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryContainsTheMediaRoot_ShouldHaveCacheDirectoryContainsMediaRootError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: _sandboxRoot);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsAFileSystemRoot_ShouldHaveCacheDirectoryIsUnsafeLocationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: Path.GetPathRoot(_mediaRoot)!);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsTheApplicationBaseDirectory_ShouldHaveCacheDirectoryIsUnsafeLocationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: AppContext.BaseDirectory);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsTheLogsDirectory_ShouldHaveCacheDirectoryIsUnsafeLocationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: Path.Combine(AppContext.BaseDirectory, "logs"));
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsThePluginsDirectory_ShouldHaveCacheDirectoryIsUnsafeLocationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: _pluginsDirectory);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsAValidExternalDirectory_ShouldNotHaveCacheDirectoryErrors()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: _validCacheDirectory);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Theory]
[InlineData(null)] // No configured directory, so the default temporary directory is used.
[InlineData(" ")] // A whitespace directory, so the default temporary directory is used.
public void Validate_WhenCacheDirectoryIsNotConfigured_ShouldOnlyValidateTheDefaultDirectory(string? cacheDirectory)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: cacheDirectory, includeCacheDirectory: cacheDirectory is not null);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
/// <summary>
/// Releases the temporary directories the containment tests use.
/// </summary>
public void Dispose()
{
try
{
if (Directory.Exists(_sandboxRoot))
Directory.Delete(_sandboxRoot, recursive: true);
}
catch (IOException)
{
// A temporary directory that cannot be removed does not fail the test.
}
}
/// <summary>
/// Creates settings that are valid unless an argument overrides a single rule under test.
/// </summary>
/// <param name="ffmpegPath">The file name or path of the ffmpeg binary.</param>
/// <param name="maxConcurrentJobs">The maximum number of normalization jobs that may run at the same time.</param>
/// <param name="maxConcurrentJobsPerUser">The maximum number of normalization jobs a single user may have running at the same time.</param>
/// <param name="maxCacheBytes">The maximum total size of the normalized audio cache, in bytes.</param>
/// <param name="jobTimeoutSeconds">The maximum duration of a single normalization job, in seconds.</param>
/// <param name="evictionGraceSeconds">The period during which a cache entry is protected from eviction, in seconds.</param>
/// <param name="cacheDirectory">The directory where normalized audio is cached.</param>
/// <param name="includeCacheDirectory">Whether the cache directory should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeFfmpegPath">Whether the ffmpeg path should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created settings.</returns>
private TranscodingSettingsDto CreateSettings(
string? ffmpegPath = "ffmpeg",
int? maxConcurrentJobs = 8,
int? maxConcurrentJobsPerUser = 4,
long? maxCacheBytes = 2L * 1024 * 1024 * 1024,
int? jobTimeoutSeconds = 900,
int? evictionGraceSeconds = 120,
string? cacheDirectory = null,
bool includeCacheDirectory = true,
bool includeFfmpegPath = true)
{
return _transcodingSettingsDtoFixture.Create(
ffmpegPath: ffmpegPath,
maxConcurrentJobs: maxConcurrentJobs,
maxConcurrentJobsPerUser: maxConcurrentJobsPerUser,
maxCacheBytes: maxCacheBytes,
jobTimeoutSeconds: jobTimeoutSeconds,
evictionGraceSeconds: evictionGraceSeconds,
cacheDirectory: cacheDirectory ?? _validCacheDirectory,
includeCacheDirectory: includeCacheDirectory,
includeFfmpegPath: includeFfmpegPath);
}
}