diff --git a/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs b/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs new file mode 100644 index 00000000..d24f2e22 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs @@ -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; + +/// +/// Middleware that catches unhandled exceptions and converts them into a ProblemDetails response. +/// +public class ExceptionHandlingMiddleware +{ + private readonly RequestDelegate _next; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The next middleware in the request pipeline. + /// Injected service used for logging. + public ExceptionHandlingMiddleware(RequestDelegate next, ILogger logger) + { + _next = next; + _logger = logger; + } + + /// + /// Handles incoming requests and converts any unhandled exception into a ProblemDetails response. + /// + /// The for the current request. + 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); + } + } + + /// + /// Writes a generic ProblemDetails response, without exposing any internal exception details to the client. + /// + /// The for the current request. + 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); + } +} diff --git a/src/Lumina.Presentation.Api/Common/Utilities/ApiExceptionHandlingMiddlewareUtilities.cs b/src/Lumina.Presentation.Api/Common/Utilities/ApiExceptionHandlingMiddlewareUtilities.cs new file mode 100644 index 00000000..1862270c --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Utilities/ApiExceptionHandlingMiddlewareUtilities.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Common.Middlewares; +using Microsoft.AspNetCore.Builder; +#endregion + +namespace Lumina.Presentation.Api.Common.Utilities; + +/// +/// Extension methods for adding the to the request pipeline. +/// +public static class ApiExceptionHandlingMiddlewareUtilities +{ + /// + /// Adds the to the application's request pipeline, so that any unhandled exception is converted into a ProblemDetails response. + /// + /// The used to configure the application's request pipeline. + /// The for further configuration. + public static IApplicationBuilder UseApiExceptionHandling(this IApplicationBuilder builder) + { + return builder.UseMiddleware(); + } +} diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 0cd26d06..abe2bbd1 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -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(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs new file mode 100644 index 00000000..27697a5b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ExceptionHandlingMiddlewareTests +{ + private readonly ILogger _mockLogger; + private readonly ExceptionHandlingMiddleware _sut; + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private RequestDelegate _nextDelegate = context => Task.CompletedTask; + + /// + /// Initializes a new instance of the class. + /// + public ExceptionHandlingMiddlewareTests() + { + _mockLogger = Substitute.For>(); + _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(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(), + Arg.Any(), + Arg.Is(exception => exception is InvalidOperationException && exception.Message == "sensitive internal details"), + Arg.Any>()); + } + + [Fact] + public async Task InvokeAsync_WhenNextThrowsOperationCanceledException_ShouldRethrow() + { + // Arrange + DefaultHttpContext context = new() + { + Response = { Body = new MemoryStream() } + }; + _nextDelegate = _ => throw new OperationCanceledException(); + + // Act + await Assert.ThrowsAsync(() => _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(new StartedHttpResponseFeature()); + context.Response.Body = new MemoryStream(); + _nextDelegate = _ => throw new InvalidOperationException("sensitive internal details"); + + // Act + await Assert.ThrowsAsync(() => _sut.InvokeAsync(context)); + + // Assert + Assert.Equal(0, context.Response.Body.Length); + _mockLogger.DidNotReceive().Log( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any>()); + } + + [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); + } + + /// + /// Response feature that reports the response as already started, for simulating a response that cannot be replaced. + /// + 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 callback, object state) + { + } + + public void OnCompleted(Func callback, object state) + { + } + } +}