diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Authentication/HttpContextCurrentUserServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Authentication/HttpContextCurrentUserServiceTests.cs index 9b91b3fa..5e4e3341 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Authentication/HttpContextCurrentUserServiceTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Authentication/HttpContextCurrentUserServiceTests.cs @@ -44,7 +44,10 @@ public class HttpContextCurrentUserServiceTests public void UserId_WhenUserIsNull_ShouldReturnNull() { // Arrange - HttpContext mockHttpContext = new DefaultHttpContext(); + HttpContext mockHttpContext = new DefaultHttpContext + { + User = null + }; _mockHttpContextAccessor.HttpContext.Returns(mockHttpContext); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs index 27697a5b..afcbea42 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NSubstitute; using System; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; @@ -85,6 +86,31 @@ public class ExceptionHandlingMiddlewareTests Arg.Any>()); } + [Fact] + public async Task InvokeAsync_WhenNextThrowsExceptionAndActivityIsCurrent_ShouldUseTheActivityIdAsTraceId() + { + // Arrange + using (Activity activity = new Activity("TestActivity")) + { + activity.Start(); + DefaultHttpContext context = new() + { + Response = { Body = new MemoryStream() } + }; + _nextDelegate = _ => throw new InvalidOperationException("sensitive internal details"); + + // Act + await _sut.InvokeAsync(context); + + // Assert + 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(activity.Id, problemDetails.Extensions["traceId"]?.ToString()); + } + } + [Fact] public async Task InvokeAsync_WhenNextThrowsOperationCanceledException_ShouldRethrow() { diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Utilities/MimeTypesTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Utilities/MimeTypesTests.cs new file mode 100644 index 00000000..50ad9587 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Utilities/MimeTypesTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Presentation.Api.Common.Utilities; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Common.Utilities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MimeTypesTests +{ + [Theory] + [InlineData(ImageType.BMP, "image/bmp")] // bmp image type + [InlineData(ImageType.JPEG, "image/jpeg")] // jpeg image type + [InlineData(ImageType.JPEG_CANON, "image/jpeg")] // canon jpeg image type + [InlineData(ImageType.SVG, "image/svg+xml")] // svg image type + [InlineData(ImageType.TGA, "image/x-tga")] // tga image type + public void GetMimeType_WhenTypeIsKnown_ShouldReturnTheMappedMimeType(ImageType type, string expectedMimeType) + { + // Act + string result = MimeTypes.GetMimeType(type); + + // Assert + Assert.Equal(expectedMimeType, result); + } + + [Theory] + [InlineData(ImageType.None)] // the none image type has no mime mapping + [InlineData((ImageType)999)] // an unknown image type has no mime mapping + public void GetMimeType_WhenTypeIsUnknown_ShouldReturnOpaqueBinaryMimeType(ImageType type) + { + // Act + string result = MimeTypes.GetMimeType(type); + + // Assert + Assert.Equal("application/octet-stream", result); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs index 2f382176..2148d262 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs @@ -6,6 +6,7 @@ using Lumina.Presentation.Api.Fixtures.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; #endregion @@ -182,4 +183,81 @@ public class BaseEndpointTests Assert.Equal(new[] { "Description1", "Description2" }, validationProblemDetails.Errors["Code1"]); Assert.Equal(new[] { "Description3" }, validationProblemDetails.Errors["Code2"]); } + + [Fact] + public void Problem_WhenCalledWithSingleUnauthorizedError_ShouldReturnForbiddenStatusCode() + { + // Act + IResult result = _sut.TestProblem([Error.Unauthorized("ErrorCode", "ErrorDescription")]); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + } + + [Fact] + public void Problem_WhenCalledWithSingleForbiddenError_ShouldReturnForbiddenStatusCode() + { + // Act + IResult result = _sut.TestProblem([Error.Forbidden("ErrorCode", "ErrorDescription")]); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + } + + [Fact] + public void Problem_WhenCalledWithMixedErrorsStartingWithValidation_ShouldReturnTheValidationStatusCode() + { + // Arrange + List errors = [ + Error.Validation("Code1", "Description1"), + Error.Conflict("Code2", "Description2") + ]; + + // Act + IResult result = _sut.TestProblem(errors); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + Assert.Equal("Code1", problemResult.ProblemDetails.Title); + } + + [Fact] + public void Problem_WhenActivityIsCurrent_ShouldUseTheActivityIdAsTraceId() + { + // Arrange + using (Activity activity = new Activity("TestActivity")) + { + activity.Start(); + List errors = [Error.NotFound("ErrorCode", "ErrorDescription")]; + + // Act + IResult result = _sut.TestProblem(errors); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(activity.Id, problemResult.ProblemDetails.Extensions["traceId"]); + } + } + + [Fact] + public void ValidationProblem_WhenActivityIsCurrent_ShouldUseTheActivityIdAsTraceId() + { + // Arrange + using (Activity activity = new Activity("TestActivity")) + { + activity.Start(); + List errors = [Error.Validation("Code1", "Description1")]; + + // Act + IResult result = _sut.TestValidationProblem(errors); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(activity.Id, validationProblemDetails.Extensions["traceId"]); + } + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs index dc9ca110..614fd2bb 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs @@ -1,10 +1,133 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; using System.Threading.Tasks; +#endregion namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook; -internal class AddBookEndpointTests + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddBookEndpointTests { + private readonly Lumina.Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly AddBookEndpoint _sut; + private readonly AddBookRequestFixture _addBookRequestFixture = new(); + private readonly BookResponseFixture _bookResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddBookEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithBookResponse() + { + // Arrange + AddBookRequest request = _addBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + BookResponse expectedResponse = _bookResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Created createdResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, createdResult.Value); + Assert.Contains(expectedResponse.Id.ToString(), createdResult.Location); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsConflictError_ShouldReturnProblemResult() + { + // Arrange + AddBookRequest request = _addBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Conflict("Book.AlreadyExists", "BookAlreadyExists"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status409Conflict, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status409Conflict, problemDetailsBody.Status); + Assert.Equal("Book.AlreadyExists", problemDetailsBody.Title); + Assert.Equal("BookAlreadyExists", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.10", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendAddBookCommandToHandler() + { + // Arrange + AddBookRequest request = _addBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_bookResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == request.LibraryId && + command.Path == request.Path), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + AddBookRequest request = _addBookRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_bookResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs index ec3878a6..4a1460b9 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs @@ -79,6 +79,38 @@ public class GetReadingResourceEndpointTests Assert.Equal("ResourceNotFound", problemResult.ProblemDetails.Detail); } + [Theory] + [InlineData("image/png", "image/png")] // a non-svg image is inert content + [InlineData("image/svg+xml", "application/octet-stream")] // an svg can be executed, so it is served as an opaque download + [InlineData("audio/mpeg", "audio/mpeg")] // audio is inert content + [InlineData("video/mp4", "video/mp4")] // video is inert content + [InlineData("font/woff2", "font/woff2")] // fonts are inert content + [InlineData("application/font-woff", "application/font-woff")] // legacy woff font media type + [InlineData("application/font-woff2", "application/font-woff2")] // legacy woff2 font media type + [InlineData("application/vnd.ms-opentype", "application/vnd.ms-opentype")] // opentype font media type + [InlineData("application/x-font-ttf", "application/x-font-ttf")] // ttf font media type + [InlineData("application/x-font-opentype", "application/x-font-opentype")] // otf font media type + [InlineData("text/css", "text/css")] // stylesheets are inert content + [InlineData("text/html", "application/octet-stream")] // an html document can be executed, so it is served as an opaque download + public async Task ExecuteAsync_WhenServingAResource_ShouldUseTheSafeContentType(string mimeType, string expectedContentType) + { + // Arrange + GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ReadingResourceDataDto response = new(Guid.NewGuid().ToByteArray(), mimeType); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + FileContentHttpResult bytesResult = Assert.IsType(result); + Assert.Equal(response.Data, bytesResult.FileContents); + Assert.Equal(expectedContentType, bytesResult.ContentType); + Assert.Equal("nosniff", _sut.HttpContext.Response.Headers["X-Content-Type-Options"]); + } + [Fact] public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingResourceQueryToSender() { diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs index e9871258..22d0c303 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs @@ -147,6 +147,27 @@ public class InstallPluginEndpointTests await Assert.ThrowsAnyAsync(() => operationTask); } + [Fact] + public async Task ExecuteAsync_WhenTheFormIsMalformed_ShouldTreatTheUploadAsMissingAndSendNullArchive() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + ConfigureMalformedForm(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Assert.IsType(result); + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Archive == null && + command.FileName == null), + Arg.Is(cancellationToken)); + } + private void ConfigureFormWithArchive(byte[] content, string fileName) { // the stream stays open for the duration of the test, since the endpoint reads it through the form file during execution @@ -155,8 +176,8 @@ public class InstallPluginEndpointTests FormFileCollection files = [formFile]; IFormCollection form = new FormCollection([], files); _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; - // a real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the - // request machinery, which would bypass a mocked feature and parse the (empty) request body + // A real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the + // request machinery, which would bypass a mocked feature and parse the (empty) request body. _sut.HttpContext.Features.Set(new FormFeature(form)); } @@ -166,4 +187,12 @@ public class InstallPluginEndpointTests _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; _sut.HttpContext.Features.Set(new FormFeature(form)); } + + private void ConfigureMalformedForm() + { + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + IFormCollection malformedForm = Substitute.For(); + malformedForm.Files.Returns(_ => throw new InvalidDataException("Malformed multipart body.")); + _sut.HttpContext.Features.Set(new FormFeature(malformedForm)); + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs index 65fe85bb..4a93b17d 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs @@ -156,6 +156,29 @@ public class InstallThemeEndpointTests await Assert.ThrowsAnyAsync(() => operationTask); } + [Fact] + public async Task ExecuteAsync_WhenTheFormIsMalformed_ShouldTreatTheUploadAsMissingAndSendNullArchive() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + ThemeResponse expectedResponse = _themeResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + ConfigureMalformedForm(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Archive == null && + command.FileName == null), + Arg.Is(cancellationToken)); + } + private void ConfigureFormWithArchive(byte[] content, string fileName) { // the stream stays open for the duration of the test, since the endpoint reads it through the form file during execution @@ -164,8 +187,8 @@ public class InstallThemeEndpointTests FormFileCollection files = [formFile]; IFormCollection form = new FormCollection([], files); _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; - // a real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the - // request machinery, which would bypass a mocked feature and parse the (empty) request body + // A real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the + // request machinery, which would bypass a mocked feature and parse the (empty) request body. _sut.HttpContext.Features.Set(new FormFeature(form)); } @@ -175,4 +198,12 @@ public class InstallThemeEndpointTests _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; _sut.HttpContext.Features.Set(new FormFeature(form)); } + + private void ConfigureMalformedForm() + { + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + IFormCollection malformedForm = Substitute.For(); + malformedForm.Files.Returns(_ => throw new InvalidDataException("Malformed multipart body.")); + _sut.HttpContext.Features.Set(new FormFeature(malformedForm)); + } }