mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Merge pull request #161 from BinaryAlley/bugfix/fix-security-tests-shared-in-memory-sqlite-connection
Bugfix/fix security tests shared in memory sqlite connection
This commit is contained in:
8 files changed
+285
-11
No files matched your search
@@ -0,0 +1,77 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Common.Middlewares;
|
||||
|
||||
/// <summary>
|
||||
/// Middleware that catches unhandled exceptions and converts them into a ProblemDetails response.
|
||||
/// </summary>
|
||||
public class ExceptionHandlingMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ExceptionHandlingMiddleware"/> class.
|
||||
/// </summary>
|
||||
/// <param name="next">The next middleware in the request pipeline.</param>
|
||||
/// <param name="logger">Injected service used for logging.</param>
|
||||
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
|
||||
{
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles incoming requests and converts any unhandled exception into a ProblemDetails response.
|
||||
/// </summary>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _next(context).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// the request was aborted, so there is no client left to write a response to
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// once the response has started, it is no longer possible to replace it with a ProblemDetails response
|
||||
if (context.Response.HasStarted)
|
||||
throw;
|
||||
_logger.LogError(ex, "Unhandled exception occurred while processing request {Method} {Path}", context.Request.Method, context.Request.Path);
|
||||
await WriteProblemDetailsResponseAsync(context).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a generic ProblemDetails response, without exposing any internal exception details to the client.
|
||||
/// </summary>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
private static async Task WriteProblemDetailsResponseAsync(HttpContext context)
|
||||
{
|
||||
ProblemDetails problemDetails = new()
|
||||
{
|
||||
Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1",
|
||||
Title = "InternalServerError",
|
||||
Status = StatusCodes.Status500InternalServerError,
|
||||
Detail = "An unexpected error occurred while processing the request.",
|
||||
Instance = context.Request.Path
|
||||
};
|
||||
problemDetails.Extensions["traceId"] = Activity.Current?.Id ?? context.TraceIdentifier;
|
||||
|
||||
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
JsonSerializerOptions? jsonSerializerOptions = null;
|
||||
await context.Response.WriteAsJsonAsync(problemDetails, jsonSerializerOptions, "application/problem+json", context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Api.Common.Middlewares;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Common.Utilities;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for adding the <see cref="ExceptionHandlingMiddleware"/> to the request pipeline.
|
||||
/// </summary>
|
||||
public static class ApiExceptionHandlingMiddlewareUtilities
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds the <see cref="ExceptionHandlingMiddleware"/> to the application's request pipeline, so that any unhandled exception is converted into a ProblemDetails response.
|
||||
/// </summary>
|
||||
/// <param name="builder">The <see cref="IApplicationBuilder"/> used to configure the application's request pipeline.</param>
|
||||
/// <returns>The <see cref="IApplicationBuilder"/> for further configuration.</returns>
|
||||
public static IApplicationBuilder UseApiExceptionHandling(this IApplicationBuilder builder)
|
||||
{
|
||||
return builder.UseMiddleware<ExceptionHandlingMiddleware>();
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ using Lumina.Infrastructure.Common.DependencyInjection;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
|
||||
using Lumina.Presentation.Api.Common.DependencyInjection;
|
||||
using Lumina.Presentation.Api.Common.Middlewares;
|
||||
using Lumina.Presentation.Api.Common.Utilities;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Data.Sqlite;
|
||||
@@ -107,7 +108,7 @@ public class Program
|
||||
app.UseRouting();
|
||||
app.UseCors("SecurePolicy");
|
||||
|
||||
//app.UseExceptionHandler("/error"); // uses a middleware which re-executes the request to the error path
|
||||
app.UseApiExceptionHandling(); // catches any unhandled exception and returns a ProblemDetails response
|
||||
|
||||
//app.UseHttpsRedirection();
|
||||
|
||||
|
||||
+9
-2
@@ -34,19 +34,26 @@ namespace Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
{
|
||||
private readonly SqliteConnection _connection;
|
||||
private readonly string _sharedInMemoryConnectionString;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=";
|
||||
private const string SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX = "Data Source=lumina-tests-{0};Mode=Memory;Cache=Shared";
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaApiFactory"/> class.
|
||||
/// </summary>
|
||||
public LuminaApiFactory()
|
||||
{
|
||||
_connection = new SqliteConnection("DataSource=:memory:");
|
||||
// each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another;
|
||||
// the shared cache allows each DbContext to open its own pooled connection to the same database, instead of sharing a single connection,
|
||||
// which would otherwise serialize every request on one connection and cause nested transaction errors between requests
|
||||
_sharedInMemoryConnectionString = string.Format(SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX, Guid.NewGuid());
|
||||
// keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped
|
||||
_connection = new SqliteConnection(_sharedInMemoryConnectionString);
|
||||
_connection.Open();
|
||||
}
|
||||
|
||||
@@ -84,7 +91,7 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
// add SQLite DbContext configuration
|
||||
services.AddDbContext<LuminaDbContext>((serviceProvider, options) =>
|
||||
{
|
||||
options.UseSqlite(_connection);
|
||||
options.UseSqlite(_sharedInMemoryConnectionString);
|
||||
options.AddInterceptors(serviceProvider.GetRequiredService<UpdateAuditableEntitiesInterceptor>());
|
||||
});
|
||||
// configure JWT authentication for testing
|
||||
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Api.Common.Middlewares;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Common.Middlewares;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ExceptionHandlingMiddleware"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ExceptionHandlingMiddlewareTests
|
||||
{
|
||||
private readonly ILogger<ExceptionHandlingMiddleware> _mockLogger;
|
||||
private readonly ExceptionHandlingMiddleware _sut;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
private RequestDelegate _nextDelegate = context => Task.CompletedTask;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ExceptionHandlingMiddlewareTests"/> class.
|
||||
/// </summary>
|
||||
public ExceptionHandlingMiddlewareTests()
|
||||
{
|
||||
_mockLogger = Substitute.For<ILogger<ExceptionHandlingMiddleware>>();
|
||||
_sut = new ExceptionHandlingMiddleware(context => _nextDelegate(context), _mockLogger);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenNextThrowsException_ShouldWriteInternalServerErrorProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext context = new()
|
||||
{
|
||||
Response = { Body = new MemoryStream() }
|
||||
};
|
||||
_nextDelegate = _ => throw new InvalidOperationException("sensitive internal details");
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, context.Response.StatusCode);
|
||||
Assert.Equal("application/problem+json", context.Response.ContentType);
|
||||
|
||||
context.Response.Body.Seek(0, SeekOrigin.Begin);
|
||||
using StreamReader reader = new(context.Response.Body, Encoding.UTF8);
|
||||
string responseBody = await reader.ReadToEndAsync();
|
||||
ProblemDetails problemDetails = JsonSerializer.Deserialize<ProblemDetails>(responseBody, _jsonOptions)!;
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, problemDetails.Status);
|
||||
Assert.Equal("InternalServerError", problemDetails.Title);
|
||||
Assert.Equal("An unexpected error occurred while processing the request.", problemDetails.Detail);
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails.Extensions["traceId"]?.ToString()));
|
||||
Assert.DoesNotContain("sensitive internal details", responseBody);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenNextThrowsException_ShouldLogTheException()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext context = new()
|
||||
{
|
||||
Response = { Body = new MemoryStream() }
|
||||
};
|
||||
_nextDelegate = _ => throw new InvalidOperationException("sensitive internal details");
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(context);
|
||||
|
||||
// Assert
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Error,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "sensitive internal details"),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenNextThrowsOperationCanceledException_ShouldRethrow()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext context = new()
|
||||
{
|
||||
Response = { Body = new MemoryStream() }
|
||||
};
|
||||
_nextDelegate = _ => throw new OperationCanceledException();
|
||||
|
||||
// Act
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => _sut.InvokeAsync(context));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
|
||||
Assert.Equal(0, context.Response.Body.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenResponseHasStarted_ShouldRethrowTheException()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext context = new();
|
||||
context.Features.Set<IHttpResponseFeature>(new StartedHttpResponseFeature());
|
||||
context.Response.Body = new MemoryStream();
|
||||
_nextDelegate = _ => throw new InvalidOperationException("sensitive internal details");
|
||||
|
||||
// Act
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => _sut.InvokeAsync(context));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(0, context.Response.Body.Length);
|
||||
_mockLogger.DidNotReceive().Log(
|
||||
Arg.Any<LogLevel>(),
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Any<Exception>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenNextCompletesSuccessfully_ShouldNotModifyTheResponse()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext context = new()
|
||||
{
|
||||
Response = { Body = new MemoryStream() }
|
||||
};
|
||||
_nextDelegate = context => Task.CompletedTask;
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
|
||||
Assert.Equal(0, context.Response.Body.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Response feature that reports the response as already started, for simulating a response that cannot be replaced.
|
||||
/// </summary>
|
||||
private sealed class StartedHttpResponseFeature : IHttpResponseFeature
|
||||
{
|
||||
public int StatusCode { get; set; } = StatusCodes.Status200OK;
|
||||
|
||||
public string? ReasonPhrase { get; set; }
|
||||
|
||||
public IHeaderDictionary Headers { get; set; } = new HeaderDictionary();
|
||||
|
||||
public Stream Body { get; set; } = Stream.Null;
|
||||
|
||||
public bool HasStarted => true;
|
||||
|
||||
public void OnStarting(Func<object, Task> callback, object state)
|
||||
{
|
||||
}
|
||||
|
||||
public void OnCompleted(Func<object, Task> callback, object state)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-6
@@ -26,6 +26,7 @@ public class GetRolesEndpointTests
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetRolesEndpoint _sut;
|
||||
private readonly RoleDtoFixture _roleDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRolesEndpointTests"/> class.
|
||||
@@ -51,15 +52,10 @@ public class GetRolesEndpointTests
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
RoleDto[]? returnedRoles = jsonDocument.RootElement.GetProperty("data").Deserialize<RoleDto[]>(CreateCaseInsensitiveOptions());
|
||||
RoleDto[]? returnedRoles = jsonDocument.RootElement.GetProperty("data").Deserialize<RoleDto[]>(_jsonOptions);
|
||||
Assert.Equal(expectedRoles.Select(role => role.RoleName), returnedRoles!.Select(role => role.RoleName));
|
||||
}
|
||||
|
||||
private static JsonSerializerOptions CreateCaseInsensitiveOptions()
|
||||
{
|
||||
return new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestRolesFromApi()
|
||||
{
|
||||
|
||||
+2
-1
@@ -26,6 +26,7 @@ public class GetLibrariesEndpointTests
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetLibrariesEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
|
||||
@@ -51,7 +52,7 @@ public class GetLibrariesEndpointTests
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
LibraryDto[]? returnedLibraries = jsonDocument.RootElement.GetProperty("data").Deserialize<LibraryDto[]>(new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||
LibraryDto[]? returnedLibraries = jsonDocument.RootElement.GetProperty("data").Deserialize<LibraryDto[]>(_jsonOptions);
|
||||
Assert.Equal(expectedLibraries.Select(library => library.Title), returnedLibraries!.Select(library => library.Title));
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -25,6 +25,7 @@ public class GetPluginsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetPluginsEndpoint _sut;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginsEndpointTests"/> class.
|
||||
@@ -50,7 +51,7 @@ public class GetPluginsEndpointTests
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
PluginDto[]? returnedPlugins = jsonDocument.RootElement.GetProperty("data").Deserialize<PluginDto[]>(new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||
PluginDto[]? returnedPlugins = jsonDocument.RootElement.GetProperty("data").Deserialize<PluginDto[]>(_jsonOptions);
|
||||
Assert.Equal(expectedPlugins.Select(plugin => plugin.Name), returnedPlugins!.Select(plugin => plugin.Name));
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user